sbuilder-mcp 0.98.9 → 0.99.0

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/CHANGELOG.md CHANGED
@@ -6,6 +6,32 @@ All notable changes to this project are documented in this file.
6
6
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [0.99.0] - 2026-10-29
10
+
11
+ ### Added
12
+ - `sb_outline` collapses shared headers, footers and overlays into one line each, and `chrome: true` expands them.
13
+ - `sb_add` returns `added` and `satellites` as `{id: type}`, and `sb_duplicate` returns `copies` as `{old: [new, type]}`.
14
+ - `sb_outline` shows the label of accordion and tab items.
15
+ - `sb_store` with `action: "form"` and `node_id` places the form into that node on the open page.
16
+ - `sb_set` reports the keys it removed (`unset`) and the keys that were not present (`absent`), and `edits[].keys` is optional when `unset` is given.
17
+ - `sb_review` and `sb_set` warn about `link_colour` when an `<a>` in `textHtml` has no `color`, because the browser paints it blue.
18
+ - `sb_review` reports `default_font` when a node keeps an element's hard-coded font on a site whose theme sets a different text font.
19
+ - `sb_undo` entries carry the tool name and a summary, and by default list only the open page, with `all: true` to list every page.
20
+ - `sb_traits_for` with `control: "layout"` names the key, its values and the fallback instead of returning `writes: null`.
21
+
22
+ ### Changed
23
+ - `sb_add` translates the seed copy of new elements, such as the "No products yet" empty state, when the site locale is `vi` or unknown, as `sb_page_create` does.
24
+ - A media dataset without children inside a dataset block or cart item is seeded with `layout: "single"`, matching the editor's card preset.
25
+ - `sb_review` checks `pageSeo` and `unreachablePage` on the open page while it is still a draft.
26
+ - `sb_traits_for` states hints, animation and notes once per process, and `sb_node_read` omits `backgroundScene*` when there is no scene.
27
+ - `sb_api_find` matches on word starts, so "list" no longer returns "wishlist".
28
+ - The `sb_publish` dry run states the cascade rule, since the platform has no preview.
29
+ - The `sb_page_state` recovery note says that autosave merges once every 5 minutes per author.
30
+
31
+ ### Fixed
32
+ - A page with `settings.noIndex` is no longer reported as `unreachablePage`, and the finding explains how to remove it with `seo.noIndex`.
33
+ - A deleted page now fails with "page … no longer exists — sb_page_open another" instead of a bare 404.
34
+
9
35
  ## [0.98.9] - 2026-10-29
10
36
 
11
37
  ### Fixed
package/CHANGELOG.vi.md CHANGED
@@ -6,6 +6,32 @@ Mọi thay đổi đáng chú ý của dự án được ghi lại trong file n
6
6
  Định dạng dựa trên [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
  và dự án tuân theo [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [0.99.0] - 2026-10-29
10
+
11
+ ### Added
12
+ - `sb_outline` thu header, footer dùng chung và overlay về một dòng mỗi mục, và `chrome: true` để mở ra.
13
+ - `sb_add` trả `added` và `satellites` dạng `{id: type}`, còn `sb_duplicate` trả `copies` dạng `{old: [new, type]}`.
14
+ - `sb_outline` hiện label của accordion và tab.
15
+ - `sb_store` với `action: "form"` và `node_id` đặt form vào node của trang đang mở.
16
+ - `sb_set` báo lại các key đã xoá (`unset`) và các key không có (`absent`), và `edits[].keys` không còn bắt buộc khi có `unset`.
17
+ - `sb_review` và `sb_set` cảnh báo `link_colour` khi thẻ `<a>` trong `textHtml` không có `color`, vì trình duyệt tô màu xanh.
18
+ - `sb_review` báo `default_font` khi node vẫn giữ font cứng của element trên site có theme dùng font text khác.
19
+ - Mục của `sb_undo` mang tên tool và phần tóm tắt, mặc định chỉ liệt kê trang đang mở, và dùng `all: true` để liệt kê mọi trang.
20
+ - `sb_traits_for` với `control: "layout"` nêu key, các giá trị và fallback thay vì trả `writes: null`.
21
+
22
+ ### Changed
23
+ - `sb_add` dịch nội dung seed của element mới, như empty state "No products yet", khi locale của site là `vi` hoặc chưa đọc được, giống `sb_page_create`.
24
+ - Media dataset không có con trong dataset block hoặc cart item được gieo `layout: "single"`, khớp với preset card của editor.
25
+ - `sb_review` xét `pageSeo` và `unreachablePage` cả trên trang đang mở khi trang còn là bản nháp.
26
+ - `sb_traits_for` nói hints, animation và notes một lần mỗi process, và `sb_node_read` bỏ `backgroundScene*` khi không có scene.
27
+ - `sb_api_find` khớp đầu từ, nên "list" không còn trả về "wishlist".
28
+ - Dry run của `sb_publish` nêu quy tắc cascade, vì nền tảng không có preview.
29
+ - Ghi chú recovery của `sb_page_state` nói rằng autosave gộp mỗi 5 phút mỗi tác giả.
30
+
31
+ ### Fixed
32
+ - Trang có `settings.noIndex` không còn bị báo `unreachablePage`, và finding chỉ cách gỡ bằng `seo.noIndex`.
33
+ - Trang đã xoá giờ báo "page … no longer exists — sb_page_open another" thay vì 404 trơn.
34
+
9
35
  ## [0.98.9] - 2026-10-29
10
36
 
11
37
  ### Fixed
package/README.md CHANGED
@@ -85,7 +85,7 @@ in this client: one would put the very key the platform exists to hold back into
85
85
  | `sb_api_find` | Find API operations by intent — one line per match — then read one operation's call sheet by id: real parameter schemas, the credential it needs, and the body's fields read off the handler that decodes them, each carrying the trap its own doc comment records |
86
86
  | `sb_api_call` | Execute an operation, or any route by method+path; dry run by default. Field selection (dotted paths, on lists and single-object write answers) and local result pagination; `merge` for whole-record PUTs, `If-Match`, multipart `file` |
87
87
  | `sb_page_open` | Open a page for editing and return its outline — or, with `form_id`, a form's field document (fields, defaults, dependent-field rules) |
88
- | `sb_outline` | The open page as a compressed tree — never a raw document dump |
88
+ | `sb_outline` | The open page as a compressed tree — never a raw document dump; shared header/footer and overlays one line each unless `chrome: true` |
89
89
  | `sb_node_read` | One node in full, with a warning if it is a shared global |
90
90
  | `sb_catalog_search` | Find an element by what it should do, using the platform's own AI hints |
91
91
  | `sb_traits_for` | An element's inspector — tabs, groups, controls and what each declared one writes — plus its AI hints, defaults and containment rules |
@@ -116,7 +116,7 @@ in this client: one would put the very key the platform exists to hold back into
116
116
  | `sb_theme` | Read or patch the site's palette and type scale — the layer every style preset resolves from, so one token repaints every page; per-breakpoint text-style overrides and element style `presets`; `locale` sets the site's language |
117
117
  | `sb_translate` | Translate a site the way the editor's Multilingual panel does — enable languages, list a page's strings as missing / done / outdated, write or machine-fill them, approve machine rows |
118
118
  | `sb_store` | Run a store flow that must happen in a fixed order — `checkout` (the four writes that make a working one), `checkout_sync` (the store's current payment and delivery methods into every existing order form, checkout page republished), `form` (any of the platform's 17 templates with its own field document), `chrome` (one shared header or footer on a real site menu — site name linked home, desktop menu, mobile drawer, search, cart and account icons), `menu` (a menu node bound to the site's menu, its links resolved), `overlay_attach` (a pop-up or quick view on the open page), `cart` (the site's cart drawer, when it has none; `relocalize` puts an existing one in the site's language) and `app` (a built-in app plus the pages it needs), `global_attach` / `global_detach` (put an EXISTING shared section on the open page, or take it off), `global_promote` (make a section on the page a NEW shared section) and `template_save` (save a section as a reusable template) |
119
- | `sb_undo` | Undo / redo this session's writes — page and form edits and `sb_api_call` PUTs; a page is refused if someone else saved it since. The platform's versions and history (`sb_page_version`) outlive this process |
119
+ | `sb_undo` | Undo / redo this session's writes — page and form edits and `sb_api_call` PUTs, each named by tool and target, the open page's by default (`all: true` for every page); a page is refused if someone else saved it since. The platform's versions and history (`sb_page_version`) outlive this process |
120
120
 
121
121
  Twenty-eight tools, **919 API operations** (344 of the 429 writes carrying a body shape read
122
122
  off the handler), 124 elements, 95 binding sources. `sb_api_find`
package/README.vi.md CHANGED
@@ -82,7 +82,7 @@ nhét ngược lại vào mọi bản cài.
82
82
  | `sb_api_find` | Tìm operation theo ý định — mỗi kết quả một dòng — rồi đọc call sheet của một operation theo id: schema tham số thật, credential cần dùng, và các trường body đọc thẳng từ handler decode chúng, mỗi trường mang theo cái bẫy doc comment của chính nó ghi lại |
83
83
  | `sb_api_call` | Chạy operation, hoặc bất kỳ route nào bằng method+path; mặc định chạy khô. Chọn field (đường dẫn có dấu chấm, trên danh sách lẫn câu trả lời ghi một object) và phân trang kết quả phía MCP; `merge` cho PUT thay cả bản ghi, `If-Match`, `file` multipart |
84
84
  | `sb_page_open` | Mở một trang để sửa và trả về outline — hoặc, với `form_id`, tài liệu trường của biểu mẫu (trường, giá trị mặc định, quy tắc trường phụ thuộc) |
85
- | `sb_outline` | Trang đang mở dạng cây nén — không bao giờ dump tài liệu thô |
85
+ | `sb_outline` | Trang đang mở dạng cây nén — không bao giờ dump tài liệu thô; header/footer dùng chung và overlay mỗi cái một dòng trừ khi `chrome: true` |
86
86
  | `sb_node_read` | Một node đầy đủ, kèm cảnh báo nếu nó là global dùng chung |
87
87
  | `sb_catalog_search` | Tìm element theo việc nó cần làm, dùng chính AI hints của nền tảng |
88
88
  | `sb_traits_for` | Inspector của element — tab, nhóm, control và mỗi control khai báo sẵn ghi vào đâu — kèm AI hints, default và luật chứa con |
@@ -113,7 +113,7 @@ nhét ngược lại vào mọi bản cài.
113
113
  | `sb_theme` | Đọc hoặc vá bảng màu và thang chữ của site — tầng mà mọi style preset phân giải từ đó, nên một token thay áo cho mọi trang; ghi đè text style theo breakpoint và vá `presets` của element; `locale` đặt ngôn ngữ của site |
114
114
  | `sb_translate` | Dịch site như bảng Đa ngôn ngữ của editor — bật ngôn ngữ, liệt kê chuỗi của một trang theo missing / done / outdated, ghi hoặc dịch máy, duyệt dòng do máy dịch |
115
115
  | `sb_store` | Chạy một luồng cửa hàng bắt buộc đúng thứ tự — `checkout` (bốn lệnh ghi tạo nên trang thanh toán), `checkout_sync` (đưa phương thức thanh toán và giao hàng hiện tại vào mọi form đặt hàng đã có, publish lại trang thanh toán), `form` (một trong 17 template của nền tảng kèm field document của nó), `chrome` (một header hoặc footer dùng chung trên menu thật của site — tên site dẫn về trang chủ, menu desktop, drawer mobile, ô tìm kiếm, icon giỏ hàng và tài khoản), `menu` (một node menu bind vào menu của site, link đã phân giải), `overlay_attach` (một pop-up hay quick view trên trang đang mở), `cart` (ngăn giỏ hàng của site, khi chưa có; `relocalize` đưa ngăn giỏ đã có về ngôn ngữ của site), `app` (một app dựng sẵn kèm những trang nó cần), và `global_attach` / `global_detach` (đặt một section dùng chung ĐÃ CÓ lên trang đang mở, hoặc gỡ ra), `global_promote` (biến một section trên trang thành section dùng chung MỚI) và `template_save` (lưu một section làm mẫu dùng lại) |
116
- | `sb_undo` | Hoàn tác / làm lại các thao tác ghi trong phiên — chỉnh sửa trang, form và PUT qua `sb_api_call`; trang bị từ chối nếu người khác đã lưu sau đó. Version và history của nền tảng (`sb_page_version`) sống lâu hơn process này |
116
+ | `sb_undo` | Hoàn tác / làm lại các thao tác ghi trong phiên — chỉnh sửa trang, form và PUT qua `sb_api_call`, mỗi mục ghi tên tool và đối tượng, mặc định của trang đang mở (`all: true` cho mọi trang); trang bị từ chối nếu người khác đã lưu sau đó. Version và history của nền tảng (`sb_page_version`) sống lâu hơn process này |
117
117
 
118
118
  Hai mươi tám tool, **919 operation API** (344 trong 429 lệnh ghi có hình dạng body đọc thẳng
119
119
  từ handler), 124 element, 95 nguồn binding. `sb_api_find` là
@@ -273,7 +273,25 @@ export function traitsFor(type, control) {
273
273
  if (!el.controls.includes(control)) {
274
274
  throw new Error(`sbuilder: ${type} has no control "${control}". It has: ${el.controls.join(', ')}.`);
275
275
  }
276
- return { type, control, ...describeControl(control) };
276
+ const desc = describeControl(control);
277
+ // A CONTROL NAMED AFTER THE KEY IT WRITES. media-dataset's `layout` row is a
278
+ // Vue picker the trait registry does not declare, so this answered
279
+ // "writes: null" while the key, its values and its fallback sat in the
280
+ // generated vocabulary (TTG gap #47). Joined on the element's own config.
281
+ if (desc.writes === null) {
282
+ const vocab = { ...sharedVocabularies(el.defaults ?? {}), ...elementVocabularies(el.type) }[control];
283
+ if (vocab || control in (el.defaults?.config ?? {})) {
284
+ const { target = 'config', writeKey = control, ...values } = vocab ?? {};
285
+ return {
286
+ type,
287
+ control,
288
+ writes: [{ target, writeKey }],
289
+ ...values,
290
+ ...(target === 'config' && isBaseOnlyConfig(type, writeKey) ? { responsive: false } : {}),
291
+ };
292
+ }
293
+ }
294
+ return { type, control, ...desc };
277
295
  }
278
296
  // Read from base only whatever breakpoint is asked for — sb_set routes them
279
297
  // there, so a "tablet-only" value of one of these is the desktop value too.
@@ -46,18 +46,23 @@ export function searchOperations(query, opts = {}) {
46
46
  pool = pool.filter((o) => o.tags.includes(opts.tag));
47
47
  if (terms.length === 0)
48
48
  return pool.slice(0, limit);
49
+ // A TERM MATCHES THE START OF A WORD, never the middle of one: "list" inside
50
+ // "wishlist" put wishlist-demand first for "list categories" (TTG gap #59).
51
+ // A prefix still lets "categor" or "product" find their longer forms.
52
+ const words = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
53
+ const hit = (ws, t) => ws.some((w) => w.startsWith(t));
49
54
  const scored = [];
50
55
  for (const op of pool) {
51
- const tags = op.tags.join(' ').toLowerCase();
52
- const path = op.path.toLowerCase();
53
- const summary = op.summary.toLowerCase();
56
+ const tags = words(op.tags.join(' '));
57
+ const path = words(op.path);
58
+ const summary = words(op.summary);
54
59
  let score = 0;
55
60
  for (const t of terms) {
56
- if (tags.includes(t))
61
+ if (hit(tags, t))
57
62
  score += WEIGHT.tag;
58
- if (path.includes(t))
63
+ if (hit(path, t))
59
64
  score += WEIGHT.path;
60
- if (summary.includes(t))
65
+ if (hit(summary, t))
61
66
  score += WEIGHT.summary;
62
67
  }
63
68
  if (score > 0)
@@ -160,6 +160,17 @@ export function addSubtree(doc, parentId, spec, index, guard) {
160
160
  // Which minted id each spec node became, so a note about a spec node names it.
161
161
  const idOf = new Map();
162
162
  const pending = new Map();
163
+ /** A repeated row — a list's card or a cart line — at or above this node. */
164
+ const inRow = (from) => {
165
+ for (let id = from, hops = 0; id && hops < 64; hops++) {
166
+ const node = (pending.get(id) ?? doc.doc.nodes[id]);
167
+ const t = node?.data?.type;
168
+ if (t === 'dataset-block' || t === 'cart-item')
169
+ return true;
170
+ id = node?.data?.parent;
171
+ }
172
+ return false;
173
+ };
163
174
  const build = (s, parentNodeId) => {
164
175
  refuseComposedStamp(s.specials);
165
176
  // A base-only config key in a breakpoint slot is read from BASE alone, so
@@ -195,6 +206,14 @@ export function addSubtree(doc, parentId, spec, index, guard) {
195
206
  responsive,
196
207
  states: s.states,
197
208
  });
209
+ // A PICTURE IN A CARD IS ONE PICTURE. media-dataset's default layout is
210
+ // `bottom` — a feature plus a thumbnail strip — so a product card grew a
211
+ // strip of thumbnails (TTG gap #47). The editor's own card and cart-line
212
+ // presets seed the childless tile at `single` (datasetParts.ts
213
+ // seedBoundMediaTile); an explicit layout, or a gallery's children, win.
214
+ if (s.type === 'media-dataset' && s.config?.layout === undefined && !s.children?.length && inRow(parentNodeId)) {
215
+ n.config.layout = 'single';
216
+ }
198
217
  pending.set(n.id, n);
199
218
  idOf.set(s, n.id);
200
219
  // A child the element declares as a SATELLITE (an icon's cart-count, a
@@ -645,6 +664,8 @@ export function copyNodeInto(src, id, target, parentId, index, guard) {
645
664
  soft(guard, () => refuseSecondTemplate(target.doc, parentId, 'Duplicating into'));
646
665
  const patches = [];
647
666
  const ids = [];
667
+ /** Source id → its copy's id, so a caller can edit the copy without re-reading the tree. */
668
+ const map = {};
648
669
  // One pass, parent-first, so a child's `parent` always names an id already
649
670
  // emitted — the same ordering rule addSubtree follows.
650
671
  const copy = (srcId, newParent) => {
@@ -666,6 +687,7 @@ export function copyNodeInto(src, id, target, parentId, index, guard) {
666
687
  delete clone.specials?.[stamp];
667
688
  patches.push({ op: 'set', path: ['nodes', clone.id], value: clone });
668
689
  ids.push(clone.id);
690
+ map[srcId] = clone.id;
669
691
  for (const kid of src.data.nodes) {
670
692
  const kidId = copy(kid, clone.id);
671
693
  patches.push({ op: 'insert', path: ['nodes', clone.id, 'data', 'nodes'], index: APPEND, value: kidId });
@@ -694,7 +716,7 @@ export function copyNodeInto(src, id, target, parentId, index, guard) {
694
716
  };
695
717
  const rootId = copy(id, parentId);
696
718
  patches.push({ op: 'insert', path: ['nodes', parentId, 'data', 'nodes'], index, value: rootId });
697
- return { patches, ids };
719
+ return { patches, ids, map };
698
720
  }
699
721
  export function moveNode(doc, id, newParentId, index, guard) {
700
722
  const n = doc.node(id);
@@ -797,8 +819,9 @@ export function setMany(doc, edits, guard) {
797
819
  throw new Error('sbuilder: sb_set edits is empty — nothing to write');
798
820
  const patches = [];
799
821
  const touched = [];
822
+ const valueAt = (path) => path.reduce((o, k) => (o && typeof o === 'object' ? o[k] : undefined), doc.doc);
800
823
  for (const e of edits) {
801
- patches.push(...setKeys(doc, e.id, e.keys, {
824
+ const mine = setKeys(doc, e.id, e.keys, {
802
825
  namespace: e.namespace,
803
826
  breakpoint: e.breakpoint,
804
827
  base: e.base,
@@ -806,8 +829,24 @@ export function setMany(doc, edits, guard) {
806
829
  unset: e.unset,
807
830
  force: guard?.force,
808
831
  forced: guard?.forced,
809
- }));
810
- touched.push({ id: e.id, keys: Object.keys(e.keys) });
832
+ });
833
+ patches.push(...mine);
834
+ // WHAT AN UNSET REMOVED, said back (TTG gap #55) — and a key that was not
835
+ // in that slot named apart, since removing nothing is usually a wrong slot.
836
+ const wanted = new Set(e.unset ?? []);
837
+ const removed = new Set();
838
+ for (const p of mine) {
839
+ const key = String(p.path[p.path.length - 1]);
840
+ if (p.op === 'unset' && wanted.has(key) && valueAt(p.path) !== undefined)
841
+ removed.add(key);
842
+ }
843
+ const absent = [...wanted].filter((k) => !removed.has(k));
844
+ touched.push({
845
+ id: e.id,
846
+ keys: Object.keys(e.keys),
847
+ ...(wanted.size ? { unset: [...removed] } : {}),
848
+ ...(absent.length ? { absent } : {}),
849
+ });
811
850
  }
812
851
  return { patches, touched };
813
852
  }
@@ -187,6 +187,11 @@ export class PageDoc {
187
187
  * cart drawer is there. `pageChildren` is for the RULES; this is for the
188
188
  * reader, and the `overlay: true` flag is how the two stay distinguishable.
189
189
  */
190
+ /**
191
+ * `chrome: false` (the tool's default) stops at a shared header/footer or an
192
+ * overlay: one line each, no kids. They are the same on every page and were
193
+ * ~70% of a routine outline (TTG gap #52).
194
+ */
190
195
  outline(opts = {}) {
191
196
  const depth = opts.depth ?? 1;
192
197
  const line = (id, level) => {
@@ -195,6 +200,9 @@ export class PageDoc {
195
200
  const out = { id, type: n.data.type, children: kidIds.length };
196
201
  if (n.data.name)
197
202
  out.name = n.data.name;
203
+ const label = n.specials?.label;
204
+ if ((n.data.type === 'accordion-content' || n.data.type === 'tab-content') && typeof label === 'string' && label)
205
+ out.label = label;
198
206
  if (level === 0) {
199
207
  if (isOverlay(this.doc, id))
200
208
  out.overlay = true;
@@ -205,7 +213,8 @@ export class PageDoc {
205
213
  out.global = true;
206
214
  if (appBlockRoot(this.doc, id) === id)
207
215
  out.app = true;
208
- if (level + 1 < depth) {
216
+ const collapsed = opts.chrome === false && level === 0 && (out.overlay || out.global);
217
+ if (level + 1 < depth && !collapsed) {
209
218
  // Satellites come FIRST, and are counted apart from `children`: they are
210
219
  // this node's own chrome, not content in it, and mixing the two would
211
220
  // make the child count disagree with `data.nodes` — the number every
@@ -29,6 +29,10 @@ export const FIX = {
29
29
  example_copy: 'Write this shop\'s own words: sb_set id "<id>", namespace specials, keys { "<key>": … }. ' +
30
30
  'A figure, a delivery or return promise, or a customer quote must be TRUE for this shop — ' +
31
31
  'if you do not know it, remove the element (sb_remove) rather than guess.',
32
+ link_colour: 'Colour each link inline: sb_set id "<id>", namespace specials, keys { "textHtml": … } with ' +
33
+ '<a href="…" style="color:inherit"> (or the brand colour) — no control or theme token reaches an <a> in text.',
34
+ default_font: 'Wear the site\'s text font: sb_set id "<id>", namespace style, base true, keys { "fontFamily": ' +
35
+ '"var(--wb-ts-text-2-family)" } — the variable tab-item and menu-item already use, so it follows the theme.',
32
36
  default_seed_copy: 'Write it in the shop\'s own language and ink: sb_set id "<id>", namespace specials, ' +
33
37
  'keys { "<key>": … }. It is a seeded satellite (an empty state, an element\'s chrome), ' +
34
38
  'so it only appears when the list is empty or the control is idle — sb_outline lists it ' +
@@ -152,6 +152,7 @@ export async function gatherReadiness(ctx, siteId, pageNodes, openPageId) {
152
152
  menuLinks,
153
153
  openPageType: open && open.isDefaultTemplate !== false ? open.type : undefined,
154
154
  openType: open?.type,
155
+ openPageId,
155
156
  products,
156
157
  liveGateways,
157
158
  shippingMethods,
@@ -112,9 +112,14 @@ const drafted = (pages, type) => pages.some((p) => p.type === type && p.status !
112
112
  /** "N published pages (a, b, c, …)" — the head of a problem sentence that names its pages. */
113
113
  function pageCount(rows) {
114
114
  const named = rows.map((p) => p.name).filter((n) => !!n).slice(0, 3);
115
- return (`${rows.length} published page${rows.length === 1 ? '' : 's'}` +
115
+ const drafts = rows.some((p) => p.status !== 'published');
116
+ return (`${rows.length} ${drafts ? '' : 'published '}page${rows.length === 1 ? '' : 's'}` +
116
117
  (named.length ? ` (${named.join(', ')}${rows.length > named.length ? ', …' : ''})` : ''));
117
118
  }
119
+ /** Said when the open DRAFT is among the rows — it is not live yet, and will go live like this. */
120
+ const draftNote = (rows) => rows.some((p) => p.status !== 'published') ? ' The open page is still a draft: fix it before its first publish.' : '';
121
+ /** Live, or the open page judged as if it were (see ReadinessInput.openPageId). */
122
+ const judged = (p, input) => p.status === 'published' || (!!input.openPageId && p.id === input.openPageId);
118
123
  /** "/about/", "/about?x=1" and "/about" are one address; "" is the home page. */
119
124
  function normalizePath(p) {
120
125
  const s = p.split(/[?#]/)[0].replace(/\/+$/, '');
@@ -158,7 +163,11 @@ export function unreachablePages(input) {
158
163
  for (const h of hrefsIn([...input.globalNodes, ...input.pageNodes]))
159
164
  reach.add(h);
160
165
  const byId = new Set(input.menuLinks.pageIds);
161
- return pages.filter((p) => p.status === 'published' &&
166
+ return pages.filter((p) => judged(p, input) &&
167
+ // A noIndex page asks to be left out of search; the sitemap leaves it out
168
+ // (page/sitemap/sitemap.go), so an unlinked one is a deliberate landing
169
+ // page, not an orphan (TTG gap #49).
170
+ p.settings?.noIndex !== true &&
162
171
  INDEXED_PAGE_TYPES.has(p.type) &&
163
172
  p.isHomepage !== true &&
164
173
  typeof p.id === 'string' &&
@@ -215,11 +224,13 @@ export function readinessGaps(input) {
215
224
  draft: false,
216
225
  problem: pageCount(orphans) +
217
226
  ' that no menu item and no link in the shared header, footer or any other page ' +
218
- 'points at. The address works and the sitemap lists it; no visitor ever arrives.',
227
+ 'points at. The address works and the sitemap lists it; no visitor arrives but by search.' +
228
+ draftNote(orphans),
219
229
  fix: 'Add it to the site menu — read GET /api/sites/{siteId}/menus, append ' +
220
230
  '{ label, link: { type: "page", pageId } } and PUT the menu back; every bound menu ' +
221
231
  'node follows. Or link it from the footer with sb_event go_to_url. A page kept out ' +
222
- 'on purpose (a landing page for ads) can stay out — say so.',
232
+ 'on purpose (a landing page for ads): sb_page_update seo {noIndex: true} — it leaves ' +
233
+ 'the sitemap and this check.',
223
234
  });
224
235
  }
225
236
  }
@@ -349,7 +360,7 @@ export function readinessGaps(input) {
349
360
  // an absent blob is "not read", not "empty".
350
361
  if (pages) {
351
362
  const bare = pages.filter((p) => {
352
- if (p.status !== 'published' || !INDEXED_PAGE_TYPES.has(p.type))
363
+ if (!judged(p, input) || !INDEXED_PAGE_TYPES.has(p.type))
353
364
  return false;
354
365
  const st = p.settings;
355
366
  if (!st || typeof st !== 'object')
@@ -365,7 +376,8 @@ export function readinessGaps(input) {
365
376
  (bare.length === 1 ? ' carries' : ' carry') +
366
377
  ' no settings.title or settings.description. Each serves the SITE NAME as its ' +
367
378
  '<title> and no meta description — a search result cannot tell them apart, and ' +
368
- 'nothing on the canvas or in a screenshot shows it.',
379
+ 'nothing on the canvas or in a screenshot shows it.' +
380
+ draftNote(bare),
369
381
  fix: 'sb_page_update {page_id, seo: {title, description}} — it merges into the page ' +
370
382
  'settings, keeping the rest. Title is what the tab and the result show (under ~60 ' +
371
383
  'chars); description is the two-line summary under it. seo.ogImage takes a share ' +
@@ -12,6 +12,7 @@ import { formFieldFindings, isFormDocument } from './formdoc.js';
12
12
  import { deadNavigation, hasPurchaseBinding, liveEventTable, PAYLOAD_NEEDS, soleNavigationClick } from './navhref.js';
13
13
  import { unknownValueNote, unknownWriteNote, vocabularyFor, vocabularyForWrite } from './vocabulary.js';
14
14
  import { iconNote } from './icons.js';
15
+ import { LINK_COLOUR, unstyledLinks } from './writecheck.js';
15
16
  /**
16
17
  * A defect somebody looking at the page would see.
17
18
  *
@@ -323,6 +324,11 @@ export function hardcodedRecords(code) {
323
324
  * can be an empty container. Findings are ordered by document order so a caller working
324
325
  * top-down meets them in the order they appear on screen.
325
326
  */
327
+ /** The first family of a CSS font-family list, unquoted; lowercased to compare. */
328
+ const family = (v, keepCase = false) => {
329
+ const f = (v.split(',')[0] ?? '').trim().replace(/^["']|["']$/g, '');
330
+ return keepCase ? f : f.toLowerCase();
331
+ };
326
332
  export function reviewDesign(doc,
327
333
  /** The site's forms by id → type, when read; lets `order_goes_nowhere` ask the form itself. */
328
334
  opts = {}) {
@@ -523,6 +529,28 @@ opts = {}) {
523
529
  });
524
530
  }
525
531
  }
532
+ // A LINK IN RICH TEXT IS THE BROWSER'S BLUE — see writecheck LINK_COLOUR (TTG gap #50).
533
+ const html = (n.specials ?? {}).textHtml;
534
+ if (typeof html === 'string' && unstyledLinks(html)) {
535
+ out.push({ code: 'link_colour', nodeId: id, type, key: 'textHtml', problem: LINK_COLOUR.problem, fix: fill('link_colour', { id }) });
536
+ }
537
+ // THE ELEMENT'S OWN LITERAL FONT ON A THEMED SITE (TTG gap #51). Most
538
+ // elements wear the theme's text style (`var(--wb-ts-…)`), but a few seed a
539
+ // LITERAL family — accordion-item's "Inter" — so an accordion header added
540
+ // to a site set in Be Vietnam Pro renders in Inter, and nothing said so.
541
+ // Only when the node still holds exactly the seed and the theme's body font
542
+ // is another family: a deliberate literal is the author's.
543
+ const ff = n.style?.fontFamily;
544
+ const seedFont = meta.defaults.style?.fontFamily;
545
+ if (opts.bodyFont && typeof ff === 'string' && ff === seedFont && !ff.includes('var(') && family(ff) !== family(opts.bodyFont)) {
546
+ out.push({
547
+ code: 'default_font',
548
+ nodeId: id,
549
+ type,
550
+ problem: `Still the element's own literal font "${ff}", while the site's text is set in "${family(opts.bodyFont, true)}" — it renders in a typeface nothing else on the page uses.`,
551
+ fix: fill('default_font', { id }),
552
+ });
553
+ }
526
554
  // THE DEMO OPTIONS. product-variants seeds config.attributes Color
527
555
  // Red/Green/Blue, Size S/M/L, and that authored config is the documented
528
556
  // FALLBACK for a product with no option axes of its own (schema binding.ts:
@@ -43,16 +43,28 @@ export function seededTypes() {
43
43
  */
44
44
  /** Rewrite every exact seed string the table carries, in place. */
45
45
  function localizeSeed(doc, table) {
46
- for (const n of Object.values(doc.nodes)) {
46
+ localizeNodes(Object.values(doc.nodes), table);
47
+ }
48
+ /**
49
+ * The same rewrite over loose nodes — what `sb_add` mints (an empty state's
50
+ * "No products yet"), which is no page seed but the same English (TTG gap #46).
51
+ * True when it changed something.
52
+ */
53
+ export function localizeNodes(nodes, table = SEED_COPY_VI) {
54
+ let changed = false;
55
+ for (const n of nodes) {
47
56
  const sp = n.specials;
48
57
  if (!sp)
49
58
  continue;
50
59
  for (const k of ['text', 'label']) {
51
60
  const v = sp[k];
52
- if (typeof v === 'string' && table[v])
61
+ if (typeof v === 'string' && table[v]) {
53
62
  sp[k] = table[v];
63
+ changed = true;
64
+ }
54
65
  }
55
66
  }
67
+ return changed;
56
68
  }
57
69
  export { SEED_COPY_VI } from './seedcopy.js';
58
70
  export function seedDocument(type, opts = {}) {
@@ -273,6 +273,13 @@ export function writeCheck(type, namespace, keys, opts = {}) {
273
273
  'never <p>/<div>, and put a separate block in its own node. A link goes to http(s), mailto, tel or a ' +
274
274
  'relative path; no comments.');
275
275
  }
276
+ // A LINK IN RICH TEXT IS THE BROWSER'S BLUE. Nothing styles `a` inside a
277
+ // text node — no element control, no theme token — so an <a> with no colour
278
+ // of its own paints the user-agent default rgb(0,0,238) (measured live on a
279
+ // #2e86ae site, TTG gap #50). The inline-rich gate keeps `style` color.
280
+ if (namespace === 'specials' && typeof v === 'string' && rich.includes(k) && !bad.length && unstyledLinks(v)) {
281
+ push(`link-colour:${type}.${k}`, 'link_colour', k, LINK_COLOUR.problem, LINK_COLOUR.fix);
282
+ }
276
283
  if (namespace === 'specials') {
277
284
  const un = unsupportedSettingNote(type, k, v);
278
285
  if (un)
@@ -292,6 +299,15 @@ export function writeCheck(type, namespace, keys, opts = {}) {
292
299
  }
293
300
  return out;
294
301
  }
302
+ /** `<a …>` tags in rich text that set no colour of their own. */
303
+ export function unstyledLinks(html) {
304
+ return (html.match(/<a\b[^>]*>/gi) ?? []).filter((tag) => !/style\s*=\s*["'][^"']*\bcolor\s*:/i.test(tag)).length;
305
+ }
306
+ export const LINK_COLOUR = {
307
+ problem: "A link in this rich text has no colour of its own, so it renders in the browser's default link blue " +
308
+ '(rgb(0,0,238)) with an underline — no element control or theme token reaches an <a> inside text.',
309
+ fix: 'Give each <a> its colour inline: <a href="…" style="color:inherit"> (or the brand colour); the rich-text gate keeps a style color.',
310
+ };
295
311
  /**
296
312
  * `specials.formRules` on a form root, judged against the open form document.
297
313
  *
@@ -1,4 +1,12 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { CallToolRequestSchema, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
3
+ /**
4
+ * WHICH TOOL CALL IS RUNNING, for code far below it that records history:
5
+ * `sb_undo` listed thirteen identical `put:…/source` entries and the caller
6
+ * could not tell the sb_remove from the sb_move (TTG gap #54). Per call, so a
7
+ * parallel free tool never relabels a serialized one.
8
+ */
9
+ export const currentCall = new AsyncLocalStorage();
2
10
  /**
3
11
  * ONE OPEN DOCUMENT, ONE CALL AT A TIME, IN ARRIVAL ORDER.
4
12
  *
@@ -32,12 +40,13 @@ export function serializeToolCalls(server, free) {
32
40
  if (schema !== CallToolRequestSchema)
33
41
  return set(schema, handler);
34
42
  return set(schema, ((req, extra) => {
43
+ const call = () => currentCall.run({ name: req.params.name, args: req.params.arguments ?? {} }, () => handler(req, extra));
35
44
  if (free(req.params.name))
36
- return handler(req, extra);
45
+ return call();
37
46
  const run = tail.then(() => {
38
47
  if (extra?.signal?.aborted)
39
48
  throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');
40
- return handler(req, extra);
49
+ return call();
41
50
  });
42
51
  tail = run.catch(() => undefined);
43
52
  return run;
@@ -13,7 +13,8 @@ import { addSubtree, setMany, baseOnlyKeys, moveNode, removeNode, duplicateNode,
13
13
  import { baseOnlyNote, splitBaseOnly } from '../domains/site/baseonly.js';
14
14
  import { detachNote, presetIdOf, presetLayer } from '../domains/site/theme.js';
15
15
  import { inertHintsFor } from '../domains/site/inert.js';
16
- import { emptyEntityTemplateNote, hasSeed, heldFromFirstPublish, layoutDocument, seedDocument, seedSummary, seededTypes, } from '../domains/site/storepage.js';
16
+ import { emptyEntityTemplateNote, hasSeed, heldFromFirstPublish, layoutDocument, localizeNodes, seedDocument, seedSummary, seededTypes, } from '../domains/site/storepage.js';
17
+ import { SEED_COPY_VI, langOf } from '../domains/site/seedcopy.js';
17
18
  import { PAGE_TYPES } from '../catalog/storepages.generated.js';
18
19
  import { skinLevelNote } from '../domains/site/fieldskin.js';
19
20
  import { siteTheme } from '../domains/site/theme-fetch.js';
@@ -48,8 +49,8 @@ import { FILTER_VALUE_TYPES, RESOURCE_KEYS, filterPatches, wantsRows } from '../
48
49
  * copies of a directive is how one of them quietly loses it. The fix for each
49
50
  * KIND is sent once under `fixes`, and the directive once per process.
50
51
  */
51
- export function reviewField(ctx, doc, formTypes, pageType, formDocType, formRedirects, siteLocale) {
52
- const all = reviewDesign(doc, { formTypes, pageType, formDocType, formRedirects, siteLocale });
52
+ export function reviewField(ctx, doc, formTypes, pageType, formDocType, formRedirects, siteLocale, bodyFont) {
53
+ const all = reviewDesign(doc, { formTypes, pageType, formDocType, formRedirects, siteLocale, bodyFont });
53
54
  if (all.length === 0)
54
55
  return {};
55
56
  // MAINTENANCE IS ADVICE, kept out of `findings`: it works for a visitor, so
@@ -102,6 +103,40 @@ export function saveRefusal(d, patches) {
102
103
  function noticeFor(ctx, dryRun) {
103
104
  return dryRun !== false ? (k, b) => ctx.notices.peek(k, b) : (k, b) => ctx.notices.once(k, b);
104
105
  }
106
+ /** The site's `settings.locale`, or undefined when unset or unreadable — never a reason to fail. */
107
+ async function siteLocaleOf(ctx, siteId) {
108
+ return request({
109
+ base: ctx.base,
110
+ method: 'GET',
111
+ path: `/api/sites/${encodeURIComponent(siteId)}/settings`,
112
+ token: siteToken(ctx),
113
+ fetchImpl: ctx.fetchImpl,
114
+ })
115
+ .then((r) => {
116
+ const l = r?.settings?.locale;
117
+ return typeof l === 'string' && l ? l : undefined;
118
+ })
119
+ .catch(() => undefined);
120
+ }
121
+ /**
122
+ * WHAT `sb_add` MINTED, BY ID AND TYPE, satellites apart (TTG gap #53). A flat id
123
+ * list interleaved an empty state's heading with the caller's own children, so
124
+ * mapping ids to nodes was guesswork. A satellite hangs off its owner's config,
125
+ * not its child list; everything under one is satellite content too.
126
+ */
127
+ function mintedIds(after, ids) {
128
+ const added = {};
129
+ const satellites = {};
130
+ for (const id of ids) {
131
+ const n = after.doc.nodes[id];
132
+ if (!n)
133
+ continue;
134
+ const parent = n.data.parent ? after.doc.nodes[n.data.parent] : undefined;
135
+ const sat = !!parent && (n.data.parent in satellites || !parent.data.nodes.includes(id));
136
+ (sat ? satellites : added)[id] = n.data.type;
137
+ }
138
+ return { added, satellites };
139
+ }
105
140
  export class PageSession {
106
141
  ctx;
107
142
  doc = null;
@@ -1381,9 +1416,12 @@ export function registerPageTools(server, ctx) {
1381
1416
  description: 'The open page as a compressed tree — id, type, name, child count, band, and whether a ' +
1382
1417
  'node is a shared global or a site overlay. Never the raw document: a real page is ' +
1383
1418
  'hundreds of KB of JSON.',
1384
- inputSchema: { depth: z.number().int().min(1).max(6).optional() },
1419
+ inputSchema: {
1420
+ depth: z.number().int().min(1).max(6).optional(),
1421
+ chrome: z.boolean().optional().describe('Expand shared chrome and overlays (default one line each)'),
1422
+ },
1385
1423
  annotations: { readOnlyHint: true },
1386
- }, async ({ depth }) => text(session.current().outline({ depth })));
1424
+ }, async ({ depth, chrome }) => text(session.current().outline({ depth, chrome: chrome === true })));
1387
1425
  server.registerTool('sb_node_read', {
1388
1426
  description: 'One node in full — style, config, specials, per-breakpoint overrides, bindings.',
1389
1427
  inputSchema: { id: z.string() },
@@ -1400,7 +1438,16 @@ export function registerPageTools(server, ctx) {
1400
1438
  // there to read, so it invented one. See domains/site/theme.ts.
1401
1439
  const { theme, from } = await siteTheme(ctx, session.site());
1402
1440
  const preset = presetLayer(theme, from, node);
1403
- return text({ node, ...(preset ? { preset } : {}), ...(warn ? { warning: warn } : {}) });
1441
+ // NO SCENE, NO SCENE KEYS (TTG gap #52): every section/block carries 13
1442
+ // seeded backgroundScene* defaults, ~40% of a read, all inert while the
1443
+ // source is empty. Left out of the answer only — the node is untouched.
1444
+ const cfg = node.config ?? {};
1445
+ const sceneOff = 'backgroundSceneSource' in cfg && !cfg.backgroundSceneSource;
1446
+ const shown = sceneOff
1447
+ ? { ...node, config: Object.fromEntries(Object.entries(cfg).filter(([k]) => !k.startsWith('backgroundScene'))) }
1448
+ : node;
1449
+ const omitted = sceneOff ? ctx.notices.once('node-read-scene', 'config.backgroundScene* omitted while backgroundSceneSource is empty (no scene)') : undefined;
1450
+ return text({ node: shown, ...(omitted ? { omitted } : {}), ...(preset ? { preset } : {}), ...(warn ? { warning: warn } : {}) });
1404
1451
  });
1405
1452
  server.registerTool('sb_catalog_search', {
1406
1453
  description: 'Find an element type by what it does — or OMIT query to browse every type, the only ' +
@@ -1420,7 +1467,12 @@ export function registerPageTools(server, ctx) {
1420
1467
  async ({ query, limit, detail }) => text(/^\s*icon:/i.test(query ?? '')
1421
1468
  ? { icons: searchIcons(query.replace(/^\s*icon:/i, '').trim(), limit ?? 30) }
1422
1469
  : query && query.trim()
1423
- ? searchWithTemplates(query, catalogMatches(query, { limit, detail }))
1470
+ ? searchWithTemplates(query, catalogMatches(query, { limit, detail }).map((m) => {
1471
+ // Hints sent here are not re-sent by sb_traits_for (gap #52).
1472
+ if (detail)
1473
+ ctx.notices.once(`hints:${m.type}`, 'x');
1474
+ return m;
1475
+ }))
1424
1476
  : {
1425
1477
  elements: catalogBrowse(),
1426
1478
  note: 'Every element type, grouped as the palette groups them. Pass a TYPE as query ' +
@@ -1437,7 +1489,23 @@ export function registerPageTools(server, ctx) {
1437
1489
  control: z.string().optional().describe('Narrow to one control, e.g. "font_size"'),
1438
1490
  },
1439
1491
  annotations: { readOnlyHint: true },
1440
- }, async ({ type, control }) => text(traitsFor(type, control)));
1492
+ },
1493
+ // SAID ONCE PER PROCESS (TTG gap #52): an element's hints (also in
1494
+ // sb_catalog_search detail:true) and the prose and animation vocabulary every
1495
+ // element repeats — ~8 KB of list-dataset's ~16 KB, on every call.
1496
+ async ({ type, control }) => {
1497
+ const r = traitsFor(type, control);
1498
+ if (control)
1499
+ return text(r);
1500
+ const SAID = 'said earlier in this session';
1501
+ if (!ctx.notices.once(`hints:${type}`, 'x'))
1502
+ r.hints = SAID;
1503
+ for (const k of ['animation', 'animation_values', 'undeclared_note', 'style_is_open_css']) {
1504
+ if (k in r && !ctx.notices.once(`traits:${k}`, 'x'))
1505
+ r[k] = SAID;
1506
+ }
1507
+ return text(r);
1508
+ });
1441
1509
  server.registerTool('sb_add', {
1442
1510
  description: 'Add an element — or a whole NESTED subtree — under a parent. One call builds a complete ' +
1443
1511
  'section: pass children rather than calling this once per node.',
@@ -1463,6 +1531,17 @@ export function registerPageTools(server, ctx) {
1463
1531
  const at = index ?? (mid < rootKids ? mid : undefined);
1464
1532
  const { patches, ids, idOf } = addSubtree(d, parent_id, spec, at, guard);
1465
1533
  const forced = guard.forced.length ? { forced: guard.forced } : {};
1534
+ // THE SEED COPY IN THE SITE'S LANGUAGE (TTG gap #46): an empty state minted
1535
+ // here said "No products yet" on a Vietnamese store, while sb_page_create
1536
+ // already seeds through SEED_COPY_VI. Same default as there — vi when the
1537
+ // locale is unread — and the settings read only when there is copy to move.
1538
+ const minted = patches.filter((p) => p.op === 'set' && p.path.length === 2).map((p) => p.value);
1539
+ const seeded = minted.some((n) => ['text', 'label'].some((k) => {
1540
+ const v = n.specials?.[k];
1541
+ return typeof v === 'string' && !!SEED_COPY_VI[v];
1542
+ }));
1543
+ if (seeded && langOf((await siteLocaleOf(ctx, session.site())) ?? 'vi') === 'vi')
1544
+ localizeNodes(minted);
1466
1545
  // ELEMENTS THAT RENDER CONVINCINGLY WHILE WIRED TO NOTHING. The add
1467
1546
  // succeeds completely, the tree is correct and the page photographs
1468
1547
  // right, so neither sb_review nor sb_look can see the gap — the moment
@@ -1540,7 +1619,17 @@ export function registerPageTools(server, ctx) {
1540
1619
  });
1541
1620
  }
1542
1621
  await session.applyAndSave(patches);
1543
- return text({ added: ids, rev: d.rev, ...(inert ? { inert } : {}), ...checks, ...base_only, ...filterOut, ...forced });
1622
+ const { added, satellites } = mintedIds(session.current(), ids);
1623
+ return text({
1624
+ added,
1625
+ ...(Object.keys(satellites).length ? { satellites } : {}),
1626
+ rev: d.rev,
1627
+ ...(inert ? { inert } : {}),
1628
+ ...checks,
1629
+ ...base_only,
1630
+ ...filterOut,
1631
+ ...forced,
1632
+ });
1544
1633
  });
1545
1634
  server.registerTool('sb_set', {
1546
1635
  description: 'Write style, config or specials keys on one node, or on many through edits (one ' +
@@ -1567,7 +1656,7 @@ export function registerPageTools(server, ctx) {
1567
1656
  .array(z.object({
1568
1657
  id: z.string(),
1569
1658
  namespace: z.enum(['style', 'config', 'specials']),
1570
- keys: z.record(z.unknown()),
1659
+ keys: z.record(z.unknown()).optional(),
1571
1660
  breakpoint: z.enum(['desktop', 'laptop', 'tablet', 'mobile']).optional(),
1572
1661
  base: z.boolean().optional(),
1573
1662
  state: z.string().optional(),
@@ -1582,7 +1671,11 @@ export function registerPageTools(server, ctx) {
1582
1671
  const d = session.current();
1583
1672
  const say = noticeFor(ctx, dry_run);
1584
1673
  // One shape inside: a single edit is a batch of one.
1585
- const batch = edits ?? [];
1674
+ const batch = (edits ?? []).map((e) => {
1675
+ if (!e.keys && !e.unset?.length)
1676
+ throw new Error(`sbuilder: sb_set edit for ${e.id} needs keys or unset`);
1677
+ return { ...e, keys: e.keys ?? {}, breakpoint: e.breakpoint };
1678
+ });
1586
1679
  if (!edits) {
1587
1680
  // `keys` is optional when `unset` carries the work: a pure removal is a
1588
1681
  // legitimate edit, and demanding an empty object alongside it would make
@@ -1808,6 +1901,8 @@ export function registerPageTools(server, ctx) {
1808
1901
  const warn = warnings[batch[0].id];
1809
1902
  return text({
1810
1903
  set: touched[0].keys,
1904
+ ...(touched[0].unset ? { unset: touched[0].unset } : {}),
1905
+ ...(touched[0].absent ? { absent: touched[0].absent } : {}),
1811
1906
  rev: d.rev,
1812
1907
  ...(warn ? { warning: warn } : {}),
1813
1908
  ...shared,
@@ -1938,7 +2033,19 @@ export function registerPageTools(server, ctx) {
1938
2033
  catch {
1939
2034
  // Readiness is additional information, never the reason a review fails.
1940
2035
  }
1941
- const field = reviewField(ctx, doc, formTypes, pageType, session.formType(), formRedirects, siteLocale);
2036
+ // The site's body font, for `default_font` — a SITE theme only: the starter
2037
+ // is set in Inter, so it can never disagree with an element's literal Inter.
2038
+ let bodyFont;
2039
+ try {
2040
+ const { theme, from } = await siteTheme(ctx, session.site());
2041
+ const f = theme.textStyles.find((t) => t.slug === 'text-2')?.base?.fontFamily;
2042
+ if (from === 'site' && typeof f === 'string' && f && !f.includes('var('))
2043
+ bodyFont = f;
2044
+ }
2045
+ catch {
2046
+ // A theme that cannot be read is a finding nobody gets, never a failed review.
2047
+ }
2048
+ const field = reviewField(ctx, doc, formTypes, pageType, session.formType(), formRedirects, siteLocale, bodyFont);
1942
2049
  // Clean = no finding a visitor meets; `advice` (maintenance) rides beside the verdict.
1943
2050
  const clean = !field.findings;
1944
2051
  return text({
@@ -1971,13 +2078,16 @@ export function registerPageTools(server, ctx) {
1971
2078
  if (to_site_id || parent_id || index !== undefined) {
1972
2079
  throw new Error('sbuilder: to_site_id, parent_id and index go with to_page_id — the page the copy lands on.');
1973
2080
  }
1974
- const { patches, ids } = duplicateNode(d, id, guard);
2081
+ const { patches, ids, map } = duplicateNode(d, id, guard);
1975
2082
  if (dry_run !== false) {
1976
2083
  const refuse = session.wouldRefuse(patches);
1977
2084
  return text({ dry_run: true, would_copy: ids.length, ...(refuse ? { would_refuse: refuse } : {}), ...forcedOf() });
1978
2085
  }
1979
2086
  await session.applyAndSave(patches);
1980
- return text({ duplicated: id, into: ids[0], nodes: ids.length, rev: d.rev, ...forcedOf() });
2087
+ // EVERY copy's id, not just the root's: editing the copied row's answer
2088
+ // used to take a whole sb_outline to find (TTG gap #53).
2089
+ const copies = Object.fromEntries(Object.entries(map).map(([from, to]) => [from, [to, d.doc.nodes[from]?.data.type ?? '']]));
2090
+ return text({ duplicated: id, into: ids[0], copies, rev: d.rev, ...forcedOf() });
1981
2091
  }
1982
2092
  // ONTO ANOTHER PAGE — the editor's paste (`useCanvasClipboard.ts`).
1983
2093
  const from = session.location();
@@ -2531,21 +2641,7 @@ export function registerPageTools(server, ctx) {
2531
2641
  // The SITE's language when the caller named none — the seed's English
2532
2642
  // copy is rewritten for a Vietnamese site (SEED_COPY_VI). Unreadable
2533
2643
  // settings fall back to the old default rather than block the create.
2534
- const lang = locale ??
2535
- (layout
2536
- ? undefined
2537
- : await request({
2538
- base: ctx.base,
2539
- method: 'GET',
2540
- path: `/api/sites/${encodeURIComponent(site_id)}/settings`,
2541
- token: siteToken(ctx),
2542
- fetchImpl: ctx.fetchImpl,
2543
- })
2544
- .then((r) => {
2545
- const l = r?.settings?.locale;
2546
- return typeof l === 'string' && l ? l : undefined;
2547
- })
2548
- .catch(() => undefined));
2644
+ const lang = locale ?? (layout ? undefined : await siteLocaleOf(ctx, site_id));
2549
2645
  const document = layout ? layoutDocument(layout) : seedDocument(type ?? '', { locale: lang, headline });
2550
2646
  if (document) {
2551
2647
  try {
@@ -2712,7 +2808,14 @@ export function registerPageTools(server, ctx) {
2712
2808
  : {}),
2713
2809
  });
2714
2810
  if (dry_run !== false) {
2715
- return text({ dry_run: true, would_post: path, body, ...draftNote(drafts, fresh) });
2811
+ // NO CASCADE PREVIEW EXISTS on the platform (page/globalservice.go
2812
+ // cascadeTargets runs inside publish only), so the dry run says the rule
2813
+ // rather than a list it cannot know (TTG gap #59); the real answer names
2814
+ // the pages under `cascaded`.
2815
+ const cascade = ctx.notices.peek('publish-cascade', 'Publishing also republishes, from their LAST PUBLISHED version (never their draft), every live page ' +
2816
+ 'whose shared header/footer, overlay (cart drawer, pop-up) or app block is behind its master. The ' +
2817
+ 'platform offers no preview of that list; the real publish names them under cascaded.');
2818
+ return text({ dry_run: true, would_post: path, body, ...draftNote(drafts, fresh), ...(cascade ? { cascade_note: cascade } : {}) });
2716
2819
  }
2717
2820
  const res = (await request({
2718
2821
  base: ctx.base,
@@ -2901,9 +3004,10 @@ export function registerPageTools(server, ctx) {
2901
3004
  const recovery = {
2902
3005
  versions,
2903
3006
  history,
2904
- note: 'The platform appends an autosave checkpoint on EVERY draft save and mints a ' +
2905
- 'labelled snapshot on demand, and both outlive this process — so a checkpoint ' +
2906
- 'before a whole-document PUT is already taken. Restore with sb_api_call ' +
3007
+ note: 'The platform keeps autosave checkpoints — one author\'s saves within 5 min of the ' +
3008
+ 'newest fold into that ONE row (web_builder e3b2ee056), so many saves can list as one ' +
3009
+ 'checkpoint holding the latest — and mints a labelled snapshot on demand; both outlive ' +
3010
+ 'this process. Snapshot before a risky whole-document PUT. Restore with sb_api_call ' +
2907
3011
  '"post:/api/sites/{siteId}/pages/{pageId}/versions/{versionId}/restore" or the ' +
2908
3012
  'history twin. A RESTORE CHANGES THE DRAFT ONLY: publish afterwards, or the ' +
2909
3013
  'storefront keeps serving the page you just rolled back from. The platform writes ' +
@@ -2968,11 +3072,11 @@ export function registerPageTools(server, ctx) {
2968
3072
  'copy: the editor loads the draft once and does not re-read it, so a save made here ' +
2969
3073
  'is invisible there until the tab is reloaded — and that tab\'s next save would ' +
2970
3074
  'store its older copy over this one. Reload the editor before editing there.',
2971
- // THE CHECKPOINT BEFORE A PUT ALREADY EXISTS, and that is worth
2972
- // stating rather than re-implementing: `saveDraftRaw` appends an
2973
- // autosave checkpoint on EVERY draft save, bounded by the service's
2974
- // own keep count, and `SaveVersion` mints a labelled snapshot beside
2975
- // it. What was missing was anyone SAYING so — this repo recorded for
3075
+ // THE CHECKPOINTS EXIST, and that is worth stating rather than
3076
+ // re-implementing: `saveDraftRaw` keeps autosave checkpoints — since
3077
+ // web_builder e3b2ee056 one author's saves inside 5 min fold into the
3078
+ // newest row (TTG gap #56: 15 saves listed one) — and `SaveVersion`
3079
+ // mints a labelled snapshot beside them. What was missing was anyone SAYING so — this repo recorded for
2976
3080
  // three phases that a wrecked draft was unrecoverable, which was true
2977
3081
  // of the OpenAPI document and false of the platform.
2978
3082
  //
@@ -388,7 +388,18 @@ function mergeSettings(...layers) {
388
388
  }
389
389
  return out;
390
390
  }
391
- async function seedForm(ctx, session, siteId, key, formName, pageName, headline, dryRun, settings) {
391
+ async function seedForm(ctx, session, siteId, key, formName, pageName, headline, dryRun, settings, parentId) {
392
+ // ON THE OPEN PAGE (TTG gap #58) — a `form` node is a reference
393
+ // (`specials.formId`) and goes anywhere a container does, so the only new part
394
+ // is placing it. Checked BEFORE the form exists: a refused placement must not
395
+ // leave a form nobody asked for to sit unplaced.
396
+ if (parentId) {
397
+ if (pageName)
398
+ throw new Error('sbuilder: action:"form" takes page_name (a new page) or node_id (the open page), not both.');
399
+ if (session.site() !== siteId)
400
+ throw new Error(`sbuilder: the open page is on site ${session.site()}, not ${siteId} — open a page of this site first.`);
401
+ addSubtree(session.current(), parentId, { type: 'form', specials: { formId: 'frm_check' } });
402
+ }
392
403
  const tpl = FORM_TEMPLATES[key];
393
404
  const site = encodeURIComponent(siteId);
394
405
  const name = formName ?? tpl.key;
@@ -426,16 +437,18 @@ async function seedForm(ctx, session, siteId, key, formName, pageName, headline,
426
437
  path: `/api/sites/${site}/forms/{formId}/document`,
427
438
  },
428
439
  ],
429
- ...(pageName
430
- ? {
431
- would_also: `create a page named ${JSON.stringify(pageName)} of type "${pageTypeFor(key)}" and put ` +
432
- 'the form on it, so the form has an address a header can link to — wearing the ' +
433
- "header and footer the site's home page wears",
434
- }
435
- : {
436
- no_page: 'Only the form. Pass page_name to have the page made and the form placed ' +
437
- 'on it in this same call — the three steps that otherwise get skipped.',
438
- }),
440
+ ...(parentId
441
+ ? { would_also: `place a form node bound to the new form inside ${parentId} on the open page` }
442
+ : pageName
443
+ ? {
444
+ would_also: `create a page named ${JSON.stringify(pageName)} of type "${pageTypeFor(key)}" and put ` +
445
+ 'the form on it, so the form has an address a header can link to — wearing the ' +
446
+ "header and footer the site's home page wears",
447
+ }
448
+ : {
449
+ no_page: 'Only the form. Pass page_name to have the page made and the form placed ' +
450
+ 'on it in this same call — the three steps that otherwise get skipped.',
451
+ }),
439
452
  preview: redact({ name, type: tpl.type }),
440
453
  ...(settings ? { settings: redact(mergeSettings(tpl.settings, settings)) } : {}),
441
454
  ...settingsNote,
@@ -483,6 +496,17 @@ async function seedForm(ctx, session, siteId, key, formName, pageName, headline,
483
496
  // for — the same rule the seed follows in sb_page_create.
484
497
  let page;
485
498
  let page_failed;
499
+ let placed;
500
+ if (parentId) {
501
+ try {
502
+ const { patches, ids } = addSubtree(session.current(), parentId, { type: 'form', specials: { formId: form.id } });
503
+ await session.applyAndSave(patches);
504
+ placed = { id: ids[0], parent: parentId };
505
+ }
506
+ catch (e) {
507
+ page_failed = e.message.replace(/^sbuilder:\s*/, '').slice(0, 160);
508
+ }
509
+ }
486
510
  if (pageName) {
487
511
  try {
488
512
  page = await placeFormOnPage(ctx, session, siteId, form.id, pageName, headline, pageTypeFor(key));
@@ -496,15 +520,19 @@ async function seedForm(ctx, session, siteId, key, formName, pageName, headline,
496
520
  fields,
497
521
  ...settingsNote,
498
522
  ...(page ? { page } : {}),
523
+ ...(placed ? { placed } : {}),
499
524
  ...(page_failed ? { page_failed } : {}),
500
- next: page
501
- ? `The form is on page ${page.id}. Publish it with sb_publish, and link to it from the ` +
502
- 'header. The submit button lives in the FORM DOCUMENT, not on the page, and a page ' +
503
- 'republish is what makes a form-document edit visible.'
504
- : `Place it: sb_add a "form" element, then sb_set its specials.formId to "${form.id}" — ` +
505
- 'or pass page_name to have that page made for you. The submit button lives in the FORM ' +
506
- 'DOCUMENT, not on the page, and a page republish is what makes a form-document edit ' +
507
- 'visible.',
525
+ next: placed
526
+ ? `The form is on the open page as ${placed.id}. Publish the page with sb_publish. The submit ` +
527
+ 'button lives in the FORM DOCUMENT (sb_page_open form_id), not on the page.'
528
+ : page
529
+ ? `The form is on page ${page.id}. Publish it with sb_publish, and link to it from the ` +
530
+ 'header. The submit button lives in the FORM DOCUMENT, not on the page, and a page ' +
531
+ 'republish is what makes a form-document edit visible.'
532
+ : `Place it: sb_add a "form" element, then sb_set its specials.formId to "${form.id}" — ` +
533
+ 'or pass page_name to have that page made for you. The submit button lives in the FORM ' +
534
+ 'DOCUMENT, not on the page, and a page republish is what makes a form-document edit ' +
535
+ 'visible.',
508
536
  };
509
537
  }
510
538
  export function registerStoreTools(server, ctx, session) {
@@ -576,7 +604,7 @@ export function registerStoreTools(server, ctx, session) {
576
604
  node_id: z
577
605
  .string()
578
606
  .optional()
579
- .describe('action:"menu" — the menu node; "global_promote"/"template_save" — the section'),
607
+ .describe('action:"menu" — the menu node; "global_promote"/"template_save" — the section; "form" — a node of the open page to place it in'),
580
608
  global_kind: z.enum(['header', 'footer', 'custom']).optional(),
581
609
  template_id: z.string().optional().describe('action:"template_save" — overwrite this template\'s content'),
582
610
  menu_id: z.string().optional(),
@@ -689,7 +717,7 @@ export function registerStoreTools(server, ctx, session) {
689
717
  if (!template) {
690
718
  throw new Error(`sbuilder: action:"form" needs a template. One of: ${FORM_TEMPLATE_KEYS.join(', ')}.`);
691
719
  }
692
- return text(await seedForm(ctx, session, siteId, template, name, page_name, headline, dry_run !== false, settings));
720
+ return text(await seedForm(ctx, session, siteId, template, name, page_name, headline, dry_run !== false, settings, node_id));
693
721
  }
694
722
  const lang = (language ?? 'vi');
695
723
  if (action === 'checkout_sync')
@@ -30,6 +30,22 @@ import { findOperation } from '../catalog/search.js';
30
30
  import { request, redact } from '../transport/http.js';
31
31
  import { text } from '../mcp/response.js';
32
32
  import { tokenFor } from './api.js';
33
+ import { currentCall } from '../mcp/serial.js';
34
+ import { sourcePath } from '../transport/pages.js';
35
+ /** "sb_remove ac_1", "sb_add flex-section under ROOT", "sb_set bt_1, bt_2" — ids and types only, never values. */
36
+ export function summarize(name, args) {
37
+ const str = (v) => (typeof v === 'string' && v ? v : '');
38
+ const spec = args.spec;
39
+ const edits = Array.isArray(args.edits) ? args.edits.map((e) => str(e.id)).filter(Boolean) : [];
40
+ const parts = [
41
+ str(spec?.type),
42
+ str(args.id),
43
+ args.parent_id ? `under ${str(args.parent_id)}` : '',
44
+ edits.join(', '),
45
+ str(args.action),
46
+ ].filter(Boolean);
47
+ return [name, ...parts].join(' ').slice(0, 100);
48
+ }
33
49
  /** Twenty is more than a session reaches back, and bounds what one process holds. */
34
50
  const CAP = 20;
35
51
  /**
@@ -84,12 +100,14 @@ export class UndoLog {
84
100
  const body = restoreBodyFrom(operationId, before);
85
101
  if (!body)
86
102
  return;
103
+ const call = currentCall.getStore();
87
104
  this.entries.unshift({
88
105
  index: 0,
89
106
  operationId,
90
107
  path,
91
108
  at: new Date().toISOString(),
92
109
  fields: Object.keys(body),
110
+ ...(call ? { tool: call.name, summary: summarize(call.name, call.args) } : {}),
93
111
  body,
94
112
  ...(meta.session ? { session: true } : {}),
95
113
  ...(meta.peer?.length ? { peer: meta.peer } : {}),
@@ -151,15 +169,26 @@ export function registerUndoTools(server, ctx, pages) {
151
169
  '.../pages/{pageId}/history) survives a restart. No argument lists what is undoable.',
152
170
  inputSchema: {
153
171
  index: z.number().int().min(1).optional().describe('1 is the most recent write'),
172
+ all: z.boolean().optional().describe('Every page, not just the open one'),
154
173
  dry_run: z.boolean().optional(),
155
174
  },
156
175
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
157
- }, async ({ index, dry_run }) => {
158
- const undoable = ctx.undo.list();
176
+ }, async ({ index, all, dry_run }) => {
159
177
  if (index === undefined) {
178
+ // SCOPED TO THE OPEN PAGE (TTG gap #54): an entry from another page,
179
+ // hours old, sat in the list as just another `put:…/source`. Another
180
+ // page's saves are counted and hidden; non-page writes always show.
181
+ // Indexes stay global, so `index` means the same with or without `all`.
182
+ const every = ctx.undo.list();
183
+ const here = pages.page();
184
+ const mine = here ? sourcePath(here.siteId, here.pageId) : undefined;
185
+ const otherPage = (e) => !all && !!mine && e.operationId === PAGE_SOURCE_OP && e.path !== mine;
186
+ const undoable = every.filter((e) => !otherPage(e));
187
+ const hidden = every.length - undoable.length;
160
188
  return text({
161
189
  undoable,
162
- ...(undoable.length === 0
190
+ ...(hidden ? { other_pages: hidden, other_pages_note: 'Saves to other pages; all:true lists them.' } : {}),
191
+ ...(every.length === 0
163
192
  ? {
164
193
  note: 'Nothing to undo. Page and form saves made here and PUTs through sb_api_call ' +
165
194
  'are recorded, only in this process.',
@@ -15,6 +15,18 @@ export function sourcePath(siteId, pageId) {
15
15
  * merged onto ROOT. That is the tree to edit; the server strips the overlays
16
16
  * back out on write.
17
17
  */
18
+ /**
19
+ * A 404 on a page's source is a DELETED page (or a wrong id), and the session
20
+ * may still be pointing at it: a bare "source not found [http 404]" after an
21
+ * sb_api_call delete told the caller nothing (TTG gap #57). Same status and
22
+ * code, a sentence that says what to do.
23
+ */
24
+ const gone = (pageId) => (e) => {
25
+ if (e instanceof ApiError && e.status === 404) {
26
+ throw new ApiError(404, e.code, `page ${pageId} no longer exists (deleted, or a wrong id) — sb_page_open another page; sb_page_list lists them`, e.details, e.fields);
27
+ }
28
+ throw e;
29
+ };
18
30
  export async function loadSource(ctx, siteId, pageId) {
19
31
  const out = (await request({
20
32
  base: ctx.base,
@@ -22,7 +34,7 @@ export async function loadSource(ctx, siteId, pageId) {
22
34
  path: sourcePath(siteId, pageId),
23
35
  token: siteToken(ctx),
24
36
  fetchImpl: ctx.fetchImpl,
25
- }));
37
+ }).catch(gone(pageId)));
26
38
  return out.source;
27
39
  }
28
40
  /**
@@ -59,6 +71,6 @@ livePeer) {
59
71
  body: { document, schemaVersion: document.schema_version ?? 1, ...(baseRev ? { baseRev } : {}) },
60
72
  ...(livePeer && LIVE_PEER.test(livePeer) ? { headers: { 'X-WB-Live-Peer': livePeer } } : {}),
61
73
  fetchImpl: ctx.fetchImpl,
62
- }));
74
+ }).catch(gone(pageId)));
63
75
  return out.source;
64
76
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbuilder-mcp",
3
- "version": "0.98.9",
3
+ "version": "0.99.0",
4
4
  "description": "MCP server that designs and operates a Store Builder site — pages, data, theme and publish — through the platform's own API and live-edit protocol.",
5
5
  "mcpName": "io.github.vuluu2k/sbuilder-mcp",
6
6
  "type": "module",