@commercelayer/agent-cli 0.2.2 → 0.2.3

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
@@ -14,13 +14,16 @@ npx -y @commercelayer/agent-cli@latest init --name "The Blue Brand" # runs c11
14
14
  ## Commands
15
15
  | Command | Does |
16
16
  | --- | --- |
17
- | `init [--name <business name>]` | Create a sandbox store, with no login. The name (the folder name when absent) names the organization; the org slug and store hostname derive from it, numbered when taken. Writes `store.yml` (a commented template) and `credentials`. Reuses the store if they exist. |
18
- | `plan` | Validate `store.yml` and the product files, and list what `apply` would create, update or delete: markets, products, promotions, images, and the store's name, policies and theme; `warnings` flags more than 10 active promotions without a coupon. `missing_images` lists `img/<file>` references with no file in `.commercelayer/img/` (`apply` refuses them); `unused_images` lists files there that nothing references. |
19
- | `apply [--allow-delete] [--full]` | Make the store match the files, the website included: the theme settings, and the images in `.commercelayer/img/` that the theme and products reference, uploaded when new or changed (unused ones are dropped from the store host). Refuses deletes without `--allow-delete`. Product changes go through a Commerce Layer import: `apply` waits for it, with progress as JSON lines on stderr, and prints one result. `apply_failed` lists the products and promotions Commerce Layer refused. While Commerce Layer is busy or unavailable, `apply` keeps reading (backing off on busy) and writes a `retrying` line. `apply_pending` means the import keeps going after 10 minutes, and `c11r status` follows it. An apply still running is finished before a new one starts. `--full` re-imports every product and price, after edits in the Commerce Layer dashboard. |
17
+ | `init [--name <business name>]` | Create a sandbox store, with no login. The name (the folder name when absent) names the organization; the org slug and store hostname derive from it, numbered when taken. Writes `store.yml` (a commented template) and `credentials`, plus a short `AGENTS.md` and `CLAUDE.md` section (appended to an existing file, never twice) that sends later agents in the repo to [commercelayer.ai/skills.md](https://commercelayer.ai/skills.md). Reuses the store if they exist. |
18
+ | `plan` | Validate `store.yml` and the product files, and list what `apply` would create, update or delete: markets, products, images, and the store's name, policies and theme. `missing_images` lists `img/<file>` references with no file in `.commercelayer/img/` (`apply` refuses them); `unused_images` lists files there that nothing references. |
19
+ | `apply [--allow-delete] [--full]` | Make the store match the files, the website included: the theme settings, and the images in `.commercelayer/img/` that the theme and products reference, uploaded when new or changed (unused ones are dropped from the store host). Refuses deletes without `--allow-delete`. Product changes go through a Commerce Layer import: `apply` waits for it, with progress as JSON lines on stderr, and prints one result. `apply_failed` lists the products Commerce Layer refused. While Commerce Layer is busy or unavailable, `apply` keeps reading (backing off on busy) and writes a `retrying` line. `apply_pending` means the import keeps going after 10 minutes, and `c11r status` follows it. An apply still running is finished before a new one starts. `--full` re-imports every product and price, after edits in the Commerce Layer dashboard. |
20
20
  | `catalog pull` | Read the products from the catalog source in `store.yml` (a Supabase table, a Google Sheet or a Google Merchant Center feed) into `.commercelayer/products/catalog.csv`. Then `plan` and `apply` as usual. |
21
21
  | `storefront init [--force]` | Custom storefronts only. Write a static storefront on [drop-in.js](https://commercelayer.github.io/drop-in.js/), no build step, wired to the sandbox's sales channel. `index.html`: the config block, the products grouped by top-level category with a navigation, a minicart that slides in on add to cart, the hosted cart and checkout, and a product page at `#/p/<sku>` built from `<template id="product-template">` and the `#products` data. `styles.css`: theme tokens first (`--paper`, `--ink`, `--muted`, `--line`, `--accent`, `--on-accent`, `--radius`, `--font`), which also restyle drop-in.js's prices, buttons and links, so a dark theme is a token change; then the drop-in.js overrides, then the page. `app.js`: the market switch, the category links and the product page. Product images are the store's, at `/img/<file>` (from `.commercelayer/img/`, uploaded by `apply`); products with no image get a neutral tile. The site's own files go in `storefront/assets/`. Refuses to overwrite without the flag; with it, rewrites the three files. |
22
22
  | `storefront publish` | Custom storefronts only. Upload the folder at `storefront.path` (default `storefront`) to the store host, where it replaces the hosted theme, leaving out dotfiles. `/img/` on the store host is always the store's images, so files under the folder's `img/` are not served: publish lists them as `not_served`. |
23
23
  | `storefront check` | Custom storefronts only. Read the published storefront at the preview URL and check it: drop-in.js and its config block wired to this store, the drop-in elements, an add to cart for every product and none for unknown skus, every image loading, alt text, stylesheets after drop-in.css, the theme tokens and drop-in overrides (no dead `::part` rules), title, `lang`, viewport, description, and whether the folder changed since publish. Prints `{ status, summary, checks: [{ id, kind, status: pass\|warn\|fail, message, fix, items }], render }` and exits 1 when a check fails; warnings do not fail. `kind` is `static` today; a later rendering phase adds `render` checks and fills `render`. |
24
+ | `promotions list` · `show <id>` | The store's promotions, live in Commerce Layer: id, name, status, rules, actions, uses, dates; `managed: false` for ones made in the dashboard. |
25
+ | `promotions create` · `update <id>` | Create a promotion, or replace one, from a spec in YAML or JSON on stdin or `-f <file>` (see [Promotions](#promotions)). Prints the promotion and the `orders test` call that checks it. |
26
+ | `promotions enable <id>` · `disable <id>` · `delete <id>` | Turn a promotion on or off, or delete it (ask the human first). |
24
27
  | `orders test [--sku <id>] [--quantity <n>] [--country <CC>] [--code <discount>] [--via-cart] [--decline]` | Buy from the store over UCP as a shopping agent would: discover, search, (cart,) checkout, address, pay with the sandbox handler, read the order back. Prints the order, the `discounts` applied (promotions and codes, in minor units like the totals) and every step. |
25
28
  | `orders list` | The orders placed in the store, newest first, as UCP order entities. |
26
29
  | `orders show <id or number>` | One order. |
@@ -58,16 +61,6 @@ theme:
58
61
  logo: img/logo.svg # or an https:// URL; default: the name as a wordmark
59
62
  hero: img/hero.jpg # the home page's wide image; default: a band in the accent
60
63
  tagline: Small-batch coffee, roasted in Milan # at most 120 characters; default: "Ships to <countries>"
61
- promotions:
62
- # Discounts: rules (when, all must match) and actions (what). The id is stable.
63
- - id: welcome10
64
- name: Welcome, 10% off
65
- rules: [{ coupon: WELCOME10 }]
66
- actions: [{ percentage: 10 }]
67
- - id: free-shipping-50
68
- market: eu
69
- rules: [{ order_amount: { min: 50 } }]
70
- actions: [free_shipping]
71
64
  policies:
72
65
  # Pages shopping agents show buyers before they pay. Without them the store
73
66
  # serves default sandbox pages at <preview_url>/policies/<name>.
@@ -76,13 +69,22 @@ policies:
76
69
  returns: https://example.com/returns
77
70
  ```
78
71
  ### Promotions
79
- Each entry under `promotions:` has an `id` (lowercase letters, digits and dashes; the store identifies the promotion by it) and optionally `name`, `market` (a market code; without it, every market), `starts` and `ends` (a day, or a UTC time; a bare `ends` day runs to 23:59:59Z; without them the promotion is always on), `limit` (total uses), `priority` (lowest first), `exclusive` and `enabled`.
72
+ Promotions are live settings in Commerce Layer, not store files: the `promotions` commands create and change them directly, and nothing about them is committed. A spec, in YAML or JSON on stdin or with `-f <file>`:
80
73
 
81
- - Rules, one of each kind at most, all matching: `coupon: CODE` or a list (8 to 40 letters, digits, `-`, `_`), `order_amount: { min }` (the items total), `skus: [...]` or `category: A > B` (resolved to its products' skus by the CLI).
74
+ ```yaml
75
+ id: welcome10 # the handle: lowercase letters, digits, dashes; unique
76
+ name: Welcome, 10% off
77
+ rules: [{ coupon: WELCOME10 }]
78
+ actions: [{ percentage: 10 }]
79
+ ```
80
+
81
+ Optional: `market` (a market code; without it, every market), `starts` and `ends` (a day, or a UTC time; a bare `ends` day runs to 23:59:59Z; without them the promotion is always on), `limit` (total uses), `priority` (lowest first), `exclusive`, `enabled`.
82
+
83
+ - Rules, one of each kind at most, all matching: `coupon: CODE` or a list (8 to 40 letters, digits, `-`, `_`), `order_amount: { min }` (the items total), `skus: [...]` or `category: A > B`. A category becomes the skus of its products in store.yml when the command runs: after adding products to it, run `update` again.
82
84
  - Actions: `percentage: 10` (with `skus` or `category` to limit it), `fixed_amount: 5`, `free_shipping`, `fixed_price: { price, skus|category }`, `free_gift: { skus|category, quantity }`, `buy_x_pay_y: { x, y, cheapest_free?, skus|category }`. Actions without their own skus take the rule's. Amounts are in major units, like prices; in a store with several currencies, a promotion with an amount names its `market`. Commerce Layer gets one promotion per action.
83
- - `flex: { rules: [...] }` holds a Commerce Layer Rules Engine promotion as written (amounts in cents), in place of `rules` and `actions`. It needs the Rules Engine: sandboxes do not have it, and `apply` stops with `flex_unavailable`, applying nothing.
85
+ - `flex: { rules: [...] }` holds a Commerce Layer Rules Engine promotion as written (amounts in cents), in place of `rules` and `actions`. Sandboxes have no Rules Engine: `create` answers `flex_unavailable` and creates nothing.
84
86
 
85
- `plan` lists them as `promotion` changes, and warns when more than 10 promotion actions without a coupon are active (Commerce Layer applies 10). Removing one needs `--allow-delete`. `orders test --code <CODE>` proves one: its `discounts` lists what was taken off, and a code that applied nothing is a `discount_code_invalid` warning in `messages`.
87
+ `list` and `show` print each promotion in the normalized form plus `status` (`active`, `scheduled`, `expired`, `disabled`, `used_up`) and `uses`; that output can be edited and sent back to `update`. Promotions made outside c11r (the dashboard, the sandbox's `SANDBOX10`) are listed with `managed: false` and Commerce Layer's id: `enable`, `disable` and `delete` work on them, `update` answers `promotion_not_managed`. `percentage` is a whole number from 1 to 100; a promotion takes at most 20 codes, a free gift at most 25 SKUs. More than 10 active promotion actions without a coupon gives a `warnings` entry (Commerce Layer applies 10). `orders test --code <CODE>` proves one: its `discounts` lists what was taken off, automatic promotions with `automatic: true`, and a code that applied nothing is a `discount_code_invalid` warning in `messages`.
86
88
 
87
89
  ### The products folder
88
90
  Beyond a handful of products, put the catalog in `.commercelayer/products/` and leave `products` out of `store.yml`. Every file in the folder is merged into the catalog by sku, in file-name order:
@@ -115,7 +117,7 @@ One rule for images: `img/<file>` anywhere in `store.yml` (product `image_url`,
115
117
 
116
118
  A custom storefront replaces the theme: `storefront.path` in `store.yml` names its folder, `storefront init` writes a drop-in.js scaffold, `storefront publish` uploads it, `storefront check` checks it. Its pages link product images at `/img/`; its own files (fonts, icons, styles) go in `assets/`, not `img/`.
117
119
 
118
- Error codes: `invalid_theme`, `invalid_promotion`, `flex_unavailable`, `promotions_unsupported`, `missing_images`, `asset_too_large`, `no_store`, `invalid_yaml`, `invalid_store`, `invalid_market`, `invalid_product`, `missing_price`, `deletes_need_approval`, `apply_failed`, `apply_pending`, `apply_in_progress`, `storefront_exists`, `no_storefront`, `storefront_unreachable`, `not_applied`, `not_found`, `missing_argument`, `invalid_argument`, `unknown_command`, `unauthorized`, `expired`, `api_unreachable`, `api_error`, `no_product`, `checkout_not_ready`, `ucp_error`, `ucp_profile_unreachable`, `ucp_profile_malformed`, `ucp_version_unsupported`, `ucp_no_rest_service`, `internal`.
120
+ Error codes: `invalid_theme`, `invalid_promotion`, `promotion_exists`, `promotion_not_managed`, `flex_unavailable`, `promotions_unsupported`, `missing_images`, `asset_too_large`, `no_store`, `invalid_yaml`, `invalid_store`, `invalid_market`, `invalid_product`, `missing_price`, `deletes_need_approval`, `apply_failed`, `apply_pending`, `apply_in_progress`, `storefront_exists`, `no_storefront`, `storefront_unreachable`, `not_applied`, `not_found`, `missing_argument`, `invalid_argument`, `unknown_command`, `unauthorized`, `expired`, `api_unreachable`, `api_error`, `no_product`, `checkout_not_ready`, `ucp_error`, `ucp_profile_unreachable`, `ucp_profile_malformed`, `ucp_version_unsupported`, `ucp_no_rest_service`, `internal`.
119
121
  ## The store speaks UCP
120
122
  Each store is a UCP business at `https://<org>.sandbox.commercelayer.store` (live stores: `<slug>.commercelayer.store`), implementing release **2026-08-25** over REST:
121
123
  | What | Where |
@@ -1,5 +1,5 @@
1
1
  // The client for the management API at api.commercelayer.ai.
2
- import { fail } from '../output.js';
2
+ import { CliError, fail } from '../output.js';
3
3
  import { apiUrl, DEFAULT_API_URL, send } from './transport.js';
4
4
  export function createApi(auth) {
5
5
  const base = apiUrl() === 'stub' ? DEFAULT_API_URL : apiUrl().replace(/\/$/, '');
@@ -27,7 +27,38 @@ export function createApi(auth) {
27
27
  fail(err.code, err.message, err.hint);
28
28
  fail('api_error', `The API answered ${res.status}.`, 'Try again. If it keeps happening, tell the human, with the output of `c11r status`.');
29
29
  };
30
+ // Promotions: on an API older than them, the collection route is an unknown route (404 not_found).
31
+ const promotions = () => `${org()}/promotions`;
32
+ const one = (id) => `${promotions()}/${encodeURIComponent(id)}`;
33
+ const unsupported = async (call) => {
34
+ try {
35
+ return await call;
36
+ }
37
+ catch (e) {
38
+ if (e instanceof CliError && (e.code === 'not_found' || (e.code === 'api_error' && /\b404\b/.test(e.message))))
39
+ fail('promotions_unsupported', 'This API does not manage promotions yet.', 'Try again later; tell the human if it persists.');
40
+ throw e;
41
+ }
42
+ };
43
+ const found = async (id, call) => {
44
+ try {
45
+ return await call;
46
+ }
47
+ catch (e) {
48
+ if (e instanceof CliError && e.code === 'not_found')
49
+ fail('not_found', `There is no promotion ${id}.`, 'Run `c11r promotions list` for the ids, or `c11r promotions create` to make it.');
50
+ throw e;
51
+ }
52
+ };
30
53
  return {
54
+ listPromotions: () => unsupported(request('GET', promotions())),
55
+ createPromotion: (spec) => unsupported(request('POST', promotions(), spec)),
56
+ getPromotion: (id) => found(id, request('GET', one(id))),
57
+ updatePromotion: (id, spec) => found(id, request('PUT', one(id), spec)),
58
+ setPromotionEnabled: (id, enabled) => found(id, request('POST', `${one(id)}/${enabled ? 'enable' : 'disable'}`)),
59
+ deletePromotion: async (id) => {
60
+ await found(id, request('DELETE', one(id)));
61
+ },
31
62
  createSandbox: (name) => request('POST', '/sandboxes', { name }),
32
63
  getStore: () => request('GET', org()),
33
64
  applyStore: (body) => request('PUT', `${org()}/resources`, body),
@@ -7,11 +7,10 @@ import { publicOrders, readDb, SANDBOX_DOMAIN, writeDb } from './db.js';
7
7
  import { bearer, error, json, readJson } from './http.js';
8
8
  function publicState(r) {
9
9
  const { token: _token, ucp: _ucp, pending: _pending, asset_files: _files, ...state } = r;
10
- return { ...state, name: r.name ?? null, policies: r.policies ?? null, theme: r.theme ?? null, assets: r.assets ?? {}, promotions: r.promotions ?? {}, apply: r.apply ?? null, orders: publicOrders(r) };
10
+ return { ...state, name: r.name ?? null, policies: r.policies ?? null, theme: r.theme ?? null, assets: r.assets ?? {}, apply: r.apply ?? null, orders: publicOrders(r) };
11
11
  }
12
- /** Like Commerce Layer refusing a sku or a promotion in an import. Only the stub does this, so tests can exercise apply_failed. */
12
+ /** Like Commerce Layer refusing a sku in an import. Only the stub does this, so tests can exercise apply_failed. */
13
13
  const REFUSED = /^REFUSED-/;
14
- const REFUSED_PROMOTION = /^refused-/;
15
14
  /** C11R_STUB_BUSY_READS=n: the first n reads of a running import answer 503 commercelayer_busy, as when Commerce Layer rate-limits. Per process. */
16
15
  let busyReads = Number(process.env.C11R_STUB_BUSY_READS) || 0;
17
16
  /** Items an import gets through per read: small, so the CLI polls a few times. */
@@ -29,23 +28,37 @@ function advance(r) {
29
28
  return;
30
29
  job.step = 'done';
31
30
  job.finished_at = new Date().toISOString();
32
- const refusedPromotions = r.pending.refused_promotions ?? [];
33
- if (r.pending.refused.length || refusedPromotions.length) {
31
+ if (r.pending.refused.length) {
34
32
  job.status = 'failed';
35
- job.errors = [
36
- ...r.pending.refused.map((sku) => ({ sku, message: 'code is invalid' })),
37
- ...refusedPromotions.map((id) => ({ sku: null, promotion: id, message: 'is invalid' })),
38
- ].slice(0, 50);
33
+ job.errors = r.pending.refused.slice(0, 50).map((sku) => ({ sku, message: 'code is invalid' }));
39
34
  }
40
35
  else {
41
36
  job.status = 'completed';
42
37
  r.applied = r.pending.applied;
43
- if (r.pending.promotions)
44
- r.promotions = r.pending.promotions;
45
38
  r.applied_hash = job.hash;
46
39
  }
47
40
  delete r.pending;
48
41
  }
42
+ function withDefaults(spec) {
43
+ return { ...spec, starts: spec.starts ?? '2000-01-01T00:00:00Z', ends: spec.ends ?? '2100-01-01T00:00:00Z', exclusive: spec.exclusive ?? false, enabled: spec.enabled ?? true };
44
+ }
45
+ /** As the API lists it: the spec plus status and uses. */
46
+ function listed(p) {
47
+ const now = Date.now();
48
+ const status = !p.enabled ? 'disabled' : p.limit !== undefined && p.uses >= p.limit ? 'used_up' : Date.parse(p.ends) <= now ? 'expired' : Date.parse(p.starts) > now ? 'scheduled' : 'active';
49
+ return { ...p, status, managed: true };
50
+ }
51
+ /** The API checks skus against the last applied catalog. */
52
+ function unknownSkus(r, spec) {
53
+ const known = r.applied?.products ?? {};
54
+ const where = [['rules.skus', spec.rules?.skus], ...(spec.actions ?? []).map((a, i) => [`actions[${i}].skus`, 'skus' in a ? a.skus : undefined])];
55
+ for (const [path, list] of where) {
56
+ const i = (list ?? []).findIndex((sku) => !(sku in known));
57
+ if (i >= 0)
58
+ return error(422, 'invalid_promotion', `${path}[${i}]: ${list[i]} is not a product of the store.`, 'Use skus of applied products: run `c11r apply` first if you just added them.');
59
+ }
60
+ return undefined;
61
+ }
49
62
  export function handleManagement(req) {
50
63
  const db = readDb();
51
64
  const path = req.url.pathname;
@@ -105,21 +118,11 @@ export function handleManagement(req) {
105
118
  writeDb(db);
106
119
  if (record.apply?.status === 'in_progress')
107
120
  return error(409, 'apply_in_progress', 'Another apply is still running.', 'Run `c11r status` to follow it, then apply again.');
108
- const { applied, hash, name, policies, theme, promotions, assets, allow_delete, full } = readJson(req);
121
+ const { applied, hash, name, policies, theme, assets, allow_delete, full } = readJson(req);
109
122
  const before = record.applied?.products ?? {};
110
123
  const removed = Object.keys(before).filter((sku) => !(sku in applied.products));
111
- // No promotions field (older CLIs): the promotions stay as they are.
112
- const promosBefore = record.promotions ?? {};
113
- const promos = promotions ? Object.fromEntries(promotions.map((p) => [p.id, p])) : promosBefore;
114
- const promosRemoved = Object.keys(promosBefore).filter((id) => !(id in promos));
115
- const promosChanged = Object.keys(promos).filter((id) => !(id in promosBefore) || canonical(promosBefore[id]) !== canonical(promos[id]));
116
- const doomed = [...removed.map((sku) => `product ${sku}`), ...promosRemoved.map((id) => `promotion ${id}`)];
117
- if (doomed.length && !allow_delete)
118
- return error(409, 'deletes_need_approval', `Apply would delete ${doomed.join(', ')}.`, 'Ask the human whether to delete these. If they agree, run `c11r apply --allow-delete`.');
119
- // Sandboxes have no Rules Engine: a new or changed flex promotion is refused before anything applies.
120
- const flexAt = (promotions ?? []).findIndex((p) => p.flex && promosChanged.includes(p.id));
121
- if (flexAt >= 0)
122
- return error(422, 'flex_unavailable', `promotions[${flexAt}] (${promotions[flexAt].id}): flex promotions need the Rules Engine, which this organization does not have.`, 'Tell the human flex promotions need a Commerce Layer plan with the Rules Engine; build the promotion from the standard rules and actions if you can, or remove it, then apply again.');
124
+ if (removed.length && !allow_delete)
125
+ return error(409, 'deletes_need_approval', `Apply would delete product ${removed.join(', ')}.`, 'Ask the human whether to delete these. If they agree, run `c11r apply --allow-delete`.');
123
126
  // The name, policies and markets apply in the request; products go through an
124
127
  // import job (SKUs, prices, then cleanups for removals) when any changed.
125
128
  record.name = name;
@@ -136,10 +139,8 @@ export function handleManagement(req) {
136
139
  }
137
140
  }
138
141
  const changed = Object.keys(applied.products).filter((sku) => full || !(sku in before) || canonical(before[sku]) !== canonical(applied.products[sku]));
139
- const refusedPromotions = promosChanged.filter((id) => REFUSED_PROMOTION.test(id));
140
- if (changed.length === 0 && removed.length === 0 && refusedPromotions.length === 0) {
142
+ if (changed.length === 0 && removed.length === 0) {
141
143
  record.applied = applied;
142
- record.promotions = promos;
143
144
  record.applied_hash = hash;
144
145
  writeDb(db);
145
146
  return json(200, publicState(record));
@@ -150,15 +151,66 @@ export function handleManagement(req) {
150
151
  step: 'skus',
151
152
  hash,
152
153
  processed: 0,
153
- total: changed.length + removed.length + promosChanged.length + promosRemoved.length,
154
+ total: changed.length + removed.length,
154
155
  started_at: new Date().toISOString(),
155
156
  finished_at: null,
156
157
  errors: [],
157
158
  };
158
- record.pending = { applied, refused: changed.filter((sku) => REFUSED.test(sku)), promotions: promos, refused_promotions: refusedPromotions };
159
+ record.pending = { applied, refused: changed.filter((sku) => REFUSED.test(sku)) };
159
160
  writeDb(db);
160
161
  return json(202, publicState(record));
161
162
  }
163
+ // Promotions: live, synchronous, keyed by id. Sandboxes have no Rules Engine.
164
+ if (rest === '/promotions' || rest.startsWith('/promotions/')) {
165
+ const store = (record.promotions ??= {});
166
+ const [, , rawId, verb] = rest.split('/');
167
+ const id = rawId === undefined ? undefined : decodeURIComponent(rawId);
168
+ const save = () => writeDb(db);
169
+ const flexRefused = (spec) => (spec.flex ? error(422, 'flex_unavailable', 'Flex promotions need the Rules Engine, which this organization does not have.', 'Tell the human flex promotions need a Commerce Layer plan with the Rules Engine; build the promotion from the standard rules and actions if you can.') : undefined);
170
+ if (id === undefined) {
171
+ if (req.method === 'GET')
172
+ return json(200, { promotions: Object.keys(store).sort().map((k) => listed(store[k])) });
173
+ if (req.method === 'POST') {
174
+ const spec = readJson(req);
175
+ if (store[spec.id])
176
+ return error(409, 'promotion_exists', `There is already a promotion ${spec.id}.`, 'Use `c11r promotions update <id>` to change it, or pick another id.');
177
+ const refused = flexRefused(spec) ?? unknownSkus(record, spec);
178
+ if (refused)
179
+ return refused;
180
+ store[spec.id] = { ...withDefaults(spec), uses: 0 };
181
+ save();
182
+ return json(201, listed(store[spec.id]));
183
+ }
184
+ }
185
+ else {
186
+ const p = store[id];
187
+ if (!p)
188
+ return error(404, 'not_found', `There is no promotion ${id}.`, 'Run `c11r promotions list`.');
189
+ if (verb === undefined && req.method === 'GET')
190
+ return json(200, listed(p));
191
+ if (verb === undefined && req.method === 'PUT') {
192
+ const spec = readJson(req);
193
+ if (spec.id !== id)
194
+ return error(422, 'invalid_promotion', `id: the body has ${spec.id}, the path ${id}.`, 'An id never changes.');
195
+ const refused = flexRefused(spec) ?? unknownSkus(record, spec);
196
+ if (refused)
197
+ return refused;
198
+ store[id] = { ...withDefaults(spec), uses: p.uses };
199
+ save();
200
+ return json(200, listed(store[id]));
201
+ }
202
+ if (verb === undefined && req.method === 'DELETE') {
203
+ delete store[id];
204
+ save();
205
+ return { status: 204, headers: {}, body: '' };
206
+ }
207
+ if ((verb === 'enable' || verb === 'disable') && req.method === 'POST') {
208
+ p.enabled = verb === 'enable';
209
+ save();
210
+ return json(200, listed(p));
211
+ }
212
+ }
213
+ }
162
214
  if (req.method === 'PUT' && rest === '/assets') {
163
215
  const { files } = readJson(req);
164
216
  let total = 0;
package/dist/bin.js CHANGED
@@ -4,13 +4,17 @@
4
4
  // Output is always JSON; exit code 1 on an error or a failed check.
5
5
  import * as cmd from './commands.js';
6
6
  import { CliError, print } from './output.js';
7
- const VALUE_OPTIONS = new Set(['--name', '--sku', '--quantity', '--country', '--code']);
7
+ const VALUE_OPTIONS = new Set(['--name', '--sku', '--quantity', '--country', '--code', '--file']);
8
8
  const argv = process.argv.slice(2);
9
9
  const flags = new Set();
10
10
  const values = {};
11
11
  const args = [];
12
12
  for (let i = 0; i < argv.length; i++) {
13
13
  const a = argv[i];
14
+ if (a === '-f' && i + 1 < argv.length) {
15
+ values.file = argv[++i];
16
+ continue;
17
+ }
14
18
  if (!a.startsWith('--')) {
15
19
  args.push(a);
16
20
  continue;
@@ -53,6 +57,20 @@ async function run() {
53
57
  if (sub === 'check')
54
58
  return cmd.storefrontCheckCmd();
55
59
  throw new CliError('unknown_command', `There is no command "storefront ${sub ?? ''}".`, 'Use `c11r storefront init`, `storefront publish` or `storefront check`.');
60
+ case 'promotions':
61
+ if (sub === 'list')
62
+ return cmd.promotionsList();
63
+ if (sub === 'show')
64
+ return cmd.promotionsShow(args[2]);
65
+ if (sub === 'create')
66
+ return cmd.promotionsCreate(values);
67
+ if (sub === 'update')
68
+ return cmd.promotionsUpdate(args[2], values);
69
+ if (sub === 'enable' || sub === 'disable')
70
+ return cmd.promotionsEnable(args[2], sub === 'enable');
71
+ if (sub === 'delete')
72
+ return cmd.promotionsDelete(args[2]);
73
+ throw new CliError('unknown_command', `There is no command "promotions ${sub ?? ''}".`, 'Use `c11r promotions list`, `show <id>`, `create`, `update <id>`, `enable <id>`, `disable <id>` or `delete <id>`.');
56
74
  case 'orders':
57
75
  if (sub === 'test')
58
76
  return cmd.ordersTest(flags, values);
package/dist/commands.js CHANGED
@@ -4,13 +4,14 @@ import fs from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import path from 'node:path';
6
6
  import { createApi } from './api/client.js';
7
- import { ignoreCredentials, paths, readCredentials, requireCredentials, writeCredentials } from './files.js';
7
+ import { ignoreCredentials, paths, readCredentials, requireCredentials, writeAgentNotes, writeCredentials } from './files.js';
8
8
  import { CliError, fail, progress } from './output.js';
9
9
  import { diff, hashStore, loadStore, storefrontPath, template, toApplied } from './store.js';
10
10
  import { storefrontFiles } from './storefront.js';
11
11
  import { imageNotes, planAssets, uploadAssets } from './assets.js';
12
12
  import { pull } from './catalog.js';
13
- import { ACTIVE_LIMIT, activeWithoutCoupon } from './promotions.js';
13
+ import { ACTIVE_LIMIT, activeWithoutCoupon, checkPromotion } from './promotions.js';
14
+ import YAML from 'yaml';
14
15
  import { storefrontCheck } from './check.js';
15
16
  import { buy } from './ucp/buy.js';
16
17
  import { check } from './ucp/check.js';
@@ -19,13 +20,20 @@ import { agentProfile, AGENT_PROFILE_URL } from './ucp/platform.js';
19
20
  /** The package version, read from package.json so a release bumps it in one place. */
20
21
  export const VERSION = createRequire(import.meta.url)('../package.json').version;
21
22
  export const HELP = {
22
- init: 'Create a sandbox store for this repo, with no login: c11r init --name "<business name>" (the folder name when --name is absent). The name becomes the organization\'s name, and the org slug and store hostname derive from it. Writes .commercelayer/store.yml and .commercelayer/credentials. Reuses the store if store.yml already exists.',
23
- plan: 'Show what apply would create, update or delete: markets, products, promotions, images, and the store\'s name, policies and theme; warnings flags more than 10 active promotions without a coupon (Commerce Layer applies 10); missing_images lists references with no file in .commercelayer/img/ (apply refuses them), unused_images files nothing references, from .commercelayer/store.yml and the product files under .commercelayer/products/ (*.yml lists, *.csv rows, merged by sku).',
24
- apply: 'Make the store match .commercelayer/store.yml and .commercelayer/products/: markets, products, promotions, the theme (its settings, and the images in .commercelayer/img/ that the theme and products reference, uploaded when new or changed), name and policies. The store\'s website is live at preview_url after apply. Refuses deletes (products, promotions) unless --allow-delete is given. Flex promotions need the Rules Engine: on an organization without it apply stops with flex_unavailable and applies nothing. Product changes go through a Commerce Layer import: apply waits for it (progress as JSON lines on stderr) and prints one result; if it stops with apply_pending the import keeps going, so run `c11r status` to follow it. While Commerce Layer is busy or unavailable it keeps reading, with a retrying line. An apply still running is finished first. --full re-imports every product and price, after edits in the Commerce Layer dashboard.',
23
+ init: 'Create a sandbox store for this repo, with no login: c11r init --name "<business name>" (the folder name when --name is absent). The name becomes the organization\'s name, and the org slug and store hostname derive from it. Writes .commercelayer/store.yml and .commercelayer/credentials, and a section in AGENTS.md and CLAUDE.md (created, or appended once) that points later agents in this repo to the skills: commit them. Reuses the store if store.yml already exists.',
24
+ plan: 'Show what apply would create, update or delete: markets, products, images, and the store\'s name, policies and theme; missing_images lists references with no file in .commercelayer/img/ (apply refuses them), unused_images files nothing references, from .commercelayer/store.yml and the product files under .commercelayer/products/ (*.yml lists, *.csv rows, merged by sku).',
25
+ apply: 'Make the store match .commercelayer/store.yml and .commercelayer/products/: markets, products, the theme (its settings, and the images in .commercelayer/img/ that the theme and products reference, uploaded when new or changed), name and policies. The store\'s website is live at preview_url after apply. Refuses deletes unless --allow-delete is given. Product changes go through a Commerce Layer import: apply waits for it (progress as JSON lines on stderr) and prints one result; if it stops with apply_pending the import keeps going, so run `c11r status` to follow it. While Commerce Layer is busy or unavailable it keeps reading, with a retrying line. An apply still running is finished first. --full re-imports every product and price, after edits in the Commerce Layer dashboard.',
25
26
  'catalog pull': 'Read the products from the catalog source in store.yml (catalog: { source: supabase | sheets | merchant, url, table }) and write them to .commercelayer/products/catalog.csv; then plan and apply as usual. Columns: sku, name, description, image_url, category and one price column per market currency, in lowercase (eur, usd). Supabase reads C11R_SUPABASE_URL and C11R_SUPABASE_KEY (the anon key) from .commercelayer/credentials or the environment; a Google Sheet needs its CSV link or a link anyone can open; a Merchant Center feed is RSS/XML or TSV.',
26
27
  'storefront init': 'Custom storefronts only: the hosted theme needs none of this (set theme: in store.yml and apply). Write a static storefront on drop-in.js, no build step: storefront/index.html (the products by category, a minicart that opens on add to cart, the hosted cart and checkout, and a product page at #/p/<sku>), styles.css (theme tokens first) and app.js. Product images are the store\'s, at /img/ (.commercelayer/img/, uploaded by apply); the site\'s own files go in storefront/assets/. Refuses to overwrite unless --force is given.',
27
28
  'storefront check': 'Custom storefronts only. Check the published storefront at the preview URL: drop-in.js and its config block wired to this store, the drop-in elements, an add to cart for every product, every image loading, alt text, stylesheets after drop-in.css, the theme tokens and drop-in overrides, title, lang, viewport, description, and whether the folder changed since publish. Prints { status, summary, checks: [{ id, kind, status: pass|warn|fail, message, fix, items }] }; exits 1 when a check fails.',
28
29
  'storefront publish': 'Custom storefronts only: upload the storefront folder (store.yml storefront.path, default storefront) to the preview URL, where it replaces the hosted theme.',
30
+ 'promotions list': 'The store\'s promotions, live in Commerce Layer (not in store files): id, name, status (active, scheduled, expired, disabled, used_up), rules, actions, uses, starts, ends; managed: false marks one made in the dashboard (its id is Commerce Layer\'s), which can be enabled, disabled or deleted but not updated. warnings flags more than 10 active promotion actions without a coupon (Commerce Layer applies 10).',
31
+ 'promotions show': 'One promotion by id, as list shows it: c11r promotions show <id>.',
32
+ 'promotions create': "Create a promotion from a spec in YAML or JSON, on stdin (c11r promotions create <<'EOF' ... EOF) or with -f <file>: { id, name, market, starts, ends, limit, priority, exclusive, enabled, rules: [{ coupon | order_amount: { min } | skus | category }], actions: [{ percentage | fixed_amount | free_shipping | fixed_price | free_gift | buy_x_pay_y }] } or flex: { rules } in place of rules and actions. id is the handle, unique. Amounts are in the market currency, in major units. A category becomes the skus of its products in store.yml now: after adding products to it, run update again. Errors: invalid_promotion (the message starts with the path in the spec), promotion_exists, flex_unavailable (no Rules Engine: nothing is created). Check it with orders test --code.",
33
+ 'promotions update': 'Replace a promotion with a whole spec, same as create, on stdin or -f <file>: c11r promotions update <id>. The id stays the same. What show prints can be edited and sent back. A promotion made in the dashboard (managed: false) cannot be updated: promotion_not_managed; enable, disable and delete work on it.',
34
+ 'promotions enable': 'Turn a promotion on: c11r promotions enable <id>.',
35
+ 'promotions disable': 'Turn a promotion off without deleting it: c11r promotions disable <id>.',
36
+ 'promotions delete': 'Delete a promotion from Commerce Layer: c11r promotions delete <id>. Ask the human first; to pause one, disable it.',
29
37
  'orders test': 'Buy from the store over UCP as a shopping agent would, paying with the sandbox handler: discover, search, checkout, address, pay, read the order. Options: --sku <id> --quantity <n> --country <CC> --code <discount> --via-cart --decline. discounts lists what promotions and codes took off; a code that applied nothing is a discount_code_invalid warning in messages.',
30
38
  'orders list': 'List the orders placed in the store, newest first, as UCP order entities.',
31
39
  'orders show': 'Show one order: c11r orders show <id or number>.',
@@ -54,7 +62,8 @@ export async function init(values) {
54
62
  const existing = readCredentials();
55
63
  if (existing && fs.existsSync(paths.store)) {
56
64
  const s = await createApi(existing).getStore();
57
- return { status: 'reused', org: s.org, claim_url: s.claim_url, expires_at: s.expires_at, preview_url: s.preview_url };
65
+ const notes = writeAgentNotes();
66
+ return { status: 'reused', org: s.org, claim_url: s.claim_url, expires_at: s.expires_at, preview_url: s.preview_url, files: notes.length ? notes : undefined };
58
67
  }
59
68
  // The business name becomes the organization's name; the platform derives the
60
69
  // org slug (and so the store hostname) from it. The folder name is the fallback.
@@ -69,6 +78,7 @@ export async function init(values) {
69
78
  const files = [paths.store, paths.credentials];
70
79
  if (ignoreCredentials())
71
80
  files.push('.gitignore');
81
+ files.push(...writeAgentNotes());
72
82
  return {
73
83
  status: 'created',
74
84
  org: sandbox.org,
@@ -80,16 +90,6 @@ export async function init(values) {
80
90
  next: 'Describe the store in .commercelayer/store.yml (products there or in .commercelayer/products/*.yml|csv, the theme under theme:, images in .commercelayer/img/), then run c11r plan and c11r apply: the website is live at preview_url.',
81
91
  };
82
92
  }
83
- /** Warnings plan and apply give about promotions: the active limit, and an API without them. */
84
- function promotionWarnings(state, desired) {
85
- const out = [];
86
- if (desired.promotions.length && state.promotions === undefined)
87
- out.push('This API does not apply promotions yet: apply will refuse while store.yml has any.');
88
- const active = activeWithoutCoupon(desired.promotions);
89
- if (active.count > ACTIVE_LIMIT)
90
- out.push(`${active.count} promotions without a coupon are active (one per action, in ${active.ids.join(', ')}): Commerce Layer applies at most ${ACTIVE_LIMIT}, the ones with the lowest priority number. Give the rest a coupon, end dates, or enabled: false.`);
91
- return out.length ? out : undefined;
92
- }
93
93
  export async function plan() {
94
94
  const api = createApi(requireCredentials());
95
95
  const desired = loadStore();
@@ -101,7 +101,6 @@ export async function plan() {
101
101
  changes,
102
102
  deletes: changes.filter((c) => c.action === 'delete' && c.type !== 'asset').length,
103
103
  ...imageNotes(assets),
104
- warnings: promotionWarnings(state, desired),
105
104
  next: assets.missing.length ? 'Put the missing images in .commercelayer/img/ (img/<file> in store.yml is .commercelayer/img/<file>), or fix the references: apply refuses until they are there.' : undefined,
106
105
  };
107
106
  }
@@ -160,9 +159,6 @@ export async function apply(flags) {
160
159
  if (assets.missing.length) {
161
160
  fail('missing_images', `The store references images that are not in .commercelayer/img/: ${assets.missing.join('; ')}.`, 'Put the files there (img/<file> in store.yml is .commercelayer/img/<file>), or fix or remove the references, then apply again.');
162
161
  }
163
- if (desired.promotions.length && state.promotions === undefined) {
164
- fail('promotions_unsupported', 'This API does not apply promotions yet.', 'Remove promotions: from store.yml to apply the rest, or update c11r (npx @commercelayer/agent-cli@latest) and try again.');
165
- }
166
162
  // Images first, so the theme and products never point at a file the store host does not have yet.
167
163
  const uploaded = assets.supported ? await uploadAssets(api, assets) : 0;
168
164
  const body = {
@@ -171,7 +167,6 @@ export async function apply(flags) {
171
167
  name: desired.name,
172
168
  policies: desired.policies,
173
169
  theme: desired.theme ?? {},
174
- promotions: desired.promotions,
175
170
  ...(assets.supported && { assets: assets.keep }),
176
171
  ...(flags.has('--allow-delete') && { allow_delete: true }),
177
172
  ...(flags.has('--full') && { full: true }),
@@ -181,10 +176,9 @@ export async function apply(flags) {
181
176
  const done = job ? await follow(api, started) : started;
182
177
  if (job && done.apply?.id === job.id && done.apply.status === 'failed') {
183
178
  const errors = done.apply.errors;
184
- const list = errors.map((e) => (e.sku ? `${e.sku}: ${e.message}` : e.promotion && !e.message.startsWith(`promotion ${e.promotion}:`) ? `promotion ${e.promotion}: ${e.message}` : e.message)).join('; ');
185
- const promos = errors.filter((e) => e.promotion && !e.sku).length;
186
- const what = errors.length === 1 ? (promos ? '1 promotion was refused' : '1 product was refused') : promos === errors.length ? `${errors.length} promotions were refused` : promos ? `${errors.length} items were refused` : `${errors.length} products were refused`;
187
- fail('apply_failed', errors.length ? `${what}: ${list}` : 'The apply failed in Commerce Layer.', `Fix ${promos ? 'them' : 'those products'} in store.yml${promos ? '' : ' or the catalog source'} and run \`c11r apply\` again; the rest of the store is unchanged.`);
179
+ const list = errors.map((e) => (e.sku ? `${e.sku}: ${e.message}` : e.message)).join('; ');
180
+ const what = errors.length === 1 ? '1 product was refused' : `${errors.length} products were refused`;
181
+ fail('apply_failed', errors.length ? `${what}: ${list}` : 'The apply failed in Commerce Layer.', 'Fix those products in store.yml or the catalog source and run `c11r apply` again; the rest of the store is unchanged.');
188
182
  }
189
183
  return {
190
184
  status: 'applied',
@@ -192,8 +186,6 @@ export async function apply(flags) {
192
186
  preview_url: done.preview_url,
193
187
  markets: desired.markets.length,
194
188
  products: desired.products.length,
195
- promotions: desired.promotions.length || undefined,
196
- warnings: promotionWarnings(state, desired),
197
189
  payment_gateway: 'sandbox (test payments only)',
198
190
  images_uploaded: uploaded || undefined,
199
191
  unused_images: assets.unused.length ? assets.unused : undefined,
@@ -355,3 +347,89 @@ export async function claim() {
355
347
  next: 'Ask the human to open verification_url and enter user_code, then run `c11r status`.',
356
348
  };
357
349
  }
350
+ // ---------- promotions: live settings in Commerce Layer, not store files
351
+ /** The fields list, show and the writes print, in a stable order. */
352
+ const READ_ONLY = ['status', 'uses', 'managed'];
353
+ /** The spec from -f <file> or stdin, YAML or JSON, validated against store.yml's markets and products. */
354
+ async function readSpec(values) {
355
+ let text = "";
356
+ if (values.file) {
357
+ if (!fs.existsSync(values.file))
358
+ fail('missing_argument', `There is no file ${values.file}.`, 'Give the promotion as YAML or JSON with -f <file>, or on stdin.');
359
+ text = fs.readFileSync(values.file, 'utf8');
360
+ }
361
+ else if (!process.stdin.isTTY) {
362
+ // A stream read: readFileSync(0) fails with EAGAIN on a pipe whose writer is still running.
363
+ const chunks = [];
364
+ for await (const chunk of process.stdin)
365
+ chunks.push(chunk);
366
+ text = Buffer.concat(chunks).toString('utf8');
367
+ }
368
+ else
369
+ fail('missing_argument', 'No promotion given.', "Give the promotion as YAML or JSON on stdin (c11r promotions create <<'EOF' ... EOF) or with -f <file>.");
370
+ if (!text.trim())
371
+ fail('missing_argument', 'No promotion given: the input is empty.', "Give the promotion as YAML or JSON on stdin (c11r promotions create <<'EOF' ... EOF) or with -f <file>.");
372
+ let raw;
373
+ try {
374
+ raw = YAML.parse(text);
375
+ }
376
+ catch (e) {
377
+ fail('invalid_promotion', `promotion: not valid YAML or JSON: ${e.message.split('\n')[0]}`, 'Fix the syntax and run the command again.');
378
+ }
379
+ // What show prints can be edited and sent back: the read-only fields are dropped.
380
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
381
+ for (const k of READ_ONLY)
382
+ delete raw[k];
383
+ const store = loadStore();
384
+ return checkPromotion(raw, store.markets, store.products);
385
+ }
386
+ /** Warn when more promotion actions without a coupon are live than Commerce Layer applies. */
387
+ async function activeWarning(api) {
388
+ const { promotions } = await api.listPromotions();
389
+ const live = promotions.filter((p) => p.status === 'active' || p.status === 'scheduled');
390
+ const active = activeWithoutCoupon(live);
391
+ return active.count > ACTIVE_LIMIT ? [`${active.count} promotions without a coupon are active or scheduled (one per action, in ${active.ids.join(', ')}): Commerce Layer applies at most ${ACTIVE_LIMIT}, the ones with the lowest priority number. Give the rest a coupon, an end date, or disable them.`] : undefined;
392
+ }
393
+ const checkNext = (p) => p.rules?.coupons?.length ? `Check it: c11r orders test --code ${p.rules.coupons[0]}, and read discounts.` : p.flex ? undefined : 'Check it: c11r orders test with an order that matches the rules (--sku, --quantity), and read discounts.';
394
+ export async function promotionsList() {
395
+ const api = createApi(requireCredentials());
396
+ const { promotions } = await api.listPromotions();
397
+ return { count: promotions.length, promotions, warnings: await activeWarning(api) };
398
+ }
399
+ export async function promotionsShow(id) {
400
+ if (!id)
401
+ fail('missing_argument', 'Which promotion?', 'Use `c11r promotions show <id>`; `c11r promotions list` has the ids.');
402
+ return createApi(requireCredentials()).getPromotion(id);
403
+ }
404
+ export async function promotionsCreate(values) {
405
+ const api = createApi(requireCredentials());
406
+ const spec = await readSpec(values);
407
+ const created = await api.createPromotion(spec);
408
+ return { status: 'created', promotion: created, warnings: await activeWarning(api), next: checkNext(created) };
409
+ }
410
+ export async function promotionsUpdate(id, values) {
411
+ if (!id)
412
+ fail('missing_argument', 'Which promotion?', 'Use `c11r promotions update <id>` with the whole promotion on stdin or -f <file>.');
413
+ const api = createApi(requireCredentials());
414
+ // A promotion made outside c11r has Commerce Layer's id, which is no spec id: say what it is first.
415
+ if ((await api.getPromotion(id)).managed === false)
416
+ fail('promotion_not_managed', `Promotion ${id} was made outside c11r, in the dashboard.`, 'Create a c11r promotion with `c11r promotions create` and delete this one with `c11r promotions delete`, or edit it in the dashboard.');
417
+ const spec = await readSpec(values);
418
+ if (spec.id !== id)
419
+ fail('invalid_promotion', `id: the spec has id ${spec.id}, the command ${id}.`, 'An id never changes: use the same id, or create a new promotion and delete the old one.');
420
+ const updated = await api.updatePromotion(id, spec);
421
+ return { status: 'updated', promotion: updated, warnings: await activeWarning(api), next: checkNext(updated) };
422
+ }
423
+ export async function promotionsEnable(id, enabled) {
424
+ if (!id)
425
+ fail('missing_argument', 'Which promotion?', `Use \`c11r promotions ${enabled ? 'enable' : 'disable'} <id>\`.`);
426
+ const api = createApi(requireCredentials());
427
+ const p = await api.setPromotionEnabled(id, enabled);
428
+ return { status: enabled ? 'enabled' : 'disabled', promotion: p, warnings: enabled ? await activeWarning(api) : undefined };
429
+ }
430
+ export async function promotionsDelete(id) {
431
+ if (!id)
432
+ fail('missing_argument', 'Which promotion?', 'Use `c11r promotions delete <id>`, after asking the human.');
433
+ await createApi(requireCredentials()).deletePromotion(id);
434
+ return { status: 'deleted', id };
435
+ }
package/dist/files.js CHANGED
@@ -61,3 +61,24 @@ export function ignoreCredentials() {
61
61
  fs.appendFileSync('.gitignore', `${sep}${paths.credentials}\n`);
62
62
  return true;
63
63
  }
64
+ /** The note that sends a future agent in this repo to the skills. No skill names: it never goes stale. */
65
+ const AGENT_NOTE_HEADING = '# Store on Commerce Layer';
66
+ export const AGENT_NOTE = `${AGENT_NOTE_HEADING}
67
+ This store is managed with \`c11r\` (\`npx @commercelayer/agent-cli\`), configured in \`.commercelayer/store.yml\`. Before any task about the store (products, prices, markets, storefront, orders, promotions, agents), fetch \`https://commercelayer.ai/skills.md\` with \`curl -fsSL\` and load the skill for the task from \`skills/<name>.md\`; follow it rather than calling the Commerce Layer API directly. If \`.commercelayer/store.yml\` is missing, start from \`https://commercelayer.ai/start.md\`.
68
+ `;
69
+ /**
70
+ * Write the note to AGENTS.md and CLAUDE.md (Claude Code reads that name) in the repo root:
71
+ * created when absent, appended as a section when the file has other content, left alone
72
+ * when the section is already there. Returns the files written.
73
+ */
74
+ export function writeAgentNotes() {
75
+ const written = [];
76
+ for (const file of ['AGENTS.md', 'CLAUDE.md']) {
77
+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
78
+ if (before.split('\n').some((line) => line.trim() === AGENT_NOTE_HEADING))
79
+ continue;
80
+ fs.writeFileSync(file, before.trim() ? `${before.replace(/\s*$/, '')}\n\n${AGENT_NOTE}` : AGENT_NOTE);
81
+ written.push(file);
82
+ }
83
+ return written;
84
+ }
@@ -29,29 +29,55 @@ function isoDate(v, end, bad) {
29
29
  bad(`"${s}" is not a date.`, hint);
30
30
  return new Date(s).toISOString().replace(/\.000Z$/, 'Z');
31
31
  }
32
- /** Validate promotions: and normalize them to the wire shape, or fail invalid_promotion with the path. */
33
- export function checkPromotions(raw, markets, products) {
34
- if (raw === undefined || raw === null)
35
- return [];
36
- if (!Array.isArray(raw))
37
- fail('invalid_promotion', 'promotions in store.yml is not a list.', `Write promotions as a YAML list under \`promotions:\`, one entry per promotion. ${SHAPE_HINT}`);
32
+ /**
33
+ * The normalized shape (what list and show print) back to the YAML shorthand, so a promotion
34
+ * read with show can be edited and sent to update: rules as an object, actions with a type.
35
+ */
36
+ function fromListed(p) {
37
+ const out = { ...p };
38
+ if (isObj(p.rules)) {
39
+ const r = p.rules;
40
+ out.rules = [
41
+ ...(r.coupons !== undefined ? [{ coupon: r.coupons }] : []),
42
+ ...(r.order_amount !== undefined ? [{ order_amount: r.order_amount }] : []),
43
+ ...(r.skus !== undefined ? [{ skus: r.skus }] : []),
44
+ ...Object.keys(r).filter((k) => !['coupons', 'order_amount', 'skus'].includes(k)).map((k) => ({ [k]: r[k] })),
45
+ ];
46
+ }
47
+ if (Array.isArray(p.actions)) {
48
+ out.actions = p.actions.map((a) => {
49
+ if (!isObj(a) || typeof a.type !== 'string')
50
+ return a;
51
+ const { type, ...rest } = a;
52
+ if (type === 'free_shipping')
53
+ return 'free_shipping';
54
+ if (type === 'percentage' || type === 'fixed_amount') {
55
+ const { value, ...targets } = rest;
56
+ return { [type]: value, ...targets };
57
+ }
58
+ return { [type]: rest };
59
+ });
60
+ }
61
+ return out;
62
+ }
63
+ /**
64
+ * Validate one promotion spec (YAML or JSON, as given to promotions create or update) and
65
+ * normalize it to the wire shape, or fail invalid_promotion naming the path inside the spec.
66
+ * Categories become their products' skus as they are now, from store.yml.
67
+ */
68
+ export function checkPromotion(raw, markets, products) {
38
69
  const skus = new Set(products.map((p) => p.sku));
39
70
  const currencies = new Set(markets.map((m) => m.currency));
40
- const ids = new Set();
41
- const out = [];
42
- raw.forEach((p, i) => {
43
- let at = `promotions[${i}]`;
44
- const bad = (msg, hint, path = at) => fail('invalid_promotion', `${path}: ${msg}`, hint);
71
+ const at = 'promotion';
72
+ const bad = (msg, hint, path = at) => fail('invalid_promotion', `${path}: ${msg}`, hint);
73
+ {
74
+ const p = raw;
45
75
  if (!isObj(p))
46
- bad('is not a map.', `Each promotion is a map with id, rules and actions. ${SHAPE_HINT}`);
47
- const pr = p;
76
+ bad('is not a map.', `A promotion is a map with id, rules and actions. ${SHAPE_HINT}`);
77
+ const pr = fromListed(p);
48
78
  if (typeof pr.id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(pr.id))
49
- bad(`id is ${pr.id === undefined ? 'missing' : `"${String(pr.id)}"`}.`, 'Give every promotion an id of lowercase letters, digits and dashes, such as welcome10. The store identifies the promotion by it: keep it stable.');
79
+ bad(`id is ${pr.id === undefined ? 'missing' : `"${String(pr.id)}"`}.`, 'Give the promotion an id of lowercase letters, digits and dashes, such as welcome10: the handle for show, update, enable, disable and delete.');
50
80
  const id = pr.id;
51
- if (ids.has(id))
52
- bad(`two promotions have id ${id}.`, 'Give every promotion a unique id.');
53
- ids.add(id);
54
- at = `promotions[${i}] (${id})`;
55
81
  for (const k of Object.keys(pr))
56
82
  if (!KEYS.includes(k))
57
83
  bad(`unknown key ${k}.`, `A promotion's keys are ${KEYS.join(', ')}.`);
@@ -95,13 +121,12 @@ export function checkPromotions(raw, markets, products) {
95
121
  if (!isObj(f) || !Array.isArray(f.rules) || f.rules.length === 0)
96
122
  bad('flex has no rules.', 'Write flex: { rules: [...] }, each rule with conditions and actions. See docs.commercelayer.io/rules-engine.');
97
123
  f.rules.forEach((r, j) => {
98
- const path = `${at}.flex.rules[${j}]`;
124
+ const path = `flex.rules[${j}]`;
99
125
  if (!isObj(r) || !Array.isArray(r.conditions) || !r.conditions.length || !Array.isArray(r.actions) || !r.actions.length)
100
126
  bad('needs a list of conditions and a list of actions.', 'Each flex rule has conditions (field, matcher, value) and actions (type, selector, value).', path);
101
127
  });
102
128
  promo.flex = f;
103
- out.push(promo);
104
- return;
129
+ return promo;
105
130
  }
106
131
  // Rules: a list of single-key maps; none means every order.
107
132
  const rules = {};
@@ -127,7 +152,7 @@ export function checkPromotions(raw, markets, products) {
127
152
  if (!Array.isArray(rawRules))
128
153
  bad('rules is not a list.', `Write rules as a list: rules: [{ coupon: CODE }]. ${SHAPE_HINT}`);
129
154
  rawRules.forEach((r, j) => {
130
- const path = `${at}.rules[${j}]`;
155
+ const path = `rules[${j}]`;
131
156
  if (!isObj(r) || Object.keys(r).length !== 1)
132
157
  bad('is not a single rule.', `Each rule is one of ${RULES.join(', ')}, written as a one-key map: { coupon: CODE }.`, path);
133
158
  const [k, v] = Object.entries(r)[0];
@@ -145,6 +170,8 @@ export function checkPromotions(raw, markets, products) {
145
170
  }
146
171
  if (!l.length)
147
172
  bad('coupon has no code.', 'Write coupon: CODE, or a list of codes.', path);
173
+ if (new Set(l).size > 20)
174
+ bad(`coupon has ${new Set(l).size} codes.`, 'A promotion takes at most 20 codes: split them across promotions.', path);
148
175
  rules.coupons = [...new Set(l)];
149
176
  }
150
177
  else if (k === 'order_amount') {
@@ -166,7 +193,7 @@ export function checkPromotions(raw, markets, products) {
166
193
  const types = new Set();
167
194
  let needsCurrency = Boolean(rules.order_amount);
168
195
  pr.actions.forEach((a, j) => {
169
- const path = `${at}.actions[${j}]`;
196
+ const path = `actions[${j}]`;
170
197
  const entry = a === 'free_shipping' ? { free_shipping: true } : a;
171
198
  if (!isObj(entry))
172
199
  bad('is not an action.', `Each action is one of ${ACTIONS.join(', ')}: { percentage: 10 }, or free_shipping.`, path);
@@ -196,8 +223,8 @@ export function checkPromotions(raw, markets, products) {
196
223
  };
197
224
  if (k === 'percentage') {
198
225
  only(entry, ['percentage', 'skus', 'category']);
199
- if (!isNum(v) || v <= 0 || v > 100)
200
- bad(`percentage is ${String(v)}.`, 'percentage is a number above 0 and up to 100: 10 is 10% off. To make shipping free, use free_shipping.', path);
226
+ if (!isInt(v, 1) || v > 100)
227
+ bad(`percentage is ${String(v)}.`, 'percentage is a whole number from 1 to 100: 10 is 10% off. To make shipping free, use free_shipping.', path);
201
228
  const t = target(entry, false);
202
229
  actions.push({ type: 'percentage', value: v, ...(t ? { skus: t } : {}) });
203
230
  }
@@ -232,7 +259,10 @@ export function checkPromotions(raw, markets, products) {
232
259
  bad('free_gift needs the SKUs given away.', 'Write free_gift: { skus: [GIFT-SKU], quantity: 1 }.', path);
233
260
  if (o.quantity !== undefined && !isInt(o.quantity, 1))
234
261
  bad(`free_gift.quantity is ${String(o.quantity)}.`, 'quantity is a whole number of 1 or more.', path);
235
- actions.push({ type: 'free_gift', skus: target(o, true), quantity: o.quantity ?? 1 });
262
+ const gifts = target(o, true);
263
+ if (gifts.length > 25)
264
+ bad(`free_gift has ${gifts.length} skus.`, 'A free gift takes at most 25 SKUs: narrow the list or the category.', path);
265
+ actions.push({ type: 'free_gift', skus: gifts, quantity: o.quantity ?? 1 });
236
266
  }
237
267
  else {
238
268
  only(o, ['x', 'y', 'cheapest_free', 'skus', 'category']);
@@ -248,9 +278,8 @@ export function checkPromotions(raw, markets, products) {
248
278
  bad('has an amount but no market, in a store with several currencies.', 'Set market: so the amount has a currency, or use a percentage.');
249
279
  promo.rules = rules;
250
280
  promo.actions = actions;
251
- out.push(promo);
252
- });
253
- return out;
281
+ return promo;
282
+ }
254
283
  }
255
284
  /**
256
285
  * Commerce Layer promotions active without a coupon: each action of an enabled promotion that
package/dist/store.js CHANGED
@@ -8,7 +8,6 @@ import YAML from 'yaml';
8
8
  import { fail } from './output.js';
9
9
  import { paths } from './files.js';
10
10
  import { productFiles, readProductFile } from './products.js';
11
- import { checkPromotions } from './promotions.js';
12
11
  /** The keys a product may have. Stock is not one: inventory lives in Commerce Layer. */
13
12
  export const PRODUCT_KEYS = ['sku', 'name', 'description', 'image_url', 'category', 'prices'];
14
13
  export const THEME_KEYS = ['color', 'logo', 'hero', 'tagline'];
@@ -62,18 +61,6 @@ theme:
62
61
  # hero: img/hero.jpg # the home page's wide image; without it a band in the accent
63
62
  # tagline: Small-batch coffee, roasted in Milan # at most 120 characters
64
63
 
65
- promotions:
66
- # Discount codes and automatic discounts: rules (when) and actions (what).
67
- # The id is unique and stable. Amounts are in the market currency, like prices.
68
- # - id: welcome10
69
- # name: Welcome, 10% off
70
- # rules: [{ coupon: WELCOME10 }] # codes have 8 to 40 characters
71
- # actions: [{ percentage: 10 }]
72
- # - id: free-shipping-50
73
- # market: eu
74
- # rules: [{ order_amount: { min: 50 } }]
75
- # actions: [free_shipping]
76
-
77
64
  storefront:
78
65
  # Only for a custom storefront (your own web app in this repo, published with
79
66
  # c11r storefront publish): it replaces the theme. Its folder, from the repo root.
@@ -149,6 +136,8 @@ export function loadStore() {
149
136
  }
150
137
  }
151
138
  }
139
+ if (doc.promotions !== undefined)
140
+ fail('invalid_store', 'store.yml has promotions:, which is not part of the store files.', 'Promotions are live settings in Commerce Layer: create each one with `c11r promotions create -f <file>` (the same entry as YAML or JSON), then remove promotions: from store.yml.');
152
141
  const policies = (doc.policies ?? {});
153
142
  for (const [key, url] of Object.entries(policies)) {
154
143
  if (url && !/^https?:\/\//.test(String(url)))
@@ -157,8 +146,7 @@ export function loadStore() {
157
146
  const theme = checkTheme(doc.theme);
158
147
  const currencies = [...new Set(markets.map((m) => m.currency))];
159
148
  const products = checkProducts(sourced, currencies);
160
- const promotions = checkPromotions(doc.promotions, markets, products);
161
- return { name: doc.name, markets, products, storefront: doc.storefront, policies, theme, promotions };
149
+ return { name: doc.name, markets, products, storefront: doc.storefront, policies, theme };
162
150
  }
163
151
  /** The product rules, shared by loadStore and catalog pull: errors name each product's source. */
164
152
  export function checkProducts(sourced, currencies) {
@@ -270,19 +258,5 @@ export function diff(state, desired) {
270
258
  if (!(id in after[kind]))
271
259
  changes.push({ action: 'delete', type, id });
272
260
  }
273
- // Promotions, by id. An API that does not know them (undefined) is skipped: apply refuses instead.
274
- if (!applied || state.promotions !== undefined) {
275
- const before = (applied ? state.promotions : undefined) ?? {};
276
- const want = Object.fromEntries((desired.promotions ?? []).map((p) => [p.id, p]));
277
- for (const id of Object.keys(want)) {
278
- if (!(id in before))
279
- changes.push({ action: 'create', type: 'promotion', id });
280
- else if (canonical(before[id]) !== canonical(want[id]))
281
- changes.push({ action: 'update', type: 'promotion', id });
282
- }
283
- for (const id of Object.keys(before))
284
- if (!(id in want))
285
- changes.push({ action: 'delete', type: 'promotion', id });
286
- }
287
261
  return changes;
288
262
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commercelayer/agent-cli",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "c11r: the Commerce Layer CLI for coding agents. Builds a sandbox store that people and shopping agents can buy from.",
5
5
  "homepage": "https://commercelayer.ai",
6
6
  "keywords": [