@clix-so/clix-agent-skills 0.1.8 → 0.1.9

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
@@ -1,7 +1,7 @@
1
1
  # Agent Skills for Clix
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/%40clix-so%2Fclix-agent-skills.svg?logo=npm&label=npm)](https://www.npmjs.com/package/@clix-so/clix-agent-skills)
4
- [![npm downloads](https://img.shields.io/npm/dm/%40clix-so%2Fclix-agent-skills.svg)](https://www.npmjs.com/package/@clix-so/clix-agent-skills)
4
+ [![npm downloads](https://img.shields.io/npm/d18m/%40clix-so%2Fclix-agent-skills.svg)](https://www.npmjs.com/package/@clix-so/clix-agent-skills)
5
5
 
6
6
  This repository contains a collection of **Agent Skills for Clix**. Each skill
7
7
  is a self-contained package that can be loaded and executed by AI clients.
@@ -50,7 +50,7 @@ npx @clix-so/clix-agent-skills@latest install integration --client cursor --glob
50
50
 
51
51
  # Install all available skills at once (repo root)
52
52
  npx @clix-so/clix-agent-skills@latest install --all --client cursor
53
- # This will install: integration, event-tracking, user-management, personalization
53
+ # This will install: integration, event-tracking, user-management, personalization, api-triggered-campaigns
54
54
 
55
55
  # Install all available skills globally (system root)
56
56
  npx @clix-so/clix-agent-skills@latest install --all --client cursor --global
@@ -58,7 +58,8 @@ npx @clix-so/clix-agent-skills@latest install --all --client cursor --global
58
58
 
59
59
  ### Available Skills
60
60
 
61
- - **clix-integration**: Integrate Clix Mobile SDK and MCP server setup
61
+ - **clix-integration**: Seamlessly integrate Clix Mobile SDK to your mobile
62
+ application with Clix MCP Server
62
63
  - **clix-event-tracking**: Implement `Clix.trackEvent` with naming/schema best
63
64
  practices and campaign-ready validation
64
65
  - **clix-user-management**: Implement `Clix.setUserId` + user properties with
@@ -66,6 +67,9 @@ npx @clix-so/clix-agent-skills@latest install --all --client cursor --global
66
67
  - **clix-personalization**: Author and debug personalization templates for
67
68
  message content, deep links/URLs, and audience targeting rules (`user.*`,
68
69
  `event.*`, `trigger.*`, `device.*`)
70
+ - **clix-api-triggered-campaigns**: Configure API-triggered campaigns in the
71
+ console and trigger them from your backend with safe auth, dynamic filters
72
+ (`trigger.*`), and personalization patterns
69
73
 
70
74
  **Supported Clients:**
71
75
 
@@ -105,6 +109,7 @@ Alternatively, you can install a single skill directly by running:
105
109
  /plugin install clix-event-tracking@clix-agent-skills
106
110
  /plugin install clix-user-management@clix-agent-skills
107
111
  /plugin install clix-personalization@clix-agent-skills
112
+ /plugin install clix-api-triggered-campaigns@clix-agent-skills
108
113
  ```
109
114
 
110
115
  Remember to restart Claude Code after installation to load the new skills.
@@ -120,11 +120,13 @@ async function installSkill(skillName, options) {
120
120
  throw error;
121
121
  }
122
122
  // 4. MCP Configuration (always global/system root)
123
- try {
124
- await (0, mcp_1.configureMCP)(options.client);
125
- }
126
- catch (error) {
127
- console.warn(chalk_1.default.yellow(`MCP Configuration warning: ${getErrorMessage(error)}`));
123
+ if (!options.skipMCPConfig) {
124
+ try {
125
+ await (0, mcp_1.configureMCP)(options.client);
126
+ }
127
+ catch (error) {
128
+ console.warn(chalk_1.default.yellow(`MCP Configuration warning: ${getErrorMessage(error)}`));
129
+ }
128
130
  }
129
131
  console.log(`\n${chalk_1.default.green("✔")} Skill ${chalk_1.default.bold(skillName)} is ready to use!`);
130
132
  console.log(` - Docs: ${path_1.default.join(destPath, "SKILL.md")}`);
@@ -170,7 +172,8 @@ async function installAllSkills(options) {
170
172
  let failCount = 0;
171
173
  for (const skillName of skills) {
172
174
  try {
173
- await installSkill(skillName, options);
175
+ // Avoid configuring MCP once per skill. We'll do it once at the end.
176
+ await installSkill(skillName, { ...options, skipMCPConfig: true });
174
177
  successCount++;
175
178
  }
176
179
  catch (error) {
@@ -178,6 +181,15 @@ async function installAllSkills(options) {
178
181
  failCount++;
179
182
  }
180
183
  }
184
+ // Configure MCP once per `--all` run (always global/system root)
185
+ if (successCount > 0) {
186
+ try {
187
+ await (0, mcp_1.configureMCP)(options.client);
188
+ }
189
+ catch (error) {
190
+ console.warn(chalk_1.default.yellow(`MCP Configuration warning: ${getErrorMessage(error)}`));
191
+ }
192
+ }
181
193
  console.log();
182
194
  if (failCount === 0) {
183
195
  console.log(chalk_1.default.green(`\n✔ Successfully installed all ${chalk_1.default.bold(successCount)} skill(s)!`));
@@ -159,7 +159,13 @@ function getClientConfig(client) {
159
159
  format: "json",
160
160
  };
161
161
  }
162
+ // GitHub Copilot runs inside VS Code, so its MCP configuration lives in VS Code's MCP config.
163
+ // We accept `github` / `copilot` as aliases and write to the same file as `vscode`.
162
164
  case "vscode":
165
+ case "github":
166
+ case "copilot":
167
+ case "github-copilot":
168
+ case "github copilot":
163
169
  return {
164
170
  path: path_1.default.join(home, ".vscode", "mcp.json"),
165
171
  configKey: "mcpServers",
package/llms.txt CHANGED
@@ -7,6 +7,32 @@ Each entry includes the file path, type, and description for semantic search.
7
7
 
8
8
  ---
9
9
 
10
+ ## clix-api-triggered-campaigns
11
+
12
+ Helps developers configure API-triggered campaigns in the Clix console and trigger them from backend services with safe auth, payload schemas, dynamic audience filters (trigger.*), and personalization best practices. Use when the user mentions transactional notifications, backend-triggered sends, campaign_id trigger APIs, or "API-triggered campaigns".
13
+
14
+ - [clix-api-triggered-campaigns](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/SKILL.md): Helps developers configure API-triggered campaigns in the Clix console and trigger them from backend services with safe auth, payload schemas, dynamic audience filters (trigger.*), and personalization best practices. Use when the user mentions transactional notifications, backend-triggered sends, campaign_id trigger APIs, or "API-triggered campaigns".
15
+
16
+ ### References
17
+
18
+ - [Api Contract (Reference)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/references/api-contract.md): Reference documentation for api-triggered-campaigns skill
19
+ - [Backend Patterns (Reference)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/references/backend-patterns.md): Reference documentation for api-triggered-campaigns skill
20
+ - [Console Setup (Reference)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/references/console-setup.md): Reference documentation for api-triggered-campaigns skill
21
+ - [Debugging (Reference)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/references/debugging.md): Reference documentation for api-triggered-campaigns skill
22
+ - [Personalization And Dynamic Filters (Reference)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/references/personalization-and-dynamic-filters.md): Reference documentation for api-triggered-campaigns skill
23
+ - [Security And Keys (Reference)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/references/security-and-keys.md): Reference documentation for api-triggered-campaigns skill
24
+
25
+ ### Examples
26
+
27
+ - [Trigger Campaign Node (Example)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/examples/trigger-campaign-node.js): Code example for api-triggered-campaigns skill
28
+ - [Trigger Campaign Python (Example)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/examples/trigger-campaign-python.py): Code example for api-triggered-campaigns skill
29
+
30
+ ### Scripts
31
+
32
+ - [Validate Api Trigger Plan (Script)](https://raw.githubusercontent.com/clix-so/skills/refs/heads/main/skills/api-triggered-campaigns/scripts/validate-api-trigger-plan.sh): Utility script for api-triggered-campaigns skill
33
+
34
+ ---
35
+
10
36
  ## clix-event-tracking
11
37
 
12
38
  Implements Clix event tracking (Clix.trackEvent) with consistent naming, safe property schemas, and campaign-ready validation. Use when adding, reviewing, or debugging event tracking; when configuring event-triggered campaigns; or when the user mentions events, tracking, funnels, or properties — or when the user types `clix-event-tracking`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clix-so/clix-agent-skills",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "An open collection of agent skills for Clix.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -0,0 +1,203 @@
1
+ Copyright (c) 2026 Clix (https://clix.so/)
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright (c) 2026 Clix (https://clix.so/)
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
@@ -0,0 +1,186 @@
1
+ ---
2
+ name: clix-api-triggered-campaigns
3
+ description:
4
+ Helps developers configure API-triggered campaigns in the Clix console and
5
+ trigger them from backend services with safe auth, payload schemas, dynamic
6
+ audience filters (trigger.*), and personalization best practices. Use when the
7
+ user mentions transactional notifications, backend-triggered sends,
8
+ campaign_id trigger APIs, or "API-triggered campaigns".
9
+ ---
10
+
11
+ # API-Triggered Campaigns (Backend → Clix)
12
+
13
+ Use this skill to set up **API-triggered campaigns** in the Clix console and
14
+ trigger them from your backend with dynamic data (`trigger.*`) for:
15
+
16
+ - Transactional notifications (orders, password reset, receipts)
17
+ - Workflow messages (assignments, approvals)
18
+ - System alerts (moderation, support tickets)
19
+ - Programmatic sends where marketers/ops should control content + targeting
20
+
21
+ ## What the official docs guarantee (high-signal)
22
+
23
+ - API-triggered campaigns are configured in the console, then triggered via:
24
+ `POST /api/v1/campaigns/{campaign_id}:trigger`
25
+ - Authentication uses **secret** headers:
26
+ - `X-Clix-Project-ID`
27
+ - `X-Clix-API-Key`
28
+ - Request `properties` become **`trigger.*`** for:
29
+ - **Dynamic audience filtering** (console audience rules)
30
+ - **Personalization** in templates (title/body/deep links)
31
+ - `audience.broadcast=true` sends to all users eligible under the campaign’s
32
+ segment definition; `audience.targets` narrows to specific users/devices
33
+ (still filtered by the segment definition).
34
+ - Dynamic audience filters are intentionally constrained for performance: **max
35
+ 3 attributes** in the audience definition.
36
+
37
+ ## MCP-first (source of truth)
38
+
39
+ If Clix MCP tools are available, treat them as the **source of truth**:
40
+
41
+ - Use `clix-mcp-server:search_docs` to confirm the latest API contract + limits:
42
+ - query examples:
43
+ - `"API-triggered campaign trigger endpoint"`
44
+ - `"campaigns/{campaign_id}:trigger audience targets broadcast"`
45
+ - `"trigger.* dynamic audience filters limitations"`
46
+
47
+ If MCP tools are not available, use the bundled references:
48
+
49
+ - API contract → `references/api-contract.md`
50
+ - Console setup + dynamic filters → `references/console-setup.md`
51
+ - Backend patterns (auth, retries, timeouts) → `references/backend-patterns.md`
52
+ - Security/key handling → `references/security-and-keys.md`
53
+ - Personalization + dynamic filters →
54
+ `references/personalization-and-dynamic-filters.md`
55
+ - Debugging checklist → `references/debugging.md`
56
+
57
+ ## Workflow (copy + check off)
58
+
59
+ ```
60
+ API-triggered campaign progress:
61
+ - [ ] 1) Confirm goals + trigger source (what backend event sends the message?)
62
+ - [ ] 2) Define campaign contract (properties keys/types; PII policy)
63
+ - [ ] 3) Configure campaign in console (API-triggered + audience rules + templates)
64
+ - [ ] 4) Implement backend trigger wrapper (auth, timeout, retries, logging)
65
+ - [ ] 5) Validate trigger plan JSON (schema + naming + safety)
66
+ - [ ] 6) Verify in Clix (test payloads, Message Logs, segment matching)
67
+ ```
68
+
69
+ ## 1) Confirm the minimum inputs
70
+
71
+ Ask only what’s needed:
72
+
73
+ - **Campaign**: where is it in the console? do you already have `campaign_id`?
74
+ - **Channel**: push / in-app / email / etc. (affects message template fields)
75
+ - **Audience mode**: broadcast vs explicit targets
76
+ - **Dynamic filter keys**: which `trigger.*` keys are used in audience rules
77
+ - **Properties**: list of keys + types + example values (avoid PII by default)
78
+ - **Backend**: runtime and HTTP client (Node/Fetch, Axios, Python, Go, etc.)
79
+
80
+ ## 2) Create a “Trigger Plan” (before touching backend code)
81
+
82
+ Create `api-trigger-plan.json` in `.clix/` (recommended) or project root.
83
+
84
+ **Recommended location**: `.clix/api-trigger-plan.json`
85
+
86
+ **Plan schema (high-level):**
87
+
88
+ - `campaign_id` (string)
89
+ - `audience.mode`: `"broadcast" | "targets" | "default"`
90
+ - `audience.targets` (if mode is `"targets"`)
91
+ - `dynamic_filter_keys` (array of up to 3 snake_case keys)
92
+ - `properties` (map of snake_case keys → `{ type, required?, example?, pii? }`)
93
+
94
+ Example:
95
+
96
+ ```json
97
+ {
98
+ "campaign_id": "019aa002-1d0e-7407-a0c5-5bfa8dd2be30",
99
+ "audience": {
100
+ "mode": "broadcast"
101
+ },
102
+ "dynamic_filter_keys": ["store_location"],
103
+ "properties": {
104
+ "store_location": {
105
+ "type": "string",
106
+ "required": true,
107
+ "example": "San Francisco"
108
+ },
109
+ "order_id": { "type": "string", "required": true, "example": "ORD-12345" },
110
+ "item_count": { "type": "number", "required": true, "example": 3 },
111
+ "pickup_time": { "type": "string", "required": false, "example": "2:30 PM" }
112
+ }
113
+ }
114
+ ```
115
+
116
+ ## 3) Configure campaign in the console (API-triggered)
117
+
118
+ - Set the campaign type to **API-Triggered**.
119
+ - Build audience rules using `{{ trigger.* }}` for dynamic filters.
120
+ - Use `{{ trigger.* }}` in message templates + deep links.
121
+
122
+ See: `references/console-setup.md` for exact guidance and limitations.
123
+
124
+ ## 4) Implement backend trigger wrapper (best practices)
125
+
126
+ Backend wrapper responsibilities:
127
+
128
+ - **Auth**: load `X-Clix-Project-ID` and `X-Clix-API-Key` from
129
+ environment/secret store (never commit).
130
+ - **Timeout**: set a short timeout (e.g., 3–10s) and fail fast.
131
+ - **Retries**: retry only on transient failures (network/5xx), with backoff; do
132
+ not retry blindly on 4xx.
133
+ - **Dedupe**: prevent double-sends in your system (e.g., unique key per order
134
+ event) since the API call is “send-like”.
135
+ - **Logging**: log `campaign_id`, your correlation id (order id), and the Clix
136
+ response (e.g., `trigger_id`).
137
+
138
+ Copy/paste examples:
139
+
140
+ - Node: `examples/trigger-campaign-node.js`
141
+ - Python: `examples/trigger-campaign-python.py`
142
+
143
+ ## 5) Validate the plan (fast feedback loop)
144
+
145
+ Run:
146
+
147
+ ```bash
148
+ bash <skill-dir>/scripts/validate-api-trigger-plan.sh .clix/api-trigger-plan.json
149
+ ```
150
+
151
+ This validator checks:
152
+
153
+ - valid JSON
154
+ - `campaign_id` present
155
+ - `dynamic_filter_keys` is ≤ 3 and snake_case
156
+ - `properties` keys are snake_case and have valid types
157
+ - example values match declared types
158
+ - `targets` entries specify exactly one of `project_user_id` or `device_id`
159
+
160
+ ## 6) Verify (Clix + end-to-end)
161
+
162
+ Minimum verification:
163
+
164
+ - Campaign is **API-Triggered** and `campaign_id` matches.
165
+ - If using dynamic audience filters, the `trigger.*` keys exist in the API call
166
+ and match audience rules exactly.
167
+ - Trigger once with a known-good payload; confirm delivery + inspect Message
168
+ Logs for rendering errors.
169
+
170
+ See `references/debugging.md`.
171
+
172
+ ## Progressive Disclosure
173
+
174
+ - **Level 1**: This `SKILL.md` (always loaded)
175
+ - **Level 2**: `references/` (load when implementing details)
176
+ - **Level 3**: `examples/` (load when copy/pasting backend code)
177
+ - **Level 4**: `scripts/` (execute directly; do not load into context)
178
+
179
+ ## References
180
+
181
+ - `references/api-contract.md`
182
+ - `references/console-setup.md`
183
+ - `references/backend-patterns.md`
184
+ - `references/security-and-keys.md`
185
+ - `references/personalization-and-dynamic-filters.md`
186
+ - `references/debugging.md`
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Minimal Node.js example: trigger an API-triggered campaign.
3
+ *
4
+ * Requirements:
5
+ * - Node 18+ (fetch is available) OR replace with your HTTP client
6
+ * - Env vars:
7
+ * - CLIX_PROJECT_ID
8
+ * - CLIX_API_KEY
9
+ */
10
+
11
+ const CLIX_PROJECT_ID = process.env.CLIX_PROJECT_ID;
12
+ const CLIX_API_KEY = process.env.CLIX_API_KEY;
13
+
14
+ if (!CLIX_PROJECT_ID || !CLIX_API_KEY) {
15
+ throw new Error("Missing CLIX_PROJECT_ID or CLIX_API_KEY");
16
+ }
17
+
18
+ async function triggerCampaign({ campaignId, audience, properties }) {
19
+ const url = `https://api.clix.so/api/v1/campaigns/${campaignId}:trigger`;
20
+
21
+ const res = await fetch(url, {
22
+ method: "POST",
23
+ headers: {
24
+ "X-Clix-Project-ID": CLIX_PROJECT_ID,
25
+ "X-Clix-API-Key": CLIX_API_KEY,
26
+ "Content-Type": "application/json",
27
+ },
28
+ body: JSON.stringify({
29
+ audience,
30
+ properties,
31
+ }),
32
+ });
33
+
34
+ const text = await res.text();
35
+ if (!res.ok) {
36
+ throw new Error(`Clix trigger failed (${res.status}): ${text}`);
37
+ }
38
+ return JSON.parse(text);
39
+ }
40
+
41
+ // Example usage
42
+ async function main() {
43
+ const campaignId = "019aa002-1d0e-7407-a0c5-5bfa8dd2be30"; // replace
44
+
45
+ const payload = {
46
+ audience: { broadcast: true },
47
+ properties: {
48
+ store_location: "San Francisco",
49
+ order_id: "ORD-12345",
50
+ item_count: 3,
51
+ pickup_time: "2:30 PM",
52
+ },
53
+ };
54
+
55
+ const out = await triggerCampaign({ campaignId, ...payload });
56
+ console.log(out); // { trigger_id: "..." }
57
+ }
58
+
59
+ main().catch((e) => {
60
+ console.error(e);
61
+ process.exit(1);
62
+ });
@@ -0,0 +1,58 @@
1
+ """
2
+ Minimal Python example: trigger an API-triggered campaign.
3
+
4
+ Requirements:
5
+ pip install requests
6
+ Env vars:
7
+ - CLIX_PROJECT_ID
8
+ - CLIX_API_KEY
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import sys
14
+ from typing import Any, Dict
15
+
16
+ import requests
17
+
18
+
19
+ def trigger_campaign(*, campaign_id: str, audience: Dict[str, Any], properties: Dict[str, Any]) -> Dict[str, Any]:
20
+ project_id = os.environ.get("CLIX_PROJECT_ID")
21
+ api_key = os.environ.get("CLIX_API_KEY")
22
+ if not project_id or not api_key:
23
+ raise RuntimeError("Missing CLIX_PROJECT_ID or CLIX_API_KEY")
24
+
25
+ url = f"https://api.clix.so/api/v1/campaigns/{campaign_id}:trigger"
26
+ res = requests.post(
27
+ url,
28
+ headers={
29
+ "X-Clix-Project-ID": project_id,
30
+ "X-Clix-API-Key": api_key,
31
+ "Content-Type": "application/json",
32
+ },
33
+ json={"audience": audience, "properties": properties},
34
+ timeout=10,
35
+ )
36
+ if res.status_code >= 400:
37
+ raise RuntimeError(f"Clix trigger failed ({res.status_code}): {res.text}")
38
+ return res.json()
39
+
40
+
41
+ def main() -> int:
42
+ out = trigger_campaign(
43
+ campaign_id="019aa002-1d0e-7407-a0c5-5bfa8dd2be30", # replace
44
+ audience={"broadcast": True},
45
+ properties={
46
+ "store_location": "San Francisco",
47
+ "order_id": "ORD-12345",
48
+ "item_count": 3,
49
+ "pickup_time": "2:30 PM",
50
+ },
51
+ )
52
+ print(json.dumps(out, indent=2))
53
+ return 0
54
+
55
+
56
+ if __name__ == "__main__":
57
+ sys.exit(main())
58
+
@@ -0,0 +1,86 @@
1
+ # Trigger Campaign API (Contract)
2
+
3
+ This reference documents the backend API call used to trigger an API-triggered
4
+ campaign.
5
+
6
+ ## Endpoint
7
+
8
+ ```
9
+ POST https://api.clix.so/api/v1/campaigns/{campaign_id}:trigger
10
+ ```
11
+
12
+ ## Authentication headers (required)
13
+
14
+ - `X-Clix-Project-ID`: your project id
15
+ - `X-Clix-API-Key`: your **secret** API key (treat as a secret; never ship to
16
+ clients)
17
+ - `Content-Type: application/json`
18
+
19
+ ## Request body
20
+
21
+ Top-level:
22
+
23
+ - `audience` (optional): targeting for this trigger
24
+ - `properties` (optional): key-value map used for both audience +
25
+ personalization
26
+
27
+ ### Audience object
28
+
29
+ - `broadcast` (boolean, optional): when true, send to all users eligible under
30
+ the campaign’s segment definition (ignores `targets`)
31
+ - `targets` (array, optional): specific recipients to narrow to (still filtered
32
+ by the campaign’s segment definition)
33
+
34
+ ### Target object
35
+
36
+ Each target should specify **exactly one**:
37
+
38
+ - `project_user_id` (string)
39
+ - `device_id` (string)
40
+
41
+ ## Properties (`trigger.*`)
42
+
43
+ All keys in `properties` are available as `trigger.<key>` in:
44
+
45
+ - **Audience rules** (dynamic filters):
46
+ `store_location == {{ trigger.store_location }}`
47
+ - **Templates** (title/body/subtitle/deep links):
48
+ `Order #{{ trigger.order_id }}`
49
+
50
+ Best practices:
51
+
52
+ - Use **snake_case** keys.
53
+ - Prefer **primitives** (string/number/boolean). Pre-format for display (e.g.,
54
+ send `"$29.99"` rather than `2999` if you want formatted output).
55
+ - Avoid PII by default (email, phone, free-text entered by users).
56
+
57
+ ## Responses
58
+
59
+ ### 200 OK
60
+
61
+ Returns a trigger identifier:
62
+
63
+ ```json
64
+ { "trigger_id": "5dbdd10e-6ea6-4ff7-836d-bd30a6d1a521" }
65
+ ```
66
+
67
+ ### 400 Bad Request
68
+
69
+ Common causes:
70
+
71
+ - missing/invalid `campaign_id`
72
+ - malformed JSON body
73
+ - campaign isn’t configured as API-triggered
74
+
75
+ ### 401 Unauthorized
76
+
77
+ Common causes:
78
+
79
+ - missing/invalid `X-Clix-Project-ID` or `X-Clix-API-Key`
80
+
81
+ ## Operational notes
82
+
83
+ - Delivery is asynchronous; the API returns quickly with `trigger_id`.
84
+ - Segment filtering is always applied:
85
+ - `broadcast=true`: sends to all users matching segment
86
+ - `targets=[...]`: sends only to targets who also match segment
@@ -0,0 +1,84 @@
1
+ # Backend Implementation Patterns
2
+
3
+ This reference focuses on production-safe backend triggering:
4
+
5
+ - auth
6
+ - timeouts
7
+ - retries
8
+ - dedupe
9
+ - logging
10
+
11
+ ## Recommended wrapper shape
12
+
13
+ Implement a single function in your backend (service/module) that all call sites
14
+ use:
15
+
16
+ - input: `campaign_id`, `audience`, `properties`, `correlation_id`
17
+ - output: `trigger_id` (or structured error)
18
+
19
+ Centralizing this wrapper ensures consistent auth, timeouts, and error handling.
20
+
21
+ ## Secrets + configuration
22
+
23
+ - Store secrets in your secret manager (or env vars on the server).
24
+ - Use different keys per environment (dev/staging/prod).
25
+ - Never send `X-Clix-API-Key` to mobile/web clients.
26
+
27
+ Required environment variables (suggested names):
28
+
29
+ - `CLIX_PROJECT_ID`
30
+ - `CLIX_API_KEY`
31
+
32
+ ## Timeouts
33
+
34
+ Always set a client-side timeout (example: 3–10 seconds). The API is “send-like”
35
+ and should not block core request handling indefinitely.
36
+
37
+ ## Retries (safe defaults)
38
+
39
+ Retry only when it’s plausibly transient:
40
+
41
+ - network errors / timeouts
42
+ - `5xx` responses
43
+
44
+ Do **not** retry blindly on `4xx` (usually contract/auth issues).
45
+
46
+ Use exponential backoff and cap total retry time.
47
+
48
+ ## Dedupe (prevent double-sends)
49
+
50
+ Typical causes of duplicates:
51
+
52
+ - message triggered by at-least-once job processing
53
+ - retries at the application layer
54
+ - replays after partial failures
55
+
56
+ Best practice:
57
+
58
+ - Define a stable dedupe key (e.g., `order_id + campaign_id`).
59
+ - Store it for a short TTL (e.g., 24h) in Redis/DB to prevent re-sends.
60
+
61
+ ## Logging + observability
62
+
63
+ Log:
64
+
65
+ - `campaign_id`
66
+ - your correlation id (order id / ticket id)
67
+ - `audience` mode (broadcast/targets)
68
+ - Clix response `trigger_id` on success
69
+ - HTTP status + response body on failures (redact secrets)
70
+
71
+ ## Payload conventions
72
+
73
+ - Prefer snake_case keys in `properties`.
74
+ - Prefer primitives.
75
+ - Pre-format display values (currency, duration, timestamps) if you want
76
+ consistent rendering.
77
+ - Avoid free-text PII by default.
78
+
79
+ ## Examples
80
+
81
+ See:
82
+
83
+ - `examples/trigger-campaign-node.js`
84
+ - `examples/trigger-campaign-python.py`
@@ -0,0 +1,74 @@
1
+ # Console Setup (API-Triggered Campaigns)
2
+
3
+ This reference is for configuring the campaign **once** in the Clix console so
4
+ your backend only needs to trigger with a small, stable payload.
5
+
6
+ ## 1) Create the campaign
7
+
8
+ In the Clix console:
9
+
10
+ 1. Go to **Campaigns** → **Create Campaign**
11
+ 2. Choose your channel (push/in-app/email/etc.)
12
+ 3. In **Schedule & Launch**, select **API-Triggered**
13
+
14
+ After saving, copy the `campaign_id`:
15
+
16
+ - From the campaign details, or
17
+ - From the URL: `.../campaigns/{campaign_id}`
18
+
19
+ ## 2) Dynamic audience filters (`trigger.*`)
20
+
21
+ API-triggered campaigns support dynamic filtering where the **filter value**
22
+ comes from the trigger payload (your API request).
23
+
24
+ Example audience rule:
25
+
26
+ ```
27
+ Group 1
28
+ user_role equals "store_staff"
29
+ AND
30
+ store_location equals {{ trigger.store_location }}
31
+ ```
32
+
33
+ Then your backend passes:
34
+
35
+ ```json
36
+ {
37
+ "properties": { "store_location": "San Francisco" }
38
+ }
39
+ ```
40
+
41
+ So delivery is limited to users matching:
42
+
43
+ - static condition: `user_role == "store_staff"`
44
+ - dynamic condition: `store_location == "San Francisco"`
45
+
46
+ ## 3) Limitations (design constraints)
47
+
48
+ To keep on-demand filtering fast:
49
+
50
+ - Keep audience definitions simple: **max 3 attributes**
51
+ - Combine with **AND**/**OR** only within those constraints
52
+
53
+ If you need complex targeting logic (many attributes, heavy joins), do it in
54
+ your backend and use `audience.targets` for explicit recipients.
55
+
56
+ ## 4) Dynamic content (templates + deep links)
57
+
58
+ Use `trigger.*` properties in templates:
59
+
60
+ - Title: `New order at {{ trigger.store_name }}`
61
+ - Body: `Order #{{ trigger.order_id }} from {{ trigger.customer_name }}`
62
+ - Deep link: `myapp://orders/{{ trigger.order_id }}`
63
+
64
+ Guidance:
65
+
66
+ - For optional data, use defaults/guards so empty strings still read well.
67
+ - Prefer pre-formatted values sent from backend (currency, durations, times).
68
+
69
+ ## 5) Verification checklist in console
70
+
71
+ - Campaign type is **API-Triggered**
72
+ - Audience rules reference `trigger.*` keys that your backend will send
73
+ - Template preview renders correctly with a sample payload
74
+ - Message Logs show no rendering errors after a test trigger
@@ -0,0 +1,77 @@
1
+ # Debugging API-Triggered Campaigns
2
+
3
+ Use this checklist when you triggered the API but users didn’t receive messages
4
+ or templates rendered incorrectly.
5
+
6
+ ## 1) Confirm the campaign type and ID
7
+
8
+ - Campaign is configured as **API-Triggered**
9
+ - `campaign_id` in your backend call matches the console campaign
10
+
11
+ ## 2) Confirm auth headers
12
+
13
+ - `X-Clix-Project-ID` is correct for the environment
14
+ - `X-Clix-API-Key` is a valid **secret** key for that project
15
+ - You are calling the correct base URL: `https://api.clix.so`
16
+
17
+ If you see `401`, fix credentials first.
18
+
19
+ ## 3) Segment filtering is always applied
20
+
21
+ Even with `broadcast=true`, only users matching the campaign’s segment
22
+ definition are eligible.
23
+
24
+ If you use `targets`, targeted users must still match the segment rules.
25
+
26
+ ## 4) Dynamic filters require exact keys
27
+
28
+ If your audience rules reference `{{ trigger.store_location }}`, then your API
29
+ call must include:
30
+
31
+ ```json
32
+ { "properties": { "store_location": "..." } }
33
+ ```
34
+
35
+ Common failures:
36
+
37
+ - key mismatch: `storeLocation` vs `store_location`
38
+ - missing property
39
+ - property value type mismatch (string vs number)
40
+
41
+ ## 5) Template rendering issues
42
+
43
+ Check Message Logs in the console for:
44
+
45
+ - missing variables
46
+ - syntax errors in templates
47
+ - unexpected empty strings
48
+
49
+ Fix approach:
50
+
51
+ - add `default` filters
52
+ - add minimal guards for optional blocks
53
+ - pre-format values in backend
54
+
55
+ ## 6) API errors
56
+
57
+ - `400`: invalid/missing campaign id, malformed JSON, or campaign not
58
+ triggerable
59
+ - `5xx`: transient server error (retry with backoff)
60
+
61
+ ## 7) Rate limits and retry storms
62
+
63
+ If you trigger from high-volume workflows:
64
+
65
+ - throttle upstream events
66
+ - dedupe sends
67
+ - add backoff on retries
68
+
69
+ ## 8) Minimal “known-good” test
70
+
71
+ Trigger once with:
72
+
73
+ - `broadcast=true`
74
+ - a single dynamic filter key with a known-matching value
75
+ - minimal properties used in template
76
+
77
+ Then expand gradually (more properties, more audience constraints).
@@ -0,0 +1,54 @@
1
+ # Personalization + Dynamic Filters (`trigger.*`)
2
+
3
+ In API-triggered campaigns, your backend passes a `properties` map. These keys
4
+ become available as `trigger.*` inside:
5
+
6
+ - templates (title/body/subtitle)
7
+ - deep links / URLs
8
+ - audience rules (dynamic filtering)
9
+
10
+ ## Naming + stability
11
+
12
+ - Use **snake_case** keys (`store_location`, `order_id`).
13
+ - Keep keys stable over time; changing keys can break targeting and templates.
14
+
15
+ ## Missing data behavior
16
+
17
+ If a property is missing, templates will often render it as an empty string.
18
+ Design templates so they still read well.
19
+
20
+ Suggested patterns:
21
+
22
+ - Provide defaults: `{{ trigger.discount | default: "10%" }}`
23
+ - Use guards/conditionals for optional blocks (keep logic minimal).
24
+
25
+ ## Pre-format values in backend
26
+
27
+ Templates are not a full programming language. Prefer sending pre-formatted
28
+ values:
29
+
30
+ - send `"$29.99"` (string) rather than `2999` (number) if you want displayed
31
+ currency
32
+ - send `"2:30 PM"` rather than raw timestamps if that’s what the message should
33
+ show
34
+
35
+ ## Dynamic audience filtering constraints
36
+
37
+ Keep on-demand filtering fast:
38
+
39
+ - max **3 attributes** per audience definition
40
+ - use simple AND/OR combinations
41
+
42
+ If you need complex targeting:
43
+
44
+ - compute recipients in your backend
45
+ - use `audience.targets` to specify recipients explicitly
46
+
47
+ ## Coordinate with event tracking and user properties
48
+
49
+ For templates that depend on:
50
+
51
+ - `user.*`: ensure your app sets user properties correctly (see
52
+ `clix-user-management`)
53
+ - `event.*`: use event-triggered campaigns (see `clix-event-tracking`)
54
+ - `trigger.*`: use this skill (API-triggered campaigns)
@@ -0,0 +1,32 @@
1
+ # Security & Key Handling
2
+
3
+ API-triggered campaigns use secret credentials. Treat them like database
4
+ passwords.
5
+
6
+ ## Which key is used here?
7
+
8
+ The trigger endpoint uses:
9
+
10
+ - `X-Clix-Project-ID`
11
+ - `X-Clix-API-Key` (**Secret API Key**)
12
+
13
+ Do not confuse this with mobile SDK public keys.
14
+
15
+ ## Rules (do this by default)
16
+
17
+ - **Backend-only**: never expose the secret key in mobile/web apps.
18
+ - **No source control**: do not commit keys in git (including examples).
19
+ - **Use a secret store**: Vault / AWS Secrets Manager / GCP Secret Manager /
20
+ Doppler / 1Password CLI, etc.
21
+ - **Rotate** keys periodically; rotate immediately if leaked.
22
+ - **Separate environments**: dev/staging/prod should not share secret keys.
23
+
24
+ ## Logging
25
+
26
+ - Never log request headers containing secrets.
27
+ - If you log the payload for debugging, consider redacting sensitive properties.
28
+
29
+ ## Least privilege
30
+
31
+ If Clix supports scoped keys in your environment, prefer keys limited to the
32
+ required API calls.
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # Validate a Clix API-triggered campaign plan (api-trigger-plan.json).
4
+ #
5
+ # Usage:
6
+ # bash skills/api-triggered-campaigns/scripts/validate-api-trigger-plan.sh path/to/api-trigger-plan.json
7
+ #
8
+ # What it validates:
9
+ # - JSON is valid
10
+ # - campaign_id is present (string)
11
+ # - dynamic_filter_keys is an array of <= 3 snake_case keys
12
+ # - properties is a non-empty object with snake_case keys
13
+ # - each property spec has a valid type and optional required/example/pii fields
14
+ # - example value matches declared type (basic check)
15
+ # - audience.mode is one of: broadcast | targets | default
16
+ # - if audience.mode == targets: targets is a non-empty array and each entry has exactly one identifier (project_user_id or device_id)
17
+ #
18
+ set -euo pipefail
19
+
20
+ plan_path="${1:-}"
21
+ if [[ -z "$plan_path" ]]; then
22
+ echo "Usage: bash skills/api-triggered-campaigns/scripts/validate-api-trigger-plan.sh path/to/api-trigger-plan.json" >&2
23
+ exit 2
24
+ fi
25
+
26
+ if [[ ! -f "$plan_path" ]]; then
27
+ echo "Error: file not found: $plan_path" >&2
28
+ exit 2
29
+ fi
30
+
31
+ validate_with_python() {
32
+ python3 - "$plan_path" <<'PY'
33
+ import json
34
+ import re
35
+ import sys
36
+
37
+ path = sys.argv[1]
38
+ snake = re.compile(r"^[a-z][a-z0-9_]*$")
39
+
40
+ def is_primitive(v):
41
+ return isinstance(v, (str, int, float, bool)) or v is None
42
+
43
+ with open(path, "r", encoding="utf-8") as f:
44
+ data = json.load(f)
45
+
46
+ errors = []
47
+
48
+ campaign_id = data.get("campaign_id")
49
+ if not isinstance(campaign_id, str) or not campaign_id.strip():
50
+ errors.append("campaign_id must be a non-empty string")
51
+
52
+ aud = data.get("audience", {})
53
+ if aud is None:
54
+ aud = {}
55
+ if not isinstance(aud, dict):
56
+ errors.append("audience must be an object if present")
57
+ aud = {}
58
+
59
+ mode = aud.get("mode", "default")
60
+ if mode not in ("broadcast", "targets", "default"):
61
+ errors.append("audience.mode must be one of: broadcast, targets, default")
62
+
63
+ targets = aud.get("targets")
64
+ if mode == "targets":
65
+ if not isinstance(targets, list) or not targets:
66
+ errors.append("audience.targets must be a non-empty array when audience.mode == 'targets'")
67
+ else:
68
+ for i, t in enumerate(targets):
69
+ if not isinstance(t, dict):
70
+ errors.append(f"audience.targets[{i}] must be an object")
71
+ continue
72
+ has_puid = isinstance(t.get("project_user_id"), str) and t.get("project_user_id").strip()
73
+ has_did = isinstance(t.get("device_id"), str) and t.get("device_id").strip()
74
+ if has_puid and has_did:
75
+ errors.append(f"audience.targets[{i}] must specify exactly one of project_user_id or device_id (not both)")
76
+ elif not has_puid and not has_did:
77
+ errors.append(f"audience.targets[{i}] must specify exactly one of project_user_id or device_id")
78
+ else:
79
+ # If not targets mode, we ignore targets but still validate shape if provided
80
+ if targets is not None and not isinstance(targets, list):
81
+ errors.append("audience.targets must be an array if present")
82
+
83
+ dfk = data.get("dynamic_filter_keys", [])
84
+ if dfk is None:
85
+ dfk = []
86
+ if not isinstance(dfk, list):
87
+ errors.append("dynamic_filter_keys must be an array if present")
88
+ else:
89
+ if len(dfk) > 3:
90
+ errors.append("dynamic_filter_keys must contain at most 3 entries")
91
+ for i, k in enumerate(dfk):
92
+ if not isinstance(k, str) or not snake.match(k):
93
+ errors.append(f"dynamic_filter_keys[{i}] must be snake_case string")
94
+
95
+ props = data.get("properties")
96
+ if not isinstance(props, dict) or not props:
97
+ errors.append("properties must be a non-empty object")
98
+ else:
99
+ for key, spec in props.items():
100
+ if not isinstance(key, str) or not snake.match(key):
101
+ errors.append(f"properties key '{key}' must be snake_case")
102
+ if not isinstance(spec, dict):
103
+ errors.append(f"properties['{key}'] must be an object")
104
+ continue
105
+ t = spec.get("type")
106
+ if t is None:
107
+ errors.append(f"properties['{key}'].type is required")
108
+ continue
109
+ if t not in ("string", "number", "boolean", "datetime"):
110
+ errors.append(
111
+ f"properties['{key}'].type must be one of: string, number, boolean, datetime"
112
+ )
113
+ req = spec.get("required")
114
+ if req is not None and not isinstance(req, bool):
115
+ errors.append(f"properties['{key}'].required must be boolean if present")
116
+ pii = spec.get("pii")
117
+ if pii is not None and not isinstance(pii, bool):
118
+ errors.append(f"properties['{key}'].pii must be boolean if present")
119
+
120
+ ex = spec.get("example")
121
+ if ex is not None:
122
+ if not is_primitive(ex):
123
+ errors.append(f"properties['{key}'].example must be a primitive (string/number/boolean/null)")
124
+ else:
125
+ if t == "string" and not isinstance(ex, str):
126
+ errors.append(f"properties['{key}'].example must be a string")
127
+ if t == "boolean" and not isinstance(ex, bool):
128
+ errors.append(f"properties['{key}'].example must be a boolean")
129
+ if t == "number":
130
+ # In Python, bool is a subclass of int; exclude it explicitly.
131
+ if isinstance(ex, bool) or not isinstance(ex, (int, float)):
132
+ errors.append(f"properties['{key}'].example must be a number")
133
+ if t == "datetime" and not isinstance(ex, str):
134
+ errors.append(f"properties['{key}'].example must be an ISO-8601 string")
135
+
136
+ if errors:
137
+ print("❌ api-trigger-plan validation failed:")
138
+ for e in errors:
139
+ print(f"- {e}")
140
+ sys.exit(1)
141
+
142
+ print("✅ api-trigger-plan validation passed")
143
+ PY
144
+ }
145
+
146
+ if command -v python3 >/dev/null 2>&1; then
147
+ validate_with_python
148
+ exit 0
149
+ fi
150
+
151
+ echo "Warning: python3 not found; only checking JSON validity with node if available." >&2
152
+ if command -v node >/dev/null 2>&1; then
153
+ node -e "JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8')); console.log('✅ JSON is valid');" "$plan_path"
154
+ exit 0
155
+ fi
156
+
157
+ echo "Error: neither python3 nor node found; cannot validate." >&2
158
+ exit 2
159
+