@buoy-gg/shared-ui 7.0.35 → 7.0.36

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.
Files changed (59) hide show
  1. package/lib/commonjs/hooks/safe-area-impl.js +1 -1
  2. package/lib/commonjs/icons/index.js +7 -0
  3. package/lib/commonjs/index.js +48 -0
  4. package/lib/commonjs/sync/keyedArrays.js +209 -0
  5. package/lib/commonjs/sync/toolAttention.test.js +51 -0
  6. package/lib/commonjs/sync/toolUiBridge.js +58 -0
  7. package/lib/commonjs/sync/typedEdit.js +228 -0
  8. package/lib/commonjs/sync/valuePath.js +337 -0
  9. package/lib/commonjs/sync/valueShape.js +161 -0
  10. package/lib/commonjs/ui/components/ExpandablePopover.js +38 -6
  11. package/lib/module/hooks/safe-area-impl.js +1 -1
  12. package/lib/module/icons/index.js +3 -1
  13. package/lib/module/index.js +4 -0
  14. package/lib/module/sync/keyedArrays.js +204 -0
  15. package/lib/module/sync/toolAttention.test.js +50 -0
  16. package/lib/module/sync/toolUiBridge.js +55 -0
  17. package/lib/module/sync/typedEdit.js +220 -0
  18. package/lib/module/sync/valuePath.js +330 -0
  19. package/lib/module/sync/valueShape.js +153 -0
  20. package/lib/module/ui/components/ExpandablePopover.js +38 -6
  21. package/lib/typescript/commonjs/hooks/safe-area-impl.d.ts +1 -1
  22. package/lib/typescript/commonjs/icons/index.d.ts +1 -1
  23. package/lib/typescript/commonjs/icons/index.d.ts.map +1 -1
  24. package/lib/typescript/commonjs/index.d.ts +4 -0
  25. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  26. package/lib/typescript/commonjs/sync/keyedArrays.d.ts +35 -0
  27. package/lib/typescript/commonjs/sync/keyedArrays.d.ts.map +1 -0
  28. package/lib/typescript/commonjs/sync/toolAttention.test.d.ts +2 -0
  29. package/lib/typescript/commonjs/sync/toolAttention.test.d.ts.map +1 -0
  30. package/lib/typescript/commonjs/sync/toolUiBridge.d.ts +25 -0
  31. package/lib/typescript/commonjs/sync/toolUiBridge.d.ts.map +1 -1
  32. package/lib/typescript/commonjs/sync/typedEdit.d.ts +70 -0
  33. package/lib/typescript/commonjs/sync/typedEdit.d.ts.map +1 -0
  34. package/lib/typescript/commonjs/sync/valuePath.d.ts +52 -0
  35. package/lib/typescript/commonjs/sync/valuePath.d.ts.map +1 -0
  36. package/lib/typescript/commonjs/sync/valueShape.d.ts +77 -0
  37. package/lib/typescript/commonjs/sync/valueShape.d.ts.map +1 -0
  38. package/lib/typescript/commonjs/ui/components/ExpandablePopover.d.ts +14 -1
  39. package/lib/typescript/commonjs/ui/components/ExpandablePopover.d.ts.map +1 -1
  40. package/lib/typescript/module/hooks/safe-area-impl.d.ts +1 -1
  41. package/lib/typescript/module/icons/index.d.ts +1 -1
  42. package/lib/typescript/module/icons/index.d.ts.map +1 -1
  43. package/lib/typescript/module/index.d.ts +4 -0
  44. package/lib/typescript/module/index.d.ts.map +1 -1
  45. package/lib/typescript/module/sync/keyedArrays.d.ts +35 -0
  46. package/lib/typescript/module/sync/keyedArrays.d.ts.map +1 -0
  47. package/lib/typescript/module/sync/toolAttention.test.d.ts +2 -0
  48. package/lib/typescript/module/sync/toolAttention.test.d.ts.map +1 -0
  49. package/lib/typescript/module/sync/toolUiBridge.d.ts +25 -0
  50. package/lib/typescript/module/sync/toolUiBridge.d.ts.map +1 -1
  51. package/lib/typescript/module/sync/typedEdit.d.ts +70 -0
  52. package/lib/typescript/module/sync/typedEdit.d.ts.map +1 -0
  53. package/lib/typescript/module/sync/valuePath.d.ts +52 -0
  54. package/lib/typescript/module/sync/valuePath.d.ts.map +1 -0
  55. package/lib/typescript/module/sync/valueShape.d.ts +77 -0
  56. package/lib/typescript/module/sync/valueShape.d.ts.map +1 -0
  57. package/lib/typescript/module/ui/components/ExpandablePopover.d.ts +14 -1
  58. package/lib/typescript/module/ui/components/ExpandablePopover.d.ts.map +1 -1
  59. package/package.json +4 -4
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Id-addressed list edits — one implementation, shared by every adapter that
5
+ * takes a merge patch.
6
+ *
7
+ * WHY. Resending a whole array is correct only when the caller has SEEN the
8
+ * whole array, and reads are capped. Measured with a 20-item list truncated to
9
+ * 5 (`pnpm ai:array --truncate=5`): the whole-array form scored 0/9 across three
10
+ * models — two refused outright, and one silently sent back only the 5 items it
11
+ * had been shown, destroying the other 15. Addressed edits scored 9/9.
12
+ *
13
+ * It also makes mass deletion impossible BY OMISSION: an addressed edit can only
14
+ * remove ids it names. Sending a real array still replaces the list, which is
15
+ * how a caller deliberately empties one.
16
+ *
17
+ * This lives here rather than in one adapter because react-query, zustand and
18
+ * network all take merge patches, and a second copy of a data-destroying safety
19
+ * rule is a copy that drifts.
20
+ */
21
+ const isPlainObject = v => typeof v === "object" && v !== null && !Array.isArray(v);
22
+
23
+ /** Fields we will treat as an item's stable identity, best first. */
24
+ const ID_FIELDS = ["id", "lineId", "key", "uuid", "_id", "slug", "name"];
25
+
26
+ /**
27
+ * The field that identifies items in this list, or undefined if there isn't one.
28
+ *
29
+ * Every item must carry it, and every value must be a distinct string/number —
30
+ * a duplicated id would make an addressed edit ambiguous, and silently picking
31
+ * the first match is exactly the kind of "helpful" guess that loses data.
32
+ */
33
+ export function identityField(items) {
34
+ if (!items.length || !items.every(isPlainObject)) return undefined;
35
+ const first = items[0];
36
+ for (const f of ID_FIELDS) {
37
+ if (!(f in first)) continue;
38
+ const values = items.map(it => it[f]);
39
+ const usable = values.every(v => typeof v === "string" || typeof v === "number");
40
+ if (!usable) continue;
41
+ if (new Set(values.map(String)).size !== values.length) continue;
42
+ return f;
43
+ }
44
+ return undefined;
45
+ }
46
+
47
+ /**
48
+ * The identity an ADDED item should carry.
49
+ *
50
+ * `Object.entries` hands back STRING keys, so `{"9901": {id: 9901, …}}` was
51
+ * written as `{id: "9901"}` — the caller's own numeric id replaced by text, and
52
+ * then refused by the typed-edit guard as `[2].id: number → string`. The caller
53
+ * recovers by resending the WHOLE array, which is exactly the truncation-unsafe
54
+ * move this module exists to prevent. Measured on a live QA run: one added
55
+ * offer cost a refusal, a full-list retransmission and 35 seconds.
56
+ *
57
+ * So the id the caller WROTE wins. With no id in the body, the key is coerced
58
+ * to the type the existing items use, and only when the text round-trips
59
+ * exactly: "007" is not 7, and inventing that identity is worse than a refusal
60
+ * the caller can read.
61
+ */
62
+ function identityForAdd(current, idField, key, edit) {
63
+ const supplied = edit[idField];
64
+ if (typeof supplied === "string" || typeof supplied === "number") {
65
+ // An item whose id disagrees with the address it was sent under is
66
+ // ambiguous — either could be the one the caller meant. Say so rather than
67
+ // silently picking one and writing an item nobody asked for.
68
+ if (String(supplied) !== key) {
69
+ return {
70
+ ok: false,
71
+ error: `The new item is addressed as \`${key}\` but carries \`${idField}\`: ${JSON.stringify(supplied)}. Use the same value for both — address it by the id it carries.`
72
+ };
73
+ }
74
+ return {
75
+ ok: true,
76
+ value: supplied
77
+ };
78
+ }
79
+ const numericList = current.every(it => typeof it[idField] === "number");
80
+ if (numericList && key.trim() !== "" && String(Number(key)) === key) {
81
+ return {
82
+ ok: true,
83
+ value: Number(key)
84
+ };
85
+ }
86
+ return {
87
+ ok: true,
88
+ value: key
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Let a caller address list items by their own id instead of resending the list.
94
+ *
95
+ * { lines: { "seed-1": { qty: 5 } } } change one field of one item
96
+ * { lines: { "seed-2": null } } remove that item
97
+ * { lines: { "new-1": { …all fields… } } } append (id not already present)
98
+ *
99
+ * WHY THIS EXISTS. Resending the whole array is correct only when the caller has
100
+ * SEEN the whole array, and reads are capped — so on a long list the honest
101
+ * agents refuse and the careless ones send back only the items they were shown,
102
+ * silently destroying the rest. Measured: with a 20-item bag truncated to 5, the
103
+ * whole-array form scored 0/9 across three models and one of them deleted 15
104
+ * lines without a word. Addressed edits scored 9/9. (`pnpm ai:array`.)
105
+ *
106
+ * It also makes mass deletion impossible BY OMISSION: `lines: []` empties a bag,
107
+ * but a keyed edit can only remove ids it names.
108
+ *
109
+ * Returns the patch with keyed objects expanded into real arrays, so everything
110
+ * downstream — the typed-edit guard, the receipt, the store write — is unchanged
111
+ * and keeps all of its protections.
112
+ */
113
+ export function expandKeyedArrays(current, patch, path = "", notes = []) {
114
+ if (Array.isArray(current) && isPlainObject(patch)) {
115
+ const idField = identityField(current);
116
+ if (!idField) {
117
+ // No stable identity: leave it alone and let the normal guard report the
118
+ // object-vs-array type change, which says something truer than we could.
119
+ return {
120
+ patch,
121
+ notes
122
+ };
123
+ }
124
+ const byId = new Map(current.map(it => [String(it[idField]), it]));
125
+ const next = current.slice();
126
+ let removed = 0;
127
+ let changed = 0;
128
+ let added = 0;
129
+ for (const [id, edit] of Object.entries(patch)) {
130
+ const i = next.findIndex(it => String(it[idField]) === id);
131
+ if (edit === null) {
132
+ if (i === -1) return {
133
+ patch,
134
+ notes
135
+ };
136
+ next.splice(i, 1);
137
+ removed++;
138
+ } else if (i === -1) {
139
+ if (!isPlainObject(edit)) return {
140
+ patch,
141
+ notes
142
+ };
143
+ const identity = identityForAdd(current, idField, id, edit);
144
+ if (!identity.ok) {
145
+ return {
146
+ patch,
147
+ notes,
148
+ error: identity.error
149
+ };
150
+ }
151
+ next.push({
152
+ ...edit,
153
+ [idField]: identity.value
154
+ });
155
+ added++;
156
+ } else {
157
+ const merged = expandKeyedArrays(byId.get(id), edit, `${path}[${id}]`, notes);
158
+ if (merged.error) return {
159
+ patch,
160
+ notes,
161
+ error: merged.error
162
+ };
163
+ const base = next[i];
164
+ next[i] = isPlainObject(base) && isPlainObject(merged.patch) ? {
165
+ ...base,
166
+ ...merged.patch
167
+ } : merged.patch;
168
+ changed++;
169
+ }
170
+ }
171
+ notes.push(`${path || "(root)"}: addressed by \`${idField}\` — ${changed} changed, ${added} added, ${removed} removed, ${next.length} item(s) remain`);
172
+ return {
173
+ patch: next,
174
+ notes
175
+ };
176
+ }
177
+ if (isPlainObject(current) && isPlainObject(patch)) {
178
+ const outPatch = {};
179
+ for (const [k, v] of Object.entries(patch)) {
180
+ const p = path ? `${path}.${k}` : k;
181
+ if (!(k in current)) {
182
+ outPatch[k] = v;
183
+ continue;
184
+ }
185
+ const inner = expandKeyedArrays(current[k], v, p, notes);
186
+ // A refusal deep in the tree is the whole patch's refusal: writing the
187
+ // rest of it would apply half of what the caller asked for.
188
+ if (inner.error) return {
189
+ patch,
190
+ notes,
191
+ error: inner.error
192
+ };
193
+ outPatch[k] = inner.patch;
194
+ }
195
+ return {
196
+ patch: outPatch,
197
+ notes
198
+ };
199
+ }
200
+ return {
201
+ patch,
202
+ notes
203
+ };
204
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * The attention badge seam: a tool says "I need you" and the rail hears it.
5
+ */
6
+ import { describe, expect, it, vi } from "vitest";
7
+ import { getToolAttention, setToolAttention, subscribeToolAttention } from "./toolUiBridge.js";
8
+ describe("toolAttention", () => {
9
+ it("stores, replaces and clears a badge, notifying once per change", () => {
10
+ const fn = vi.fn();
11
+ const off = subscribeToolAttention(fn);
12
+ setToolAttention("ask-buoy", {
13
+ kind: "needsInput",
14
+ label: "Needs your approval"
15
+ });
16
+ expect(getToolAttention("ask-buoy")).toEqual({
17
+ kind: "needsInput",
18
+ label: "Needs your approval"
19
+ });
20
+ expect(fn).toHaveBeenCalledTimes(1);
21
+ // Same value again is not a change.
22
+ setToolAttention("ask-buoy", {
23
+ kind: "needsInput",
24
+ label: "Needs your approval"
25
+ });
26
+ expect(fn).toHaveBeenCalledTimes(1);
27
+ setToolAttention("ask-buoy", {
28
+ kind: "done",
29
+ label: "Finished"
30
+ });
31
+ expect(fn).toHaveBeenCalledTimes(2);
32
+ setToolAttention("ask-buoy", null);
33
+ expect(getToolAttention("ask-buoy")).toBeNull();
34
+ expect(fn).toHaveBeenCalledTimes(3);
35
+ // Clearing what is already clear is silent.
36
+ setToolAttention("ask-buoy", null);
37
+ expect(fn).toHaveBeenCalledTimes(3);
38
+ off();
39
+ });
40
+ it("keeps tools apart", () => {
41
+ setToolAttention("a", {
42
+ kind: "failed",
43
+ label: "x"
44
+ });
45
+ setToolAttention("b", null);
46
+ expect(getToolAttention("a")?.kind).toBe("failed");
47
+ expect(getToolAttention("b")).toBeNull();
48
+ setToolAttention("a", null);
49
+ });
50
+ });
@@ -65,4 +65,59 @@ export function openBuoyTool(toolId) {
65
65
  /** True when some host is listening — for deciding whether to offer the button. */
66
66
  export function canOpenBuoyTools() {
67
67
  return openers().size > 0;
68
+ }
69
+
70
+ // ─── Attention ───────────────────────────────────────────────────────────────
71
+
72
+ /**
73
+ * "This tool needs you" — shown as a badge on its chip in the minimized rail.
74
+ *
75
+ * The case: Ask Buoy is minimized so a tester can watch the app, and the
76
+ * agent hits a step that needs a tap. Nobody can see the card. The sheet used
77
+ * to fail safe by DECLINING the change and ending the turn — which made
78
+ * minimize mean "stop", the opposite of what it is for. Now the approval
79
+ * holds, the chip gets a badge, and tapping the chip (the existing restore
80
+ * path) brings the card back. Same seam shape as the opener above: the rail
81
+ * lives inside the host, the tool cannot import the host, so it publishes
82
+ * through a global.
83
+ *
84
+ * `done` and `failed` cover the other thing a hidden tool cannot say — that
85
+ * the work you minimized it to wait for has finished.
86
+ */
87
+
88
+ const ATTENTION_KEY = "__buoyToolAttention";
89
+ function attention() {
90
+ const g = globalThis;
91
+ if (!g[ATTENTION_KEY]) g[ATTENTION_KEY] = {
92
+ byTool: new Map(),
93
+ listeners: new Set()
94
+ };
95
+ return g[ATTENTION_KEY];
96
+ }
97
+
98
+ /** Set, replace or (with null) clear a tool's badge. No-op when nothing changed. */
99
+ export function setToolAttention(toolId, next) {
100
+ const store = attention();
101
+ const prev = store.byTool.get(toolId) ?? null;
102
+ if (prev === next || prev && next && prev.kind === next.kind && prev.label === next.label) return;
103
+ if (next) store.byTool.set(toolId, next);else store.byTool.delete(toolId);
104
+ for (const fn of store.listeners) {
105
+ try {
106
+ fn();
107
+ } catch {
108
+ // A throwing subscriber must not stop the others from hearing.
109
+ }
110
+ }
111
+ }
112
+ export function getToolAttention(toolId) {
113
+ return attention().byTool.get(toolId) ?? null;
114
+ }
115
+
116
+ /** For `useSyncExternalStore` in the rail. */
117
+ export function subscribeToolAttention(fn) {
118
+ const store = attention();
119
+ store.listeners.add(fn);
120
+ return () => {
121
+ store.listeners.delete(fn);
122
+ };
68
123
  }
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * The typed-edit guard — ONE implementation, for every surface that takes a
5
+ * merge patch from a remote caller.
6
+ *
7
+ * The rule, which is the React Query devtools value-editor rule: you may change
8
+ * the VALUE of a field that already exists, to the same kind of thing. You may
9
+ * not add a field, change a field's type, or null a list or object the screen
10
+ * renders. A list may grow or shrink — carts are lists you add to — but every
11
+ * item in it must have the same fields as the items already there, because an
12
+ * item missing a field the others have is what crashes the list on render.
13
+ *
14
+ * WHY IT LIVES HERE. This existed twice, once in the zustand adapter and once in
15
+ * react-query, drifting slightly (one said "the ones already in the list", the
16
+ * other "the items"; only one had the did-you-mean hint). Jotai had NO copy at
17
+ * all, so `setAtom` accepted a string over a number or a one-item array over a
18
+ * fifty-item one with nothing to stop it. Three copies of a data-destroying
19
+ * safety rule is two more than anyone can keep in step — the same argument
20
+ * `keyedArrays.ts` makes about the expansion it owns.
21
+ *
22
+ * The one behavioural knob is `noun`: what to call the thing being edited in a
23
+ * refusal ("this store", "this data", "this atom"). Everything else is shared,
24
+ * deliberately — a rule that differs per surface is a rule nobody can state.
25
+ */
26
+
27
+ const isPlainObject = v => !!v && typeof v === "object" && !Array.isArray(v);
28
+
29
+ /** The shape category the screen depends on: array vs object vs the rest. */
30
+ export function shapeKind(v) {
31
+ if (Array.isArray(v)) return "array";
32
+ if (v === null) return "null";
33
+ if (typeof v === "object") return "object";
34
+ return typeof v;
35
+ }
36
+ const SCALARS = ["string", "number", "boolean"];
37
+
38
+ /**
39
+ * Where a key actually lives in a nested value, as a dotted path — first match,
40
+ * breadth-first, capped so a huge payload cannot stall the walk.
41
+ *
42
+ * This is what turns "you put `name` at the top" into "`name` lives at
43
+ * `item.name`", which is the difference between a caller that gives up and one
44
+ * that fixes it. Ten of eleven measured `query` write failures were this exact
45
+ * mistake.
46
+ */
47
+ export function findKeyPath(obj, key, maxNodes = 2000) {
48
+ const queue = [{
49
+ node: obj,
50
+ path: ""
51
+ }];
52
+ let seen = 0;
53
+ while (queue.length && seen < maxNodes) {
54
+ const {
55
+ node,
56
+ path
57
+ } = queue.shift();
58
+ seen++;
59
+ if (Array.isArray(node)) {
60
+ node.slice(0, 20).forEach((v, i) => queue.push({
61
+ node: v,
62
+ path: `${path}[${i}]`
63
+ }));
64
+ } else if (isPlainObject(node)) {
65
+ for (const [k, v] of Object.entries(node)) {
66
+ const p = path ? `${path}.${k}` : k;
67
+ if (k === key && path) return p; // path set => nested, not the top level
68
+ if (isPlainObject(v) || Array.isArray(v)) queue.push({
69
+ node: v,
70
+ path: p
71
+ });
72
+ }
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+ /**
78
+ * Every way this patch would break the value it is merged into. Empty means the
79
+ * edit is safe to apply.
80
+ */
81
+ export function typedEditViolations(current, patch, opts = {}, root = current, path = "", out = []) {
82
+ const noun = opts.noun ?? "data";
83
+ const here = path || "(root)";
84
+ if (Array.isArray(patch)) {
85
+ if (!Array.isArray(current)) {
86
+ out.push({
87
+ path: here,
88
+ kind: "type-change",
89
+ detail: `${shapeKind(current)} → array`
90
+ });
91
+ return out;
92
+ }
93
+ // Length may change — a cart is a list you add to and remove from — but each
94
+ // item must match the shape of the ones already there. The first item is the
95
+ // template; an added item missing a field the others have is what makes the
96
+ // list throw when it renders that field.
97
+ const template = current.length ? current[0] : undefined;
98
+ if (template !== undefined && (isPlainObject(template) || Array.isArray(template))) {
99
+ patch.forEach((el, i) => {
100
+ const ep = `${path}[${i}]`;
101
+ if (isPlainObject(template) && isPlainObject(el)) {
102
+ for (const k of Object.keys(template)) {
103
+ if (!(k in el)) {
104
+ out.push({
105
+ path: `${ep}.${k}`,
106
+ kind: "missing-key",
107
+ detail: `list items need \`${k}\` — the items already in the list have it`
108
+ });
109
+ }
110
+ }
111
+ }
112
+ typedEditViolations(template, el, opts, root, ep, out);
113
+ });
114
+ }
115
+ return out;
116
+ }
117
+ if (isPlainObject(patch)) {
118
+ if (!isPlainObject(current)) {
119
+ out.push({
120
+ path: here,
121
+ kind: "type-change",
122
+ detail: `${shapeKind(current)} → object`
123
+ });
124
+ return out;
125
+ }
126
+ for (const [k, v] of Object.entries(patch)) {
127
+ const p = path ? `${path}.${k}` : k;
128
+ if (!(k in current)) {
129
+ const elsewhere = findKeyPath(root, k);
130
+ out.push({
131
+ path: p,
132
+ kind: "add-key",
133
+ detail: elsewhere ? `no such field here — did you mean \`${elsewhere}\`?` : `no field named \`${k}\` exists in this ${noun}`,
134
+ ...(elsewhere ? {
135
+ movedTo: elsewhere
136
+ } : {})
137
+ });
138
+ } else {
139
+ typedEditViolations(current[k], v, opts, root, p, out);
140
+ }
141
+ }
142
+ return out;
143
+ }
144
+
145
+ // A leaf: the edit itself.
146
+ const ck = shapeKind(current);
147
+ const pk = shapeKind(patch);
148
+ // Filling an empty field and CLEARING one are the same kind of edit, and this
149
+ // guard used to allow only the first. That asymmetry had a cost: "take the
150
+ // promo off my bag" is `string → null`, the refusal named `force: true` as the
151
+ // only way through, and a model that anticipated it wrote the forced call
152
+ // pre-emptively — reaching for the one parameter that bypasses EVERY
153
+ // protection in order to do something completely ordinary. Measured on
154
+ // `cart/take-promo-off`: an S1 on an otherwise correct flow.
155
+ //
156
+ // Nulling a LIST or OBJECT the screen renders stays refused. That is the crash
157
+ // this guard exists for (`sizes.map` on null); a null scalar renders as empty.
158
+ const fillingNull = ck === "null" && SCALARS.includes(pk);
159
+ const clearingScalar = pk === "null" && SCALARS.includes(ck);
160
+ if (ck !== pk && !fillingNull && !clearingScalar) {
161
+ out.push({
162
+ path: here,
163
+ kind: "type-change",
164
+ detail: `${ck} → ${pk}`
165
+ });
166
+ }
167
+ return out;
168
+ }
169
+
170
+ /**
171
+ * The patch the caller should have sent, when every problem was a field written
172
+ * at the wrong DEPTH.
173
+ *
174
+ * The guard already worked out where each field really lives in order to say
175
+ * "did you mean `item.name`?", so it can rebuild the patch instead of leaving
176
+ * the caller to re-derive it from prose. Returns undefined unless EVERY
177
+ * violation is a relocatable add-key: a partial suggestion that silently drops
178
+ * the parts we could not fix would be worse than none, because the caller would
179
+ * send it, be refused again, and learn nothing.
180
+ */
181
+ export function suggestedPatch(patch, violations) {
182
+ if (!violations.length || !violations.every(v => v.kind === "add-key" && v.movedTo)) return undefined;
183
+ const out = {};
184
+ for (const v of violations) {
185
+ const value = getAtDotted(patch, v.path);
186
+ if (value === undefined) return undefined;
187
+ // `movedTo` can name a list element (`results[0].name`); a merge patch
188
+ // cannot address one by index, and rewriting it to the id-addressed form
189
+ // needs the list itself. Leave those to the prose rather than suggest
190
+ // something that will not apply.
191
+ if (v.movedTo.includes("[")) return undefined;
192
+ let node = out;
193
+ const segs = v.movedTo.split(".");
194
+ segs.slice(0, -1).forEach(seg => {
195
+ node[seg] ??= {};
196
+ node = node[seg];
197
+ });
198
+ node[segs[segs.length - 1]] = value;
199
+ }
200
+ return out;
201
+ }
202
+ function getAtDotted(obj, path) {
203
+ let cur = obj;
204
+ for (const seg of path.split(".")) {
205
+ if (!isPlainObject(cur)) return undefined;
206
+ cur = cur[seg];
207
+ }
208
+ return cur;
209
+ }
210
+
211
+ /**
212
+ * The sentence a refusal ends with. Shared so every surface refuses in the same
213
+ * words — a caller that learns the rule on one tool should recognise it on the
214
+ * next.
215
+ */
216
+ export function refusalText(violations, noun, suggestion) {
217
+ const listed = violations.slice(0, 6).map(v => `\`${v.path}\`: ${v.detail}`).join("; ");
218
+ const more = violations.length > 6 ? `; +${violations.length - 6} more` : "";
219
+ return `Refused: this isn't a same-type edit of existing fields (the rule the React Query devtools enforces). ${listed}${more}. ` + `You can only change the VALUE of a field that already exists, to the same type — you can't add fields, change a field's type, ` + `or null a list/object the screen renders. Clearing a scalar to null is fine. Send just the field(s) you're changing, nested to ` + `match the current shape of this ${noun}. Use force:true only to deliberately break that.` + (suggestion ? ` This is the same edit at the right depth — send it as the patch: ${JSON.stringify(suggestion)}` : "");
220
+ }