suppa-mcp-2 1.45.1 → 1.46.1

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.
package/README.md CHANGED
@@ -30,7 +30,7 @@ No API key needed to start — the server authenticates interactively via the `s
30
30
 
31
31
  ## The `suppa` command
32
32
 
33
- The same 108 operations the MCP server exposes are available as a command, for
33
+ The same 110 operations the MCP server exposes are available as a command, for
34
34
  shells, scripts and CI:
35
35
 
36
36
  ```bash
@@ -419,7 +419,7 @@ extension table is created outside that check and is not subject to it.
419
419
 
420
420
  ## Available tools
421
421
 
422
- 108 tools across the areas below.
422
+ 110 tools across the areas below.
423
423
 
424
424
  ### Session & identity
425
425
 
@@ -484,7 +484,7 @@ extension table is created outside that check and is not subject to it.
484
484
  | `suppa_list_entities` | List entities (tables) |
485
485
  | `suppa_describe_entity` | Field definitions + types for an entity (compact by default; `full=true` for the raw schema) |
486
486
  | `suppa_list_tabular_parts` | List tabular parts (ТЧ) of an entity |
487
- | `suppa_search_records` | Search / filter records in any entity — nested AND/OR groups, auto-diagnoses an empty result (`deleted_scope` finds soft-deleted rows) |
487
+ | `suppa_search_records` | Search / filter records in any entity — nested AND/OR groups, auto-diagnoses an empty result (`deleted_scope` finds soft-deleted rows); `order_by='custom_order(page, 12)'` reads the platform's manual order of a list |
488
488
  | `suppa_validate_select` | Check a select/filter payload against the entity without running it — names the field that does not resolve |
489
489
  | `suppa_query` | Run one read-only SuppaSQL statement (SELECT/WITH) with the caller's read permissions — check a SQL chart or table source before writing the form |
490
490
  | `suppa_sql_kb` | The SuppaSQL skill offline (`skills/writing-suppa-sql`): rules, cheat sheet, common mistakes, references by section, and `check` — what the platform refuses and the measured slow shapes a draft's text shows |
@@ -511,6 +511,8 @@ extension table is created outside that check and is not subject to it.
511
511
  | `suppa_delete_record` | Soft-delete a record — reversible (confirm-gated); permanent delete is blocked server-wide |
512
512
  | `suppa_restore_record` | Undo a soft delete: clear `deletedAt` on a record (confirm-gated) |
513
513
  | `suppa_copy_record` | Duplicate a record, optionally with its files / related records |
514
+ | `suppa_reorder_records` | Move records within any entity's manual order — a board column, a hierarchy's children; a hierarchy kept per owner orders its top level under the owner (`custom_order(page, 12)` for a page's blocks) and each parent's children under `custom_order(parent, <id>)`; rows checked with your rights first (confirm-gated) |
515
+ | `suppa_insert_record_at` | Create records at a place in any entity's manual order (before / after a record, first / last) |
514
516
  | `suppa_attach_file_to_record` | Attach a local file to any record |
515
517
  | `suppa_list_record_files` | List the files attached to a record |
516
518
  | `suppa_download_file` | Download one attachment (original, preview, or generated PDF) |
package/dist/cli/run.js CHANGED
@@ -92,7 +92,7 @@ function parseArgsObject(text, source) {
92
92
  return { error: `${source} is not valid JSON: ${e instanceof Error ? e.message : String(e)}` };
93
93
  }
94
94
  if (json === null || typeof json !== "object" || Array.isArray(json)) {
95
- return { error: `${source} must hold a JSON object of arguments ({"entity_name": "Tasks", …})` };
95
+ return { error: `${source} must hold a JSON object of arguments ({"entity_name": "Orders", …} — a hypothetical entity; use the tenant's own)` };
96
96
  }
97
97
  return { args: json };
98
98
  }
package/dist/server.js CHANGED
@@ -12,6 +12,7 @@ import { config } from "./config.js";
12
12
  import * as tasks from "./tools/tasks.js";
13
13
  import * as docs from "./tools/docs.js";
14
14
  import * as entity from "./tools/entity.js";
15
+ import * as recordOrder from "./tools/recordOrder.js";
15
16
  import * as customFields from "./tools/customFields.js";
16
17
  import * as customFieldSets from "./tools/customFieldSets.js";
17
18
  import * as customFieldsAsCode from "./tools/customFieldsAsCode.js";
@@ -142,6 +143,32 @@ const RecordValuesOrBatchJson = z
142
143
  .describe('JSON object of field values — or a JSON ARRAY of such objects to create many ' +
143
144
  'in one request. Relations/enums as {"id": N}, e.g. {"title": "X", ' +
144
145
  '"customer": {"id": 7}}; batch: [{"title": "A"}, {"title": "B"}].');
146
+ // The manual-order tools (suppa_reorder_records, suppa_insert_record_at): which
147
+ // list, where in it, and how the list is read. See tools/customOrder.ts.
148
+ const OrderContextField = z
149
+ .string()
150
+ .nullable()
151
+ .default(null)
152
+ .describe("The list's scoping field (many-to-one or enum), e.g. 'page'; null = the entity's own list.");
153
+ const OrderContextValue = z
154
+ .number()
155
+ .int()
156
+ .positive()
157
+ .nullable()
158
+ .default(null)
159
+ .describe("Id that scopes the list, e.g. the page id; null with a field = its empty group.");
160
+ const OrderWhereArg = z.enum(["before", "after", "first", "last"]);
161
+ const OrderAnchorId = z
162
+ .number()
163
+ .int()
164
+ .positive()
165
+ .nullable()
166
+ .default(null)
167
+ .describe("For before / after: a record of the same list.");
168
+ const OrderDirectionArg = z
169
+ .enum(["asc", "desc"])
170
+ .default("desc")
171
+ .describe("The direction you read the list in (default desc).");
145
172
  const MergeNamesJson = z
146
173
  .string()
147
174
  .nullable()
@@ -176,7 +203,7 @@ const BlocksJson = z
176
203
  'checkList|quote|callout|divider|code|table|toggle", "title": "text or HTML"}].');
177
204
  const EntityName = z
178
205
  .string()
179
- .describe("Exact entity name, e.g. 'Tasks' — discover via suppa_list_entities.");
206
+ .describe("Exact entity name as suppa_list_entities reports it (e.g. a hypothetical 'Orders').");
180
207
  /**
181
208
  * A field label: a plain string, or the LOCALIZATION OBJECT the builder doc
182
209
  * prescribes (`title | object | Localization object`, builder.txt:56).
@@ -334,7 +361,7 @@ ENTITY BUILDER (create + edit fields; core-field removal is UI-only) — suppa_a
334
361
  - OWNED CHILD COLLECTIONS ARE TABULAR PARTS: repeating rows that belong to ONE parent record (a part's BOM items) go through suppa_create_tabular_part(parent_entity, name), which creates the child's 'owner' relation and the parent link. Never model it by hand — suppa_add_field REFUSES field_type='one-to-many'; 'many-to-many' is for a shared lookup referenced by many records.
335
362
  - An enum value on a RECORD is a reference, {"id": <Enums row id>} (an array of those for multi-enum), never a bare code like "red" — that is refused. Read the ids with suppa_search_records on 'Enums' filtered by name.
336
363
 
337
- CUSTOM FIELDS — ANY entity, not just Tasks: one whose options.customFields is on (an admin enables it; suppa_describe_entity shows it) carries extra columns that vary BY CONTEXT, so which are live differs from record to record — suppa_resolve_custom_fields answers for a given record. Their values ride on the OWNER record under the reserved key customFields, e.g. fields_json {"customFields": {"budget": 600}}.
364
+ CUSTOM FIELDS — ANY entity: one whose options.customFields is on (an admin enables it; suppa_describe_entity shows it) carries extra columns that vary BY CONTEXT, so which are live differs from record to record — suppa_resolve_custom_fields answers for a given record. Their values ride on the OWNER record under the reserved key customFields, e.g. fields_json {"customFields": {"budget": 600}}.
338
365
 
339
366
  ${formV2.FORM_V2_INSTRUCTION_LINE}
340
367
 
@@ -567,14 +594,12 @@ export function buildToolTable() {
567
594
  return text(await tasks.closeTask(a.task_id));
568
595
  });
569
596
  reg("suppa_add_comment", {
570
- description: "Add a comment to a task. Supports HTML — plain text is auto-wrapped in <p>…</p>, so\n" +
571
- " start the string with < to pass raw markup. mention_ids: comma-separated\n" +
572
- " 'userId:Name' pairs for @mentions.",
597
+ description: "Add a comment to a task. Plain text is wrapped in <p>; a string starting with < is HTML.\n" +
598
+ " mention_ids: comma-separated 'userId:Name' pairs — one @mention each, in the first\n" +
599
+ " paragraph; a user the content already mentions is not added again.",
573
600
  inputSchema: {
574
601
  task_id: z.number().int(),
575
- content: z
576
- .string()
577
- .describe("Comment text; plain text is wrapped in <p>, raw HTML passes through."),
602
+ content: z.string().describe("Comment text or HTML."),
578
603
  mention_ids: z
579
604
  .string()
580
605
  .nullable()
@@ -960,6 +985,14 @@ export function buildToolTable() {
960
985
  " An EMPTY result (or a 400) is auto-diagnosed with select/validate: if the query\n" +
961
986
  ' references a field that does not exist you get "validation" naming it, not silence.\n' +
962
987
  " Returns {records, returned, has_more, next_offset, deleted_scope} — page with offset until has_more is false.\n\n" +
988
+ " MANUAL ORDER: order_by='custom_order(page, 12)' returns the rows of that list (any entity:\n" +
989
+ " context field, scoping record's id) in the order the platform keeps by hand; 'custom_order'\n" +
990
+ " = a flat entity's own list; ':asc' reads it reversed (default desc). A hierarchy kept per\n" +
991
+ " owner orders its top level under the owner (custom_order(page, 12): a page's top-level\n" +
992
+ " blocks), each parent's children under custom_order(parent, <id>); another hierarchy's top\n" +
993
+ ' level: custom_order(parent). Nested rows in order: {"children": "#expand_tree(10)"} in\n' +
994
+ " fields_json. Move rows with suppa_reorder_records; create at a place with\n" +
995
+ " suppa_insert_record_at.\n\n" +
963
996
  " Enum fields read back as objects {value, title, id} — project them as\n" +
964
997
  ' {"myEnum": {"value": true}} and read .value, not as a bare string.\n\n' +
965
998
  " SOFT-DELETED ROWS: deleted_scope='deleted' returns ONLY records that\n" +
@@ -969,7 +1002,7 @@ export function buildToolTable() {
969
1002
  inputSchema: {
970
1003
  entity_name: z
971
1004
  .string()
972
- .describe("Exact entity name, e.g. 'Tasks', 'Users' — see suppa_list_entities."),
1005
+ .describe("Exact entity name as suppa_list_entities reports it (e.g. a hypothetical 'Orders')."),
973
1006
  filters_json: z
974
1007
  .string()
975
1008
  .default("[]")
@@ -985,7 +1018,7 @@ export function buildToolTable() {
985
1018
  order_by: z
986
1019
  .string()
987
1020
  .default("createdAt:desc")
988
- .describe("'field:asc' or 'field:desc', e.g. 'createdAt:desc'."),
1021
+ .describe("'field:asc' or 'field:desc', e.g. 'createdAt:desc' — or 'custom_order(<field>, <id>)' for the manual order (see MANUAL ORDER)."),
989
1022
  match_any: z
990
1023
  .boolean()
991
1024
  .default(false)
@@ -1040,7 +1073,7 @@ export function buildToolTable() {
1040
1073
  inputSchema: {
1041
1074
  query: z
1042
1075
  .string()
1043
- .describe('The SuppaSQL statement, e.g. SELECT "stage.name", COUNT("id") AS "n" FROM Tasks GROUP BY "stage.name" LIMIT 100 — as a chart: sqlCategoryColumn "name", sqlValueColumns [{"key": "n"}].'),
1076
+ .describe('The SuppaSQL statement, e.g. SELECT "status.title", COUNT("id") AS "n" FROM Orders GROUP BY "status.title" LIMIT 100 (Orders is a hypothetical entity; use the one you found) — as a chart: sqlCategoryColumn "title", sqlValueColumns [{"key": "n"}].'),
1044
1077
  bind_params_json: z
1045
1078
  .string()
1046
1079
  .optional()
@@ -1313,7 +1346,7 @@ export function buildToolTable() {
1313
1346
  "platform's own docs say the backend never defaults them and every consumer " +
1314
1347
  "reads an absent key as FALSE — which is how agent-created fields ended up " +
1315
1348
  "non-groupable, unsortable and hidden from tables. The stored shape does look " +
1316
- "sparse: of 70 Tasks fields, 15 carry no options object at all. So if the new " +
1349
+ "sparse: of 70 fields on one live entity, 15 carry no options object at all. So if the new " +
1317
1350
  "field MUST be visible and sortable, pass the five explicitly rather than " +
1318
1351
  "trusting a default — it costs nothing — and read the field back afterwards. " +
1319
1352
  "Unknown keys are refused here (the platform would silently drop them)."),
@@ -1954,6 +1987,62 @@ export function buildToolTable() {
1954
1987
  },
1955
1988
  annotations: _ADD,
1956
1989
  }, async (a) => text(await entity.copyRecord(a.entity_name, a.record_id, a.fields_json, a.copy_files, a.copy_related_entities)));
1990
+ reg("suppa_reorder_records", {
1991
+ description: "Move records within an entity's MANUAL (hand-kept) order — page blocks, a hierarchy's children,\n" +
1992
+ " a board column. Changes no field, deletes nothing.\n\n" +
1993
+ " The order is per LIST: both null = the entity's own list; a hierarchy kept per owner keeps\n" +
1994
+ " its top level under the owner (PageBlocks of page 12 = context_field='page', context_value=12),\n" +
1995
+ " each parent's children under 'parent', <id>; another hierarchy's top level = 'parent', null.\n" +
1996
+ " Read it with suppa_search_records(order_by='custom_order(page, 12)'). record_ids land as one\n" +
1997
+ " block in the order given, before / after anchor_id or first / last. Refused before sending:\n" +
1998
+ " a record missing, not visible to you or in another list.\n\n" +
1999
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and changes nothing.",
2000
+ inputSchema: {
2001
+ entity_name: EntityName,
2002
+ record_ids: z.array(z.number().int().positive()).describe("Ids to move, in the order they should stand (at most 200)."),
2003
+ context_field: OrderContextField,
2004
+ context_value: OrderContextValue,
2005
+ where: OrderWhereArg,
2006
+ anchor_id: OrderAnchorId,
2007
+ direction: OrderDirectionArg,
2008
+ confirm: Confirm,
2009
+ },
2010
+ annotations: _MUT,
2011
+ }, async (a) => {
2012
+ // A move rearranges what other people see in a list, like suppa_reorder_blocks:
2013
+ // gated, and the preview reads nothing.
2014
+ if (!a.confirm) {
2015
+ return text(confirmRequired("reorder records", {
2016
+ entity_name: a.entity_name,
2017
+ record_ids: a.record_ids,
2018
+ context_field: a.context_field,
2019
+ context_value: a.context_value,
2020
+ where: a.where,
2021
+ anchor_id: a.anchor_id,
2022
+ direction: a.direction,
2023
+ }));
2024
+ }
2025
+ return text(await recordOrder.reorderRecords(a.entity_name, a.record_ids, a.context_field, a.context_value, a.where, a.anchor_id, a.direction));
2026
+ });
2027
+ reg("suppa_insert_record_at", {
2028
+ description: "Create records AT A PLACE in an entity's manual order — e.g. a page block after block 40:\n" +
2029
+ " entity_name='PageBlocks', context_field='page', context_value=12, where='after', anchor_id=40,\n" +
2030
+ ' fields_json=[{"type": "text", "properties": {"title": "<p>Hi</p>"}, "format": {"block_color": ""}}].\n\n' +
2031
+ " fields_json as in suppa_create_record (an array is placed as one block, in order); the context\n" +
2032
+ " field is filled in. The list and place work as in suppa_reorder_records; a bad anchor is\n" +
2033
+ " refused BEFORE anything is created. If only the placing fails, the answer has inserted_ids:\n" +
2034
+ " move them with suppa_reorder_records, never insert again.",
2035
+ inputSchema: {
2036
+ entity_name: EntityName,
2037
+ fields_json: RecordValuesOrBatchJson,
2038
+ context_field: OrderContextField,
2039
+ context_value: OrderContextValue,
2040
+ where: OrderWhereArg,
2041
+ anchor_id: OrderAnchorId,
2042
+ direction: OrderDirectionArg,
2043
+ },
2044
+ annotations: _ADD,
2045
+ }, async (a) => text(await recordOrder.insertRecordAt(a.entity_name, a.fields_json, a.context_field, a.context_value, a.where, a.anchor_id, a.direction)));
1957
2046
  reg("suppa_list_record_files", {
1958
2047
  description: "List the files attached to one record of any entity.\n" +
1959
2048
  "\n" +
package/dist/toolTable.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export const PROFILES = {
2
2
  core: ["login", "logout", "use_tenant", "list_tenants", "get_me", "health_check", "diagnostics", "version"],
3
- data: ["search_records", "get_record", "create_record", "update_record", "delete_record", "restore_record", "copy_record", "validate_select", "query", "sql_kb", "query_analyze", "search_entities", "list_entities", "describe_entity", "search_users"],
3
+ data: ["search_records", "get_record", "create_record", "update_record", "delete_record", "restore_record", "copy_record", "reorder_records", "insert_record_at", "validate_select", "query", "sql_kb", "query_analyze", "search_entities", "list_entities", "describe_entity", "search_users"],
4
4
  tasks: ["search_tasks", "get_task", "create_task", "update_task", "close_task", "delete_task", "move_task", "count_tasks", "list_stages", "list_task_types", "list_workflows", "add_comment", "get_comments", "create_workspace", "add_menu_item"],
5
5
  files: ["attach_file", "attach_file_to_record", "download_file", "download_files_zip", "list_record_files"],
6
6
  schema: ["create_entity", "add_field", "update_field", "change_field_type", "update_entity_options", "set_title_field", "create_tabular_part", "list_tabular_parts", "list_field_types", "add_enum_values", "add_custom_field", "add_custom_fields_batch", "remove_custom_field", "restore_custom_field", "resolve_custom_fields", "link_custom_field", "apply_custom_fields", "validate_entity_code", "migrate_entities_from_v1", "read_v1_entities", "read_v1_entity_props", "read_v1_enum"],
@@ -0,0 +1,307 @@
1
+ /**
2
+ * The platform's MANUAL order of records ("custom order") — for ANY entity.
3
+ *
4
+ * It is not a column. The platform keeps it in its own table, CustomOrders, one
5
+ * row per (entity, context field, context value, record), and exposes it two ways
6
+ * (entity-builder develop 1e8ea716d):
7
+ * - read: an orderBy entry {field, order, function: "custom_order", args: [value]}
8
+ * (core2 lower-custom-order.pass.ts; "#custom_order" is the same name —
9
+ * sql-safety.util.ts toSafeDslFunctionName strips the "#");
10
+ * - write: POST /api/core/data/custom-order/<Entity> with InstancesOrderDto
11
+ * (modules/entity/controllers/custom-order.controller.ts).
12
+ *
13
+ * The CONTEXT names the list: one parent's children are (parent, 40), a
14
+ * hierarchy's top level is (parent, null), a flat entity's own list is the global
15
+ * order (no field, no value). Reads express exactly these three; nothing reads a
16
+ * value without a field (assertReadableContext). A hierarchy that ALSO has an
17
+ * owner keeps its top level per owner: the top-level PageBlocks of page 12 are
18
+ * (page, 12) read with parent = null, the top-level Pages of doc 55 are (doc, 55)
19
+ * — the front reads and writes exactly these (pagesStore.ts loadDocPages, the
20
+ * page and block reorders), and nothing reads (parent, null) for them.
21
+ *
22
+ * Anchors are positions IN THE LIST THE READER SEES, read in `direction`, and the
23
+ * ids land as one block in the order given — InstancesOrderDto.direction ("relative
24
+ * to what the user sees … Absent ⇒ 'desc'") and
25
+ * test/integration/common/custom-order/custom-order-visible-order.e2e.spec.ts pin
26
+ * both. Nothing here inverts an anchor or reverses the ids.
27
+ */
28
+ import { makeRequest, searchEntity } from "../httpClient.js";
29
+ /**
30
+ * contextFieldName for the global order. The DTO requires a name, and the
31
+ * controller's (no field, no value) branch IS the global order — the front sends
32
+ * 'parent' for a flat table and relies on exactly that (custom-order.controller.ts
33
+ * assertReadableContext). orderContextRefusal guarantees the entity has no `parent`.
34
+ */
35
+ export const GLOBAL_CONTEXT_FIELD = "parent";
36
+ /** What the planner scopes a custom_order by (lower-custom-order.pass.ts: "must be an "enum" or "many-to-one" relation"). */
37
+ const CONTEXT_FIELD_TYPES = new Set(["many-to-one", "enum"]);
38
+ const ACCEPTED = "custom_order, custom_order(page, 12) or custom_order(parent), each optionally followed by :asc or :desc";
39
+ const CUSTOM_ORDER = /^custom_order\s*(?:\(\s*(?:"?([A-Za-z_][A-Za-z0-9_]*)"?\s*(?:,\s*(null|\d+)\s*)?)?\))?\s*(?::\s*([A-Za-z]+)\s*)?$/i;
40
+ /**
41
+ * An order_by that asks for the manual order, or null when it is a plain 'field:dir'.
42
+ * custom_order the entity's global order, desc
43
+ * custom_order(page, 2962) the list of page 2962
44
+ * custom_order(parent):asc a hierarchy's top level, read ascending
45
+ * Throws, naming the accepted forms, when it starts like one and is malformed.
46
+ */
47
+ export function parseCustomOrderBy(orderBy) {
48
+ const text = String(orderBy ?? "").trim();
49
+ if (!/^custom_order(?![A-Za-z0-9_])/i.test(text))
50
+ return null;
51
+ const m = CUSTOM_ORDER.exec(text);
52
+ if (!m)
53
+ throw new Error(`order_by '${text}' is not a manual-order read. Accepted: ${ACCEPTED}.`);
54
+ const [, field, rawValue, rawDir] = m;
55
+ const direction = (rawDir ?? "desc").toLowerCase();
56
+ if (direction !== "asc" && direction !== "desc") {
57
+ throw new Error(`order_by direction must be 'asc' or 'desc', got '${rawDir}'. Accepted: ${ACCEPTED}.`);
58
+ }
59
+ const value = rawValue === undefined || rawValue.toLowerCase() === "null" ? null : Number(rawValue);
60
+ if (value !== null && !isRecordId(value)) {
61
+ throw new Error(`order_by's context value must be a positive record id, got '${rawValue}'. Accepted: ${ACCEPTED}.`);
62
+ }
63
+ return { context: { field: field ?? null, value }, direction };
64
+ }
65
+ /** A record id: a positive, safe integer (the platform once stored contextValue = 0 for a missing value). */
66
+ export function isRecordId(n) {
67
+ return Number.isSafeInteger(n) && n > 0;
68
+ }
69
+ export function flip(direction) {
70
+ return direction === "desc" ? "asc" : "desc";
71
+ }
72
+ /**
73
+ * The orderBy of a read in that order. The custom-order entry goes FIRST:
74
+ * #expand_tree orders a row's children by their own parent's order only then
75
+ * (expand-tree.service.ts selectInParentOrder). The id entry breaks ties so offset
76
+ * paging is stable, and runs against the order so asc is exactly desc reversed.
77
+ */
78
+ export function customOrderBy(context, direction) {
79
+ const entry = {};
80
+ if (context.field !== null)
81
+ entry.field = context.field;
82
+ entry.order = direction;
83
+ entry.function = "custom_order";
84
+ if (context.field !== null && context.value !== null)
85
+ entry.args = [context.value];
86
+ return [entry, { field: "id", order: flip(direction) }];
87
+ }
88
+ /**
89
+ * The filters that keep a read to the rows of its list (a row outside it has no
90
+ * place in it) — with `topLevelField`, an owner list's top level only.
91
+ */
92
+ export function contextFilters(context, topLevelField = null) {
93
+ if (context.field === null)
94
+ return [];
95
+ const own = context.value === null
96
+ ? { field: context.field, comparator: "=", value: null }
97
+ : { field: `${context.field}.id`, comparator: "=", value: context.value };
98
+ return topLevelField === null ? [own] : [own, { field: topLevelField, comparator: "=", value: null }];
99
+ }
100
+ /** The order_by that reads this list back with suppa_search_records. */
101
+ export function orderByText(context, direction) {
102
+ const head = context.field === null
103
+ ? "custom_order"
104
+ : context.value === null
105
+ ? `custom_order(${context.field})`
106
+ : `custom_order(${context.field}, ${context.value})`;
107
+ return direction === "asc" ? `${head}:asc` : head;
108
+ }
109
+ /** Why this placement cannot be sent, or null. `anchorArg` names the anchor's argument in the answer. */
110
+ export function placementProblem(where, anchorId, movedIds, anchorArg = "anchor_id") {
111
+ const noAnchor = anchorId === null || anchorId === undefined;
112
+ if (where === "before" || where === "after") {
113
+ if (noAnchor)
114
+ return `where='${where}' needs ${anchorArg} — the id of a record of the same list.`;
115
+ if (!isRecordId(anchorId)) {
116
+ return `${anchorArg} must be a positive record id, got ${String(anchorId)}.`;
117
+ }
118
+ if (movedIds.includes(anchorId)) {
119
+ return `${anchorArg} ${anchorId} is one of the records being placed — anchor on a record that stays put.`;
120
+ }
121
+ return null;
122
+ }
123
+ if (where === "first" || where === "last") {
124
+ return noAnchor ? null : `where='${where}' takes no ${anchorArg} — leave it null, or use where='before'/'after'.`;
125
+ }
126
+ return `where must be 'before', 'after', 'first' or 'last', got '${String(where)}'.`;
127
+ }
128
+ /** The body of POST /api/core/data/custom-order/<Entity>. `updates` stays empty: the platform applies it as sudo. */
129
+ export function reorderBody(ids, context, direction, anchor) {
130
+ return {
131
+ instanceIds: [...ids],
132
+ contextFieldName: context.field ?? GLOBAL_CONTEXT_FIELD,
133
+ contextValue: context.value,
134
+ direction,
135
+ updates: {},
136
+ ...("beforeId" in anchor ? { beforeInstanceId: anchor.beforeId } : { afterInstanceId: anchor.afterId }),
137
+ };
138
+ }
139
+ function fieldsOf(schema) {
140
+ const fields = schema?.fields;
141
+ return Array.isArray(fields) ? fields.filter((f) => typeof f === "object" && f !== null) : [];
142
+ }
143
+ const carriesOrder = (f) => f.options?.customOrder === true;
144
+ /** The hierarchy field of an entity whose order is kept per parent. */
145
+ const HIERARCHY_FIELD = "parent";
146
+ /**
147
+ * The owners of a hierarchy kept per owner: the order-carrying many-to-one fields
148
+ * other than `parent` (Pages: doc, PageBlocks: page). Read from the schema, never
149
+ * from the entity's name; empty when the entity has no `parent` many-to-one.
150
+ */
151
+ function ownersOf(fields) {
152
+ const isManyToOne = (f) => String(f.type) === "many-to-one";
153
+ if (!fields.some((f) => f.name === HIERARCHY_FIELD && isManyToOne(f)))
154
+ return [];
155
+ return fields
156
+ .filter((f) => carriesOrder(f) && isManyToOne(f) && f.name !== HIERARCHY_FIELD && f.name !== "id")
157
+ .map((f) => String(f.name));
158
+ }
159
+ function perOwnerRefusal(entityName, owners) {
160
+ const top = owners.map((o) => `context_field='${o}', context_value=<${o} id> (custom_order(${o}, <id>))`).join(" or ");
161
+ return (`'${entityName}' is a hierarchy kept per ${owners.join(" / ")}: no list reads its global order or parent = null. ` +
162
+ `The top level is kept per owner — ${top}; one parent's children: ` +
163
+ "context_field='parent', context_value=<parent id> (custom_order(parent, <id>)).");
164
+ }
165
+ /**
166
+ * Why `context` cannot name a manual order of `entityName` — or, when it can, the
167
+ * list it names: an owner list of a hierarchy kept per owner carries its
168
+ * topLevelField, which contextFilters and listProblem apply. One GET
169
+ * /api/core/schema/<E>. Without it the platform answers a wrong context
170
+ * with "custom_order() expects a field name as its first argument, got a 'func'
171
+ * expression" (read live on Pages.title) — or, on a write, stores an order that
172
+ * no list ever reads.
173
+ */
174
+ export async function orderContextRefusal(entityName, context) {
175
+ const refuse = (refusal) => ({ refusal });
176
+ if (context.field === null && context.value !== null) {
177
+ return refuse("context_value needs a context_field: the platform keeps no list under a value without a field, " +
178
+ "and nothing could read it back. Name the field that scopes the list (e.g. 'page').");
179
+ }
180
+ if (context.value !== null && !isRecordId(context.value)) {
181
+ return refuse(`context_value must be a positive record id (or null for the field's empty group), got ${String(context.value)}.`);
182
+ }
183
+ let schema;
184
+ try {
185
+ // One path segment: a name with a '/' must not reach another endpoint.
186
+ schema = await makeRequest("GET", `/api/core/schema/${encodeURIComponent(entityName)}`);
187
+ }
188
+ catch (e) {
189
+ const msg = e instanceof Error ? e.message : String(e);
190
+ return refuse(`Refused: the schema of '${entityName}' could not be read (${msg}) — check the name with suppa_list_entities. Nothing was sent.`);
191
+ }
192
+ const fields = fieldsOf(schema);
193
+ if (!fields.some(carriesOrder)) {
194
+ return refuse(`'${entityName}' keeps no manual order: none of its fields carries options.customOrder.`);
195
+ }
196
+ const scoping = fields.filter((f) => carriesOrder(f) && f.name !== "id").map((f) => String(f.name));
197
+ const scopes = scoping.length ? scoping.join(", ") : "none — only its own list (no context)";
198
+ const owners = ownersOf(fields);
199
+ const list = (topLevelField = null) => ({ refusal: null, list: { context, topLevelField } });
200
+ if (context.field === null) {
201
+ const hierarchy = fields.find((f) => f.name === HIERARCHY_FIELD || f.name === "parents");
202
+ if (!hierarchy)
203
+ return list();
204
+ if (hierarchy.name === "parents") {
205
+ return refuse(`'${entityName}' is a multi-parent hierarchy: its manual order is kept per parent (parents), which this server does not read or write yet.`);
206
+ }
207
+ if (owners.length)
208
+ return refuse(perOwnerRefusal(entityName, owners));
209
+ return refuse(`'${entityName}' is a hierarchy: its manual order is kept per parent and no list reads a global one. ` +
210
+ "Name the field — context_field='parent' / custom_order(parent) for the top level, " +
211
+ "custom_order(parent, <id>) for one parent's children.");
212
+ }
213
+ const def = fields.find((f) => f.name === context.field);
214
+ if (!def)
215
+ return refuse(`'${entityName}' has no field '${context.field}'. Fields that scope its manual order: ${scopes}.`);
216
+ if (!CONTEXT_FIELD_TYPES.has(String(def.type))) {
217
+ return refuse(`'${context.field}' is a ${String(def.type)} field — a manual order is scoped only by a many-to-one ` +
218
+ `relation or an enum. Fields that scope it on '${entityName}': ${scopes}.`);
219
+ }
220
+ if (owners.length && context.field === HIERARCHY_FIELD && context.value === null) {
221
+ return refuse(perOwnerRefusal(entityName, owners));
222
+ }
223
+ return list(owners.includes(context.field) ? HIERARCHY_FIELD : null);
224
+ }
225
+ // ---------------------------------------------------------------------------
226
+ // Membership. The platform's custom-order write runs as sudo and checks no rights
227
+ // on the rows (custom-order.controller.ts updateRows), so every row a write moves,
228
+ // and every anchor, is read first WITH THE CALLER'S RIGHTS (active rows only).
229
+ // ---------------------------------------------------------------------------
230
+ /** One call moves or inserts at most this many records — one membership read covers them. */
231
+ export const MAX_ORDER_IDS = 200;
232
+ /** A record id from a bare id or a {id} reference; null for anything else. */
233
+ export function idOf(v) {
234
+ if (typeof v === "number" && Number.isInteger(v))
235
+ return v;
236
+ if (v !== null && typeof v === "object" && Number.isInteger(v.id))
237
+ return v.id;
238
+ return null;
239
+ }
240
+ /** Why `ids` cannot be the records of one move, or null. `arg` names the argument in the answer. */
241
+ export function idsProblem(ids, arg = "record_ids") {
242
+ if (!Array.isArray(ids) || ids.length === 0) {
243
+ return `${arg} is empty — pass the ids to move, in the order they should stand.`;
244
+ }
245
+ if (ids.length > MAX_ORDER_IDS)
246
+ return `${arg} has ${ids.length} ids; one call moves at most ${MAX_ORDER_IDS}.`;
247
+ const bad = ids.filter((n) => !isRecordId(n));
248
+ if (bad.length)
249
+ return `${arg} must be positive record ids; got ${JSON.stringify(bad)}.`;
250
+ if (new Set(ids).size !== ids.length)
251
+ return `${arg} names a record twice — each id once, in the order they should stand.`;
252
+ return null;
253
+ }
254
+ /** The fields a membership read of `list` projects: its context field, and the field its top level keeps empty. */
255
+ export function listFields(list) {
256
+ return [list.context.field, list.topLevelField].filter((f) => f !== null);
257
+ }
258
+ /** `ids` of `entity`, read with the caller's rights (active rows only), each of `fields` projected as {id}. */
259
+ export async function readOrderRows(entity, ids, fields) {
260
+ const projection = { id: true };
261
+ for (const f of fields)
262
+ projection[f] = { id: true };
263
+ const rows = (await searchEntity(entity, [{ field: "id", comparator: "in", value: ids }], projection, ids.length + 1, 0, [{ field: "id", order: "asc" }], "", "and", "active"));
264
+ return new Map(rows.map((r) => [r.id, r]));
265
+ }
266
+ /** Why the rows read (`byId`) do not all stand in `list`, or null. Pure; the reason only. */
267
+ export function listProblem(entity, list, ids, byId) {
268
+ const missing = ids.filter((id) => !byId.has(id));
269
+ if (missing.length) {
270
+ return `Records ${missing.join(", ")} of '${entity}' were not found — no such id, soft-deleted, or not visible to you.`;
271
+ }
272
+ const { field, value } = list.context;
273
+ if (field === null)
274
+ return null;
275
+ // An empty relation reads back as null. A field hidden by field permissions
276
+ // reads back ABSENT, and a related row the caller may not see comes back masked
277
+ // "*" (entity-builder lower-root-relations.pass.ts) — neither is "empty": never
278
+ // take them for standing in a list.
279
+ const readable = (row, f) => row !== undefined && Object.prototype.hasOwnProperty.call(row, f) && (row[f] === null || idOf(row[f]) !== null);
280
+ for (const f of listFields(list)) {
281
+ const unread = ids.filter((id) => !readable(byId.get(id), f));
282
+ if (unread.length) {
283
+ return `You cannot read '${f}' of records ${unread.join(", ")} of '${entity}' (hidden from you), so their list cannot be checked.`;
284
+ }
285
+ }
286
+ const foreign = ids.filter((id) => idOf(byId.get(id)?.[field] ?? null) !== value);
287
+ if (foreign.length) {
288
+ const where = value === null ? `${field} is empty` : `${field} = ${value}`;
289
+ return `Records ${foreign.join(", ")} do not stand in the list ${where} — a record is placed only among the records of its own list.`;
290
+ }
291
+ const top = list.topLevelField;
292
+ if (top === null)
293
+ return null;
294
+ const nested = ids
295
+ .map((id) => [id, idOf(byId.get(id)?.[top] ?? null)])
296
+ .filter((p) => p[1] !== null);
297
+ if (!nested.length)
298
+ return null;
299
+ return (`Records ${nested.map(([id, parent]) => `${id} (its list: custom_order(${top}, ${parent}))`).join(", ")} are nested: ` +
300
+ `the list ${field} = ${String(value)} holds the top level only; a nested record stands in its own parent's list — ` +
301
+ `context_field='${top}', context_value=<that parent's id>.`);
302
+ }
303
+ /** Why `ids` cannot be placed in `list`, or null. One read, with the caller's rights. */
304
+ export async function membershipRefusal(entity, list, ids) {
305
+ const why = listProblem(entity, list, ids, await readOrderRows(entity, ids, listFields(list)));
306
+ return why === null ? null : `${why} Nothing was sent.`;
307
+ }
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { makeRequest, dataUrl, customOrderUrl, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
12
12
  import { ownProjection, registerOwnProjections } from "../projection.js";
13
+ import { idOf, idsProblem, listProblem, membershipRefusal, placementProblem, readOrderRows, reorderBody, } from "./customOrder.js";
13
14
  import { makeFilter, writeOutcome, stripHtml, jsonResponse, wrapHtml, unescapeUnicode, parseJsonParam, parseProjectionParam, notFoundAnswer, } from "../utils.js";
14
15
  // ---------------------------------------------------------------------------
15
16
  // Constants
@@ -245,6 +246,15 @@ export function _flattenBlockTree(rows, _seen = null) {
245
246
  }
246
247
  return out;
247
248
  }
249
+ /**
250
+ * The list a page's top-level blocks stand in, as the front keeps it: (page, P)
251
+ * with parent empty. A block's children stand in (parent, X) — pagesStore.ts,
252
+ * the block reorders. The custom-order write is sudo and checks no rights, so the
253
+ * block tools read the rows they place, and the anchor, against this list first.
254
+ */
255
+ function topLevelBlocks(pageId) {
256
+ return { context: { field: "page", value: pageId }, topLevelField: "parent" };
257
+ }
248
258
  /** Fetch a page's blocks in custom (display) order (used by getBlocks/readPage). */
249
259
  async function _fetchBlocks(pageId) {
250
260
  const body = {
@@ -484,6 +494,18 @@ export async function insertBlock(pageId, blocksJson, afterId = null, beforeId =
484
494
  catch (e) {
485
495
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
486
496
  }
497
+ // The new blocks stand at the page's top level (_blocksFromJson sets page, never
498
+ // parent), so the anchor must be a top-level block of this page — read with the
499
+ // caller's rights BEFORE the create, so a refusal leaves nothing behind.
500
+ const anchorId = (afterId || beforeId);
501
+ const anchorArg = afterId ? "after_id" : "before_id";
502
+ const notHere = placementProblem(afterId ? "after" : "before", anchorId, [], anchorArg) ??
503
+ (await membershipRefusal(ENTITY_PAGE_BLOCKS, topLevelBlocks(pageId), [anchorId]));
504
+ if (notHere) {
505
+ return jsonResponse({
506
+ error: `${notHere} suppa_insert_block creates top-level blocks of page ${pageId}: ${anchorArg} must be one of those.`,
507
+ });
508
+ }
487
509
  const res = await makeRequest("POST", dataUrl(ENTITY_PAGE_BLOCKS, "insert"), {
488
510
  fields: payload,
489
511
  returning: { id: true, type: true },
@@ -498,24 +520,15 @@ export async function insertBlock(pageId, blocksJson, afterId = null, beforeId =
498
520
  if (newIds.length === 0) {
499
521
  return jsonResponse({ error: "Insert returned no block ids; nothing to position.", raw: res });
500
522
  }
501
- // Reorder — API reverses multi-block order, so we always reverse
502
- const reorderBody = {
503
- instanceIds: [...newIds].reverse(),
504
- contextFieldName: "page",
505
- contextValue: pageId,
506
- updates: {},
507
- };
508
- if (afterId) {
509
- reorderBody.beforeInstanceId = afterId;
510
- }
511
- else if (beforeId) {
512
- reorderBody.afterInstanceId = beforeId;
513
- }
523
+ // Anchors as the editor sends them (front pageBlocksAdapter.ts): the side the
524
+ // reader sees, ids in the order given, read desc — customOrder.ts F3.
525
+ const anchor = afterId ? { afterId } : { beforeId: beforeId };
526
+ const orderBody = reorderBody(newIds, { field: "page", value: pageId }, "desc", anchor);
514
527
  // The blocks already exist at this point. If only the positioning fails,
515
528
  // report partial success with the ids — raising would hide the insert and
516
529
  // bait the agent into retrying, which duplicates the blocks.
517
530
  try {
518
- await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), reorderBody);
531
+ await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), orderBody);
519
532
  }
520
533
  catch (e) {
521
534
  const msg = e instanceof Error ? e.message : String(e);
@@ -635,19 +648,27 @@ export async function reorderBlocks(pageId, blockIds, afterId = null, beforeId =
635
648
  if (ids.length === 0) {
636
649
  return jsonResponse({ error: "block_ids is empty — pass at least one block id." });
637
650
  }
638
- // API reverses multi-block order, so we always reverse
639
- const body = {
640
- instanceIds: [...ids].reverse(),
641
- contextFieldName: "page",
642
- contextValue: pageId,
643
- updates: {},
644
- };
645
- if (afterId) {
646
- body.beforeInstanceId = afterId;
647
- }
648
- else if (beforeId) {
649
- body.afterInstanceId = beforeId;
650
- }
651
+ const anchorId = (afterId || beforeId);
652
+ const problem = idsProblem(ids, "block_ids") ??
653
+ placementProblem(afterId ? "after" : "before", anchorId, ids, afterId ? "after_id" : "before_id");
654
+ if (problem)
655
+ return jsonResponse({ error: problem });
656
+ // One read of the blocks and the anchor, with the caller's rights. The first
657
+ // block names the list — the page's top level, or one block's children — and
658
+ // every block and the anchor must stand in it, on this page.
659
+ const all = [...ids, anchorId];
660
+ const rows = await readOrderRows(ENTITY_PAGE_BLOCKS, all, ["page", "parent"]);
661
+ const parentId = idOf(rows.get(ids[0])?.parent ?? null);
662
+ const list = parentId === null ? topLevelBlocks(pageId) : { context: { field: "parent", value: parentId }, topLevelField: null };
663
+ const offPage = all.filter((id) => rows.has(id) && idOf(rows.get(id)?.page ?? null) !== pageId);
664
+ const why = listProblem(ENTITY_PAGE_BLOCKS, list, all, rows) ??
665
+ (offPage.length ? `Blocks ${offPage.join(", ")} are not on page ${pageId}.` : null);
666
+ if (why)
667
+ return jsonResponse({ error: `${why} Nothing was sent.` });
668
+ // Anchors as the editor sends them (front pageBlocksAdapter.ts): the side the
669
+ // reader sees, ids in the order given, read desc — customOrder.ts F3.
670
+ const anchor = afterId ? { afterId } : { beforeId: beforeId };
671
+ const body = reorderBody(ids, list.context, "desc", anchor);
651
672
  await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), body);
652
673
  return jsonResponse({
653
674
  reordered: ids,
@@ -21,6 +21,7 @@ import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListPro
21
21
  import { compactEntitySchema, slimTitle, titleLanguages } from "../readEconomy.js";
22
22
  import { customFieldsHint } from "../customFieldHints.js";
23
23
  import { transliterationProblem, untranslatedTokens } from "./nameMap.js";
24
+ import { contextFilters, customOrderBy, orderByText, orderContextRefusal, parseCustomOrderBy, } from "./customOrder.js";
24
25
  // Builder field types that accept file uploads.
25
26
  export const FILE_FIELD_TYPES = ["file", "multi-file"];
26
27
  export const RELATION_FIELD_TYPES = [
@@ -894,16 +895,45 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
894
895
  }
895
896
  fields = proj.fields;
896
897
  }
897
- const idx = orderBy.indexOf(":");
898
- const field = idx === -1 ? orderBy : orderBy.slice(0, idx);
899
- const rawDir = idx === -1 ? "" : orderBy.slice(idx + 1);
900
- const direction = rawDir.trim().toLowerCase() || "desc";
901
- if (direction !== "asc" && direction !== "desc") {
902
- return jsonResponse({
903
- error: `order_by direction must be 'asc' or 'desc', got '${direction}'.`,
904
- });
898
+ // order_by is either 'field:dir' or a read of the platform's MANUAL order,
899
+ // custom_order(<field>, <id>) — see customOrder.ts for what that list is.
900
+ let custom;
901
+ try {
902
+ custom = parseCustomOrderBy(orderBy);
903
+ }
904
+ catch (e) {
905
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e), records: [], returned: 0 });
906
+ }
907
+ let order;
908
+ if (custom) {
909
+ const check = await orderContextRefusal(entityName, custom.context);
910
+ if (check.refusal !== null) {
911
+ return jsonResponse({ error: check.refusal, records: [], returned: 0 });
912
+ }
913
+ order = customOrderBy(custom.context, custom.direction);
914
+ // The read is the rows OF that list: one outside it has no place in it and
915
+ // would sort by its creation time among the rest — and an owner list of a
916
+ // hierarchy kept per owner holds its top level only (parent = null). ANDed
917
+ // with the caller's filters even under match_any, which keeps its OR among them.
918
+ const scoped = contextFilters(check.list.context, check.list.topLevelField);
919
+ if (scoped.length) {
920
+ const own = filters;
921
+ filters = matchAny && own.length > 0 ? [{ operator: "or", filters: own }, ...scoped] : [...own, ...scoped];
922
+ matchAny = false;
923
+ }
924
+ }
925
+ else {
926
+ const idx = orderBy.indexOf(":");
927
+ const field = idx === -1 ? orderBy : orderBy.slice(0, idx);
928
+ const rawDir = idx === -1 ? "" : orderBy.slice(idx + 1);
929
+ const direction = rawDir.trim().toLowerCase() || "desc";
930
+ if (direction !== "asc" && direction !== "desc") {
931
+ return jsonResponse({
932
+ error: `order_by direction must be 'asc' or 'desc', got '${direction}'.`,
933
+ });
934
+ }
935
+ order = [{ field: field.trim() || "createdAt", order: direction }];
905
936
  }
906
- const order = [{ field: field.trim() || "createdAt", order: direction }];
907
937
  // Fetch one extra row so the agent learns whether another page exists.
908
938
  // Cap at 500/page: larger responses blow the model's context — page instead.
909
939
  limit = Math.max(1, Math.min(limit, 500));
@@ -968,6 +998,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
968
998
  Object.assign(out, diag);
969
999
  }
970
1000
  }
1001
+ if (custom) {
1002
+ out.custom_order = {
1003
+ context_field: custom.context.field,
1004
+ context_value: custom.context.value,
1005
+ direction: custom.direction,
1006
+ order_by: orderByText(custom.context, custom.direction),
1007
+ };
1008
+ }
971
1009
  return jsonResponse(out);
972
1010
  }
973
1011
  /**
@@ -2466,8 +2504,8 @@ async function _updateField(entityName, fieldName, opts, checkOnly) {
2466
2504
  notApplicable.push(`defaultValue was sent as the plain string ${JSON.stringify(body.defaultValue)} on ` +
2467
2505
  `'${fieldName}', which is a '${liveType}' — a default on a relation/enum/file field is a ` +
2468
2506
  "REFERENCE: `{ id }`, or `[{ id }, …]` for a multi (a Users relation also takes the " +
2469
- "`$current-user` token). Live examples on a tenant: `Tasks.priority` (enum) holds the " +
2470
- "Enums row id, `Tasks.createdBy` (many-to-one) holds `$current-user`. Read the field " +
2507
+ "`$current-user` token). An enum field holds the " +
2508
+ "Enums row id; a many-to-one to Users may hold `$current-user`. Read the field " +
2471
2509
  "back to check what was stored.");
2472
2510
  }
2473
2511
  }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * suppa_reorder_records and suppa_insert_record_at — the generic writes of the
3
+ * platform's manual order. The contract (context, anchors, direction) is
4
+ * customOrder.ts; this file adds what a write needs around it.
5
+ *
6
+ * The platform's custom-order write runs as sudo and checks no rights on the rows
7
+ * (custom-order.controller.ts updateRows, CustomOrderService.setOrder). So every
8
+ * row a call moves, and every anchor, is read first WITH THE CALLER'S RIGHTS, and
9
+ * a row that is missing, soft-deleted, not visible or in another list is refused
10
+ * before anything is sent.
11
+ */
12
+ import { customOrderUrl, makeRequest, searchEntity } from "../httpClient.js";
13
+ import { jsonResponse, parseJsonParam } from "../utils.js";
14
+ import { createRecord } from "./entity.js";
15
+ import { contextFilters, customOrderBy, flip, idOf, idsProblem, listFields, listProblem, MAX_ORDER_IDS, membershipRefusal, orderByText, orderContextRefusal, placementProblem, readOrderRows, reorderBody, } from "./customOrder.js";
16
+ function refuse(error) {
17
+ return jsonResponse({ error });
18
+ }
19
+ /** The first (or last) record of the list as the reader sees it, other than `exclude`; null when there is none. */
20
+ async function edgeAnchor(entity, list, direction, edge, exclude) {
21
+ const filters = [...contextFilters(list.context, list.topLevelField)];
22
+ if (exclude.length)
23
+ filters.push({ field: "id", comparator: "not in", value: exclude });
24
+ const rows = (await searchEntity(entity, filters, { id: true }, 1, 0, customOrderBy(list.context, edge === "first" ? direction : flip(direction))));
25
+ return idOf(rows[0]?.id ?? null);
26
+ }
27
+ async function resolveAnchor(entity, list, direction, where, anchorId, exclude) {
28
+ if (where === "before")
29
+ return { beforeId: anchorId };
30
+ if (where === "after")
31
+ return { afterId: anchorId };
32
+ const edge = await edgeAnchor(entity, list, direction, where, exclude);
33
+ if (edge === null)
34
+ return null;
35
+ return where === "first" ? { beforeId: edge } : { afterId: edge };
36
+ }
37
+ /** Send one order write. True when the platform answered that the order row already exists. */
38
+ async function sendOrder(entity, body) {
39
+ try {
40
+ await makeRequest("POST", customOrderUrl(entity), body);
41
+ return false;
42
+ }
43
+ catch (e) {
44
+ // Not idempotent: a send whose answer was lost and is sent again comes back
45
+ // 409 "Another Custom Order with the same combination already exists" — the
46
+ // unique index CustomOrdersEntityIdFieldIdValueInstanceIdUIndex. The front
47
+ // treats it as done (pageBlocksAdapter.ts reorder()), but the row it found may
48
+ // also be another writer's, so it is said, never passed off as a fresh write.
49
+ const msg = e instanceof Error ? e.message : String(e);
50
+ if (/HTTP 409/.test(msg) && /same combination already exists/i.test(msg))
51
+ return true;
52
+ throw e;
53
+ }
54
+ }
55
+ /**
56
+ * Write the order of `ids` at `anchor`. With no anchor the list holds nothing
57
+ * else: the ids are ordered among themselves (ids[1..] after ids[0]), and one id
58
+ * alone needs no write.
59
+ */
60
+ async function place(entity, context, direction, ids, anchor) {
61
+ if (anchor) {
62
+ return { anchor, alreadyWritten: await sendOrder(entity, reorderBody(ids, context, direction, anchor)) };
63
+ }
64
+ if (ids.length < 2)
65
+ return { anchor: null, alreadyWritten: false };
66
+ const first = { afterId: ids[0] };
67
+ return { anchor: first, alreadyWritten: await sendOrder(entity, reorderBody(ids.slice(1), context, direction, first)) };
68
+ }
69
+ /** The anchor used, and a 409 said out loud. */
70
+ function placedAnswer({ anchor, alreadyWritten }) {
71
+ const out = anchor === null ? {} : "beforeId" in anchor ? { before_id: anchor.beforeId } : { after_id: anchor.afterId };
72
+ if (alreadyWritten) {
73
+ out.already_written = true;
74
+ out.note =
75
+ "The platform answered 409 'same combination already exists': an order row for these records was already " +
76
+ "there — a retried send of this write, or another writer's. Read back with read_back to confirm the order.";
77
+ }
78
+ return out;
79
+ }
80
+ /** The exact suppa_reorder_records call that places `ids` the way this call meant to. */
81
+ function reorderCall(entity, ids, context, where, anchorId, direction) {
82
+ const arg = (v) => JSON.stringify(v ?? null);
83
+ return (`suppa_reorder_records(entity_name=${arg(entity)}, record_ids=${arg(ids)}, context_field=${arg(context.field)}, ` +
84
+ `context_value=${arg(context.value)}, where=${arg(where)}, anchor_id=${arg(anchorId)}, direction=${arg(direction)})`);
85
+ }
86
+ /** Where rows with no order row of their own stand in a list read in `direction` (F4: desc reads them last). */
87
+ function unplacedSide(direction) {
88
+ return direction === "desc" ? "read last in the list (desc)" : "read first in the list (asc)";
89
+ }
90
+ /** Move existing records of `entityName` within one manual-order list. */
91
+ export async function reorderRecords(entityName, recordIds, contextField, contextValue, where, anchorId, direction = "desc") {
92
+ const context = { field: contextField ?? null, value: contextValue ?? null };
93
+ const problem = idsProblem(recordIds) ?? placementProblem(where, anchorId ?? null, recordIds);
94
+ if (problem)
95
+ return refuse(problem);
96
+ const check = await orderContextRefusal(entityName, context);
97
+ if (check.refusal !== null)
98
+ return refuse(check.refusal);
99
+ const { list } = check;
100
+ const toCheck = anchorId === null || anchorId === undefined ? [...recordIds] : [...recordIds, anchorId];
101
+ const notHere = await membershipRefusal(entityName, list, toCheck);
102
+ if (notHere)
103
+ return refuse(notHere);
104
+ const anchor = await resolveAnchor(entityName, list, direction, where, anchorId ?? null, recordIds);
105
+ const placed = await place(entityName, context, direction, recordIds, anchor);
106
+ return jsonResponse({
107
+ reordered: placed.anchor === null ? [] : recordIds,
108
+ entity: entityName,
109
+ context_field: context.field,
110
+ context_value: context.value,
111
+ direction,
112
+ ...placedAnswer(placed),
113
+ ...(placed.anchor === null ? { note: "Nothing else stands in that list — a single record has no place to move to." } : {}),
114
+ read_back: orderByText(context, direction),
115
+ });
116
+ }
117
+ /**
118
+ * Create records of `entityName` at a place in one manual-order list. Everything
119
+ * that can be refused is refused BEFORE the create — the context, a record that
120
+ * names another list, an anchor that is missing or elsewhere — so a refusal never
121
+ * leaves a stray record. After the create, the new rows are checked to stand in
122
+ * the list before they are placed; if they do not, or only the placing fails,
123
+ * the records exist and the answer says so, with their ids and the exact
124
+ * suppa_reorder_records call that places them.
125
+ */
126
+ export async function insertRecordAt(entityName, fieldsJson, contextField, contextValue, where, anchorId, direction = "desc") {
127
+ const context = { field: contextField ?? null, value: contextValue ?? null };
128
+ let parsed;
129
+ try {
130
+ parsed = parseJsonParam(fieldsJson, "fields_json");
131
+ }
132
+ catch (e) {
133
+ return refuse(e instanceof Error ? e.message : String(e));
134
+ }
135
+ const rows = (Array.isArray(parsed) ? parsed : [parsed]);
136
+ if (rows.length === 0)
137
+ return refuse("fields_json is an empty array — nothing to insert.");
138
+ if (rows.length > MAX_ORDER_IDS)
139
+ return refuse(`fields_json has ${rows.length} records; one call inserts at most ${MAX_ORDER_IDS}.`);
140
+ const bad = rows.findIndex((r) => r === null || typeof r !== "object" || Array.isArray(r));
141
+ if (bad !== -1)
142
+ return refuse(`fields_json[${bad}] must be a JSON object of field values.`);
143
+ const problem = placementProblem(where, anchorId ?? null, []);
144
+ if (problem)
145
+ return refuse(problem);
146
+ const check = await orderContextRefusal(entityName, context);
147
+ if (check.refusal !== null)
148
+ return refuse(check.refusal);
149
+ const { list } = check;
150
+ // A record placed in a list must stand in it: the context field is filled in
151
+ // when a record leaves it out, and a record that names another list is refused.
152
+ const records = rows.map((r) => ({ ...r }));
153
+ if (context.field !== null) {
154
+ for (const [i, r] of records.entries()) {
155
+ const given = r[context.field];
156
+ if (given === undefined) {
157
+ if (context.value !== null)
158
+ r[context.field] = { id: context.value };
159
+ continue;
160
+ }
161
+ if (idOf(given) !== context.value) {
162
+ return refuse(`fields_json[${i}].${context.field} is ${JSON.stringify(given)}, but the list is ` +
163
+ `${context.field} = ${String(context.value)} — a record inserted there must stand in it. Nothing was inserted.`);
164
+ }
165
+ }
166
+ }
167
+ // An owner list holds the top level: a record with a parent belongs to that parent's list.
168
+ const top = list.topLevelField;
169
+ if (top !== null) {
170
+ const i = records.findIndex((r) => idOf(r[top] ?? null) !== null);
171
+ if (i !== -1) {
172
+ const parent = idOf(records[i][top]);
173
+ return refuse(`fields_json[${i}].${top} is ${JSON.stringify(records[i][top])}: the list ${String(context.field)} = ` +
174
+ `${String(context.value)} holds the top level only, and a record with a ${top} stands in that ${top}'s list — ` +
175
+ `insert it with context_field='${top}', context_value=${parent}. Nothing was inserted.`);
176
+ }
177
+ }
178
+ if (anchorId !== null && anchorId !== undefined) {
179
+ const notHere = await membershipRefusal(entityName, list, [anchorId]);
180
+ if (notHere)
181
+ return refuse(notHere);
182
+ }
183
+ const anchor = await resolveAnchor(entityName, list, direction, where, anchorId ?? null, []);
184
+ const created = JSON.parse(await createRecord(entityName, JSON.stringify(records)));
185
+ const ids = Array.isArray(created.records)
186
+ ? created.records.map((r) => idOf(r)).filter((n) => n !== null)
187
+ : [];
188
+ if (ids.length === 0)
189
+ return jsonResponse(created); // a refusal, or nothing came back: nothing to place
190
+ const notes = createNotes(created);
191
+ const recovery = reorderCall(entityName, ids, context, where, anchorId ?? null, direction);
192
+ // The new rows must stand in the list before an order row is written for them.
193
+ const outside = await createdOutsideList(entityName, list, ids, created.records);
194
+ if (outside) {
195
+ return jsonResponse({
196
+ inserted_ids: ids,
197
+ entity: entityName,
198
+ placed: false,
199
+ warning: `The records were created but NOT placed: ${outside} An order row would go into a list they do not stand ` +
200
+ `in. Do NOT insert them again — check them with suppa_search_records; once they stand in the list, place ` +
201
+ `them with ${recovery}.`,
202
+ ...notes,
203
+ });
204
+ }
205
+ try {
206
+ const placed = await place(entityName, context, direction, ids, anchor);
207
+ return jsonResponse({
208
+ inserted_ids: ids,
209
+ entity: entityName,
210
+ context_field: context.field,
211
+ context_value: context.value,
212
+ direction,
213
+ ...placedAnswer(placed),
214
+ read_back: orderByText(context, direction),
215
+ ...notes,
216
+ });
217
+ }
218
+ catch (e) {
219
+ const msg = e instanceof Error ? e.message : String(e);
220
+ return jsonResponse({
221
+ inserted_ids: ids,
222
+ entity: entityName,
223
+ warning: `The records were created but placing them failed: ${msg}. With no place of their own yet they ` +
224
+ `${unplacedSide(direction)}. Do NOT insert them again — place them with ${recovery}.`,
225
+ ...notes,
226
+ });
227
+ }
228
+ }
229
+ /**
230
+ * Why the created rows do not stand in `list`, or null. A platform default or a
231
+ * hook can put a record elsewhere, and a context field the caller may not write
232
+ * is dropped. The create's answer shows the fields it was sent; when it does not
233
+ * show every list field, the rows are read back with the caller's rights.
234
+ */
235
+ async function createdOutsideList(entity, list, ids, answered) {
236
+ if (list.context.field === null)
237
+ return null; // the entity's own list holds every row
238
+ const fields = listFields(list);
239
+ const rows = (Array.isArray(answered) ? answered : []).filter((r) => r !== null && typeof r === "object");
240
+ const shown = rows.length === ids.length && rows.every((r) => fields.every((f) => Object.prototype.hasOwnProperty.call(r, f)));
241
+ if (shown)
242
+ return listProblem(entity, list, ids, new Map(rows.map((r) => [r.id, r])));
243
+ try {
244
+ return listProblem(entity, list, ids, await readOrderRows(entity, ids, fields));
245
+ }
246
+ catch (e) {
247
+ return `they could not be read back to check their list (${e instanceof Error ? e.message : String(e)}).`;
248
+ }
249
+ }
250
+ /**
251
+ * What suppa_create_record says about the same write and an insert at a place
252
+ * must not drop: a wrong-group enum value, a direct write to a custom-values
253
+ * table, and fewer rows created than requested.
254
+ */
255
+ function createNotes(created) {
256
+ const notes = {};
257
+ if (created.enum_group_warning)
258
+ notes.enum_group_warning = created.enum_group_warning;
259
+ if (created.direct_extension_write_warning)
260
+ notes.direct_extension_write_warning = created.direct_extension_write_warning;
261
+ if (typeof created.created === "number" && created.created !== created.requested) {
262
+ notes.created = created.created;
263
+ notes.requested = created.requested;
264
+ }
265
+ return notes;
266
+ }
@@ -396,25 +396,80 @@ async function _resolveCurrentUserId() {
396
396
  }
397
397
  throw new Error("Could not resolve current user id");
398
398
  }
399
- /** Add a comment to a task. Content supports HTML. mention_ids: comma-separated 'id:Name' pairs. */
399
+ /** The user ids a comment's HTML already mentions — `<a class="mention-user" data-id="…">`, the markup the
400
+ * platform reads mentions from (entity-builder common/utils/mention.util.ts, `a.mention-user[data-id]`). */
401
+ export function mentionedIdsIn(html) {
402
+ const out = new Set();
403
+ for (const m of html.matchAll(/<a\b[^>]*>/gi)) {
404
+ const tag = m[0];
405
+ if (!/\bclass\s*=\s*["'][^"']*\bmention-user\b/i.test(tag))
406
+ continue;
407
+ const id = /\bdata-id\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1]?.trim();
408
+ if (id)
409
+ out.add(id);
410
+ }
411
+ return out;
412
+ }
413
+ const escapeHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
414
+ /**
415
+ * Add a comment to a task. Content supports HTML. mention_ids: comma-separated 'id:Name' pairs.
416
+ *
417
+ * A mention is ONE tag per user, in the order given, inside the comment's first paragraph. Up to
418
+ * 1.46.0 every pair was prepended whatever the content held: an agent that wrote the mention into the
419
+ * text AND passed mention_ids got the same `@Name` twice in the comment (reported 2026-11-19), a repeated
420
+ * pair repeated it again, the tags came out in reverse order, and a plain-text comment with a mention
421
+ * lost its <p> (the tags made it start with `<`). A user the content already mentions is not added
422
+ * again; an id that is not a user id (digits, or the front's `$all`) is refused before anything is sent.
423
+ */
400
424
  export async function addComment(taskId, content, mentionIds = null) {
401
- let html = content;
402
- // Process mentions (prepended, matching platform format)
425
+ let html = String(content ?? "");
426
+ // Plain text becomes paragraphs FIRST, so the mentions land inside the first one.
427
+ if (!html.replace(/^\s+/, "").startsWith("<")) {
428
+ html = wrapHtml(html);
429
+ }
430
+ const added = [];
431
+ const alreadyInContent = [];
403
432
  if (mentionIds) {
404
- for (let part of mentionIds.split(",")) {
405
- part = part.trim();
406
- if (part.includes(":")) {
407
- const idx = part.indexOf(":");
408
- const uid = part.slice(0, idx).trim();
409
- const name = part.slice(idx + 1).trim();
410
- const mentionTag = `<a class="mention-user" id="mention-${uid}" ` +
411
- `data-id="${uid}">@${name}</a>&nbsp;`;
412
- html = mentionTag + html;
433
+ const present = mentionedIdsIn(html);
434
+ const seen = new Set();
435
+ const tags = [];
436
+ const bad = [];
437
+ for (const raw of mentionIds.split(",")) {
438
+ const part = raw.trim();
439
+ if (!part)
440
+ continue;
441
+ const idx = part.indexOf(":");
442
+ const uid = (idx === -1 ? part : part.slice(0, idx)).trim();
443
+ const name = idx === -1 ? "" : part.slice(idx + 1).trim();
444
+ if (!/^\d+$/.test(uid) && uid !== "$all") {
445
+ bad.push(part);
446
+ continue;
447
+ }
448
+ if (seen.has(uid))
449
+ continue;
450
+ seen.add(uid);
451
+ if (present.has(uid)) {
452
+ alreadyInContent.push(uid);
453
+ continue;
454
+ }
455
+ if (!name) {
456
+ bad.push(part);
457
+ continue;
413
458
  }
459
+ tags.push(`<a class="mention-user" id="mention-${uid}" data-id="${uid}">@${escapeHtml(name)}</a>&nbsp;`);
460
+ added.push(uid);
461
+ }
462
+ if (bad.length) {
463
+ return jsonResponse({
464
+ error: `mention_ids: ${bad.map((b) => `'${b}'`).join(", ")} — each mention is 'userId:Name' with a numeric user id ` +
465
+ "(suppa_search_users finds it). Nothing was posted.",
466
+ });
467
+ }
468
+ if (tags.length) {
469
+ const prefix = tags.join("");
470
+ const firstParagraph = /^(\s*<p\b[^>]*>)/i.exec(html);
471
+ html = firstParagraph ? firstParagraph[1] + prefix + html.slice(firstParagraph[1].length) : prefix + html;
414
472
  }
415
- }
416
- if (!html.replace(/^\s+/, "").startsWith("<")) {
417
- html = wrapHtml(html);
418
473
  }
419
474
  const fields = {
420
475
  owner: { id: taskId },
@@ -422,7 +477,18 @@ export async function addComment(taskId, content, mentionIds = null) {
422
477
  content: html,
423
478
  };
424
479
  const result = await insertEntity("TasksComments", [fields]);
425
- return jsonResponse(result.length ? result[0] : null);
480
+ const row = result.length ? result[0] : null;
481
+ if (!mentionIds || !row || typeof row !== "object")
482
+ return jsonResponse(row);
483
+ return jsonResponse({
484
+ ...row,
485
+ mentions: {
486
+ added,
487
+ ...(alreadyInContent.length
488
+ ? { already_in_content: alreadyInContent, note: "these users are mentioned in the content itself — not added a second time" }
489
+ : {}),
490
+ },
491
+ });
426
492
  }
427
493
  /**
428
494
  * Get the latest N comments for a task, oldest-first.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.45.1",
3
+ "version": "1.46.1",
4
4
  "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: suppa-cli
3
- description: Use when working with a Suppa 2.0 tenant from a terminal — tasks, records, entities, custom fields, docs, forms, automations, file attachments. The `suppa` command carries all 108 operations with browser-based login and token storage in the OS keychain. Prefer it over hand-written HTTP calls: validates arguments before sending and explains platform refusals.
3
+ description: Use when working with a Suppa 2.0 tenant from a terminal — tasks, records, entities, custom fields, docs, forms, automations, file attachments. The `suppa` command carries all 110 operations with browser-based login and token storage in the OS keychain. Prefer it over hand-written HTTP calls: validates arguments before sending and explains platform refusals.
4
4
  ---
5
5
 
6
6
  # Suppa 2.0 from the shell