@memberjunction/cli 6.1.2 → 6.2.0-edge.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +18 -7
  2. package/dist/commands/agent/init.d.ts +23 -0
  3. package/dist/commands/agent/init.d.ts.map +1 -0
  4. package/dist/commands/agent/init.js +222 -0
  5. package/dist/commands/agent/init.js.map +1 -0
  6. package/dist/commands/doctor/index.d.ts +6 -4
  7. package/dist/commands/doctor/index.d.ts.map +1 -1
  8. package/dist/commands/doctor/index.js +43 -18
  9. package/dist/commands/doctor/index.js.map +1 -1
  10. package/dist/commands/test/scripts.d.ts +13 -0
  11. package/dist/commands/test/scripts.d.ts.map +1 -0
  12. package/dist/commands/test/scripts.js +50 -0
  13. package/dist/commands/test/scripts.js.map +1 -0
  14. package/dist/init-templates/citizen-builder/.agents/skills/new-agent/SKILL.md +66 -0
  15. package/dist/init-templates/citizen-builder/.agents/skills/package-agent/SKILL.md +69 -0
  16. package/dist/init-templates/citizen-builder/.agents/skills/test-agent/SKILL.md +61 -0
  17. package/dist/init-templates/citizen-builder/.claude/skills/new-agent/SKILL.md +66 -0
  18. package/dist/init-templates/citizen-builder/.claude/skills/package-agent/SKILL.md +69 -0
  19. package/dist/init-templates/citizen-builder/.claude/skills/test-agent/SKILL.md +61 -0
  20. package/dist/init-templates/citizen-builder/.env.example +30 -0
  21. package/dist/init-templates/citizen-builder/AGENTS.md +331 -0
  22. package/dist/init-templates/citizen-builder/README.md +259 -0
  23. package/dist/init-templates/citizen-builder/docker/Dockerfile +16 -0
  24. package/dist/init-templates/citizen-builder/docker-compose.yml +59 -0
  25. package/dist/init-templates/citizen-builder/docs/ENTERPRISE_ORG_SETUP.md +73 -0
  26. package/dist/init-templates/citizen-builder/docs/PROMOTION_GUIDE.md +70 -0
  27. package/dist/init-templates/citizen-builder/metadata/.mj-sync.json +7 -0
  28. package/dist/init-templates/citizen-builder/metadata/agents/.customer-insight-agent.json +55 -0
  29. package/dist/init-templates/citizen-builder/metadata/agents/.mj-sync.json +45 -0
  30. package/dist/init-templates/citizen-builder/metadata/prompts/.customer-insight-prompt.json +15 -0
  31. package/dist/init-templates/citizen-builder/metadata/prompts/.mj-sync.json +45 -0
  32. package/dist/init-templates/citizen-builder/metadata/prompts/templates/customer-insight.template.md +18 -0
  33. package/dist/init-templates/citizen-builder/scripts/bootstrap.sh +47 -0
  34. package/dist/init-templates/citizen-builder/scripts/docker-entrypoint.sh +184 -0
  35. package/dist/init-templates/citizen-builder/scripts/generate-capabilities.sh +74 -0
  36. package/dist/init-templates/citizen-builder/scripts/query-run-history.sh +34 -0
  37. package/dist/init-templates/citizen-builder/scripts/sync-metadata.sh +14 -0
  38. package/dist/init-templates/remote-mj/README.md +4 -4
  39. package/oclif.manifest.json +271 -98
  40. package/package.json +22 -22
@@ -0,0 +1,331 @@
1
+ # Citizen Agent Builder — Coding Agent Instructions (`AGENTS.md`)
2
+
3
+ You are the AI pair programmer and authoring assistant for a business user building **MemberJunction AI Agents**.
4
+
5
+ ## Core Product Principle
6
+
7
+ > **Make the human surface simple; keep the agent surface complete.**
8
+
9
+ The business-user experience should be simple: the user chats with you and describes their business goal.
10
+ However, **your surface as the agent is comprehensive and complete**. You have full access to MemberJunction's declarative configuration, entities, actions, prompts, agent types, sub-agents, metadata synchronization, diagnostic probes, traces, and packaging. Safety controls govern consequential actions (e.g. database schema changes) rather than restricting what you can design.
11
+
12
+ Your user is a business user (operations lead, analyst, product manager, rev-ops) who has elevated machine permissions (can run Docker Desktop and CLI commands), but **is not a software developer**:
13
+ - **NEVER** ask them to write TypeScript, Angular, SQL DDL, or database migrations.
14
+ - **NEVER** ask them to edit JSON metadata or write prompt templates by hand.
15
+ - You do the discovery, authoring, validating, database syncing, diagnostics, trace verification, and packaging. The user describes business intent, tests the experience in the UI or CLI, and gives you feedback.
16
+
17
+ ---
18
+
19
+ ## 1. Documentation & Architecture References
20
+
21
+ Before and during authoring, refer to the authoritative MemberJunction documentation:
22
+
23
+ ### A. Official Documentation Site (`docs.memberjunction.org`)
24
+ When you need to understand MemberJunction concepts, entity APIs, or configuration shapes, use your web search/fetch tools to research:
25
+ * **Documentation Portal**: [https://docs.memberjunction.org/](https://docs.memberjunction.org/)
26
+ * **AI Agents Architecture**: [https://docs.memberjunction.org/ai/](https://docs.memberjunction.org/ai/) — Covers Agent Types (`Flow` vs `Loop`), Prompt bindings, model selection, execution lifecycle, and sub-agents.
27
+ * **Actions Framework**: [https://docs.memberjunction.org/actions/](https://docs.memberjunction.org/actions/) — Action parameters, return codes, synchronous vs async execution.
28
+ * **Metadata Sync System**: [https://docs.memberjunction.org/developer-guide/metadata-sync/](https://docs.memberjunction.org/developer-guide/metadata-sync/) — Explains how JSON metadata records represent database rows, reference resolution, and upsert semantics.
29
+ * **Entity Data Platform**: [https://docs.memberjunction.org/concepts/entities/](https://docs.memberjunction.org/concepts/entities/) — Entities, entity fields, permissions, and query conventions.
30
+
31
+ ### B. MemberJunction Repository Reference Documents
32
+ If you have access to the MemberJunction repository (or view them on GitHub at `https://github.com/MemberJunction/MJ/blob/next/`):
33
+ * [`metadata/CLAUDE.md`](https://github.com/MemberJunction/MJ/blob/next/metadata/CLAUDE.md): **The Definitive Metadata Specification**. Authoritative rules on `@lookup`, `@file`, `@parent`, native JSON-type fields, and `mj sync push` mechanics.
34
+ * [`packages/Actions/CLAUDE.md`](https://github.com/MemberJunction/MJ/blob/next/packages/Actions/CLAUDE.md): Conventions for Action authoring, parameter schemas, and error handling.
35
+ * [`packages/AI/README.md`](https://github.com/MemberJunction/MJ/blob/next/packages/AI/README.md): Deep dive into AI providers, AgentManager state graphs, and execution engines.
36
+
37
+ ---
38
+
39
+ ## 2. MetadataSync & JSON Formatting Rules (CRITICAL)
40
+
41
+ The MetadataSync engine (`mj sync push`) parses declarative JSON files under `./metadata/` and maps them into SQL Server records. Follow these rules strictly:
42
+
43
+ ### A. JSON-Type Fields: Native JSON Objects (NEVER Escaped Strings)
44
+ In MemberJunction v6, database fields that hold structured JSON (such as `Configuration`, `Settings`, `Metadata`, etc.) **MUST be written as clean, native nested JSON objects** directly in your metadata files.
45
+
46
+ ```json
47
+ // ❌ WRONG — Escaped strings break validation and reference resolution!
48
+ {
49
+ "fields": {
50
+ "Name": "Invoice Analysis Agent",
51
+ "Configuration": "{\"Steps\":[{\"Name\":\"ProcessInvoice\",\"StepType\":\"Prompt\"}]}"
52
+ }
53
+ }
54
+
55
+ // ✅ CORRECT — Clean, native nested JSON object
56
+ {
57
+ "fields": {
58
+ "Name": "Invoice Analysis Agent",
59
+ "Configuration": {
60
+ "Steps": [
61
+ {
62
+ "Name": "ProcessInvoice",
63
+ "StepType": "Prompt",
64
+ "TargetID": "@lookup:MJ: AI Prompts.Name=Invoice Analysis Prompt",
65
+ "ExecutionOrder": 1,
66
+ "OnError": "fail"
67
+ }
68
+ ]
69
+ }
70
+ }
71
+ }
72
+ ```
73
+ *Why this matters*: When formatted as native JSON, MetadataSync automatically crawls the object tree, resolves any `@lookup:` or `@file:` tokens inside the JSON to real UUIDs, and handles database serialization automatically.
74
+
75
+ ### B. Reference Tokens: `@lookup`, `@file`, `@parent`
76
+ Never hardcode foreign key UUIDs. Use dynamic reference tokens:
77
+ * **`@lookup:<EntityName>.<FieldName>=<Value>`**: Resolves foreign keys by querying records at sync time.
78
+ - *Single field*: `"TypeID": "@lookup:MJ: AI Agent Types.Name=Flow"`
79
+ - *Category lookup*: `"CategoryID": "@lookup:MJ: AI Agent Categories.Name=Assistant"`
80
+ - *Multi-field lookup*: `"PromptID": "@lookup:MJ: AI Prompts.Name=My Prompt&Status=Active"`
81
+ * **`@file:<relativePath>`**: Replaces the field value with the contents of an external file.
82
+ - Used for prompt templates: `"TemplateText": "@file:templates/my-agent.template.md"`
83
+ - *Note*: `@file:` paths are resolved at push time. If you modify a `.template.md` file, you must run `./scripts/sync-metadata.sh` again to push changes to the database.
84
+ * **`@parent:<FieldName>`**: References a field on the parent record in nested hierarchical JSON files (e.g. `"AgentID": "@parent:ID"`).
85
+
86
+ ### C. System-Generated Fields: Do NOT Include `sync`
87
+ * **NEVER author a `sync` block** (`lastModified`, `checksum`). `mj sync push` manages this block automatically. If you write it by hand, checksum calculation will fail.
88
+ * **Do NOT include timestamp fields**: `CreatedAt`, `UpdatedAt`, `__mj_CreatedAt`, `__mj_UpdatedAt` are managed by the database engine.
89
+ * **Assign deterministic `primaryKey`**: Assign a fresh UUID in uppercase (e.g., generated via CLI `uuidgen | tr '[:lower:]' '[:upper:]'`) so the entity retains the exact same ID across all environments.
90
+
91
+ ### D. Flow Agent Step Graph Schema
92
+ For `Flow` agents, structure the `Configuration.Steps` array in `metadata/agents/.*.json` like this:
93
+ ```json
94
+ "Configuration": {
95
+ "Steps": [
96
+ {
97
+ "Name": "Step 1 Name",
98
+ "Description": "Evaluates customer orders",
99
+ "StepType": "Prompt",
100
+ "TargetID": "@lookup:MJ: AI Prompts.Name=Step 1 Prompt",
101
+ "ExecutionOrder": 1,
102
+ "OnError": "fail",
103
+ "RetryCount": 0,
104
+ "TimeoutSeconds": 300
105
+ },
106
+ {
107
+ "Name": "Step 2 Name",
108
+ "Description": "Executes notification action",
109
+ "StepType": "Action",
110
+ "TargetID": "@lookup:MJ: Actions.Name=Send Email",
111
+ "ExecutionOrder": 2,
112
+ "OnError": "continue"
113
+ }
114
+ ]
115
+ }
116
+ ```
117
+
118
+ ### E. File Naming & Directory Structure
119
+ * **Agent definitions**: `metadata/agents/.<slug>-agent.json` (must start with `.` to match the `.*.json` pattern in `.mj-sync.json`).
120
+ * **Prompt definitions**: `metadata/prompts/.<slug>-prompt.json`.
121
+ * **Prompt templates**: `metadata/prompts/templates/<slug>.template.md`.
122
+ ```
123
+ metadata/
124
+ ├── .mj-sync.json
125
+ ├── agents/
126
+ │ ├── .mj-sync.json
127
+ │ └── .<slug>-agent.json
128
+ └── prompts/
129
+ ├── .mj-sync.json
130
+ ├── .<slug>-prompt.json
131
+ └── templates/
132
+ └── <slug>.template.md
133
+ ```
134
+
135
+ ---
136
+
137
+ ## 3. The Three Tiers — Rules and Boundaries
138
+
139
+ The boundary between tiers is **code** and **schema**.
140
+
141
+ | Tier | Boundary | What You May Author | Human Approval Needed? |
142
+ |---|---|---|---|
143
+ | **Tier 1** | **Declarative Only** | Agents, prompts, flows, loops, step configurations, action bindings, payload mapping, and sub-agent composition. | No — auto-promotable |
144
+ | **Tier 2** | **Runtime Code** | Sandboxed JavaScript **Runtime Actions** with explicit permission scopes. | Yes — admin code review |
145
+ | **Tier 3** | **Schema Changes** | New database tables, columns, migrations, or entity CodeGen. | **FORBIDDEN** for citizen builders |
146
+
147
+ ### Tier 1: Make Declarative as Powerful as Possible
148
+ Push hard to solve the user's intent in Tier 1. Use:
149
+ * **Flow Agents**: Best for deterministic pipelines ("Step 1: lookup customer -> Step 2: calculate balance -> Step 3: draft email").
150
+ * **Sub-Agent Composition**: Delegate complex tasks to other existing agents (e.g., query generation, research) rather than writing custom code.
151
+ * **Existing Actions**: Reuse existing actions in the catalog.
152
+
153
+ ### Tier 2: Sandboxed Runtime Actions (When Custom Logic is Essential)
154
+ If a requirement cannot be met declaratively or via existing actions (e.g. specialized math, external API formatting):
155
+ 1. Author a Runtime Action in JavaScript.
156
+ 2. **Explicit Permission Scope**: You MUST define an explicit `allowedEntities` list. NEVER use `allowAnyEntity: true` or wildcards in final submissions.
157
+ 3. Inform the user: *"I've created a custom Runtime Action for this logic. It will run in an isolated sandbox and will require admin approval when promoted."*
158
+
159
+ ### Tier 3: Entity/Schema Boundary
160
+ If the user asks for new tables, columns, or physical database modifications:
161
+ - Stop immediately and explain: *"Creating new database entities or modifying schema is a Tier 3 platform change. MemberJunction's platform engineering team manages database schema. However, we can track this information using existing entities or metadata."*
162
+
163
+ ---
164
+
165
+ ## 4. Mandatory Authoring Defaults & Guardrails
166
+
167
+ These defaults prevent portability bugs and privilege escalation:
168
+
169
+ 1. **Never Let the User or Agent Hardcode LLM Models:**
170
+ - Always set `ModelSelectionMode: "Agent Type"`.
171
+ - Never emit an `MJ: AI Prompt Models` block pinning a specific provider model (e.g. `gpt-4o` or `claude-3-5-sonnet`). The destination environment determines which models back each Agent Type.
172
+ 2. **`ExposeAsAction: false` by Default:**
173
+ - Do NOT set `ExposeAsAction: true` unless explicitly requested. Exposing an agent as an action allows other agents to invoke it, which is an unintended privilege escalation for personal agents.
174
+ 3. **Never Hardcode Record Names or IDs:**
175
+ - Entity schemas are portable across environments; record instances and IDs are not.
176
+ - Prompts must resolve records dynamically via queries, lookup actions, or input parameters. Never write prompts like `"Find the member named John Doe (ID: 12345)"`.
177
+ 4. **Prefer `Flow` Over `Loop` for Deterministic Sequences:**
178
+ - If the task is sequential and bounded, use a `Flow` agent. It is faster, cheaper, and far easier to audit. Use `Loop` only when iterative problem-solving with dynamic tool calling is required.
179
+ 5. **Never Hand-Edit `ID`, `lastModified`, or `checksum`:**
180
+ - Let `mj sync push` manage identity and sync checksums in `.agent.json` and `.prompt.json`. Do not invent GUIDs unless authoring a new file that has not been pushed yet.
181
+
182
+ ---
183
+
184
+ ## 5. Security Checklist (Enforce Before Syncing)
185
+
186
+ - [ ] **No Secrets:** No API keys, credentials, bearer tokens, or passwords in prompt text or action parameters.
187
+ - [ ] **Data Access via Entities:** All data operations must use MemberJunction entity permissions or standard actions. Never embed raw SQL statements in prompt templates.
188
+ - [ ] **Human Confirmation on Writes:** In v1, any agent action that updates, inserts, or deletes records must require a confirmation step before committing.
189
+ - [ ] **No PII in Templates:** Prompt templates and few-shot examples must use synthetic/generic data.
190
+
191
+ ---
192
+
193
+ ---
194
+
195
+ ## 6. The Complete 11-Step Agent Engineering Loop
196
+
197
+ MemberJunction provides a machine-readable, agent-first surface. Always follow this full loop when designing and building agents:
198
+
199
+ ```
200
+ 1. Understand Intent ──> 2. Discover Environment ──> 3. Diagnostic Health Check
201
+ │
202
+ 6. Author Metadata <── 5. Choose Pattern <── 4. Reason & Plan
203
+ │
204
+ 7. Validate References ──> 8. Push DB Metadata ──> 9. Run & Test Agent
205
+ │
206
+ 11. Package & Distribute <── 10. Audit Traces & Assert <───────────┘
207
+ ```
208
+
209
+ ### Step 1: Understand Business Intent
210
+ Elicit requirements from the user. Clarify:
211
+ - Inputs expected (e.g. customer ID, date range, message text).
212
+ - Data sources involved (entities, views, existing actions).
213
+ - Desired output format (markdown summary, structured JSON, draft email).
214
+ - Whether operations involve read-only evaluation or write actions requiring confirmation.
215
+
216
+ ### Step 2: Progressive Capability Discovery (CLI & Metadata)
217
+ Never guess entity names, fields, or available actions. Discover them directly:
218
+ - **Read `CAPABILITIES.md`**: Contains pre-generated catalog of entities, fields, and actions in the local instance.
219
+ - **Query Live Actions via CLI**:
220
+ ```bash
221
+ docker compose exec -T mj mj ai actions list --format json
222
+ ```
223
+ - **Query Existing Agents & Prompts**:
224
+ ```bash
225
+ docker compose exec -T mj mj ai agents list --format json
226
+ ```
227
+ - **Refresh Capabilities**:
228
+ ```bash
229
+ ./scripts/generate-capabilities.sh
230
+ ```
231
+
232
+ ### Step 3: Diagnostic Health & Prerequisite Checks
233
+ Check that runtime services, database connectivity, and required AI keys are healthy:
234
+ ```bash
235
+ docker compose exec -T mj mj doctor --format json
236
+ ```
237
+ Filter by specific scopes if diagnosing an issue:
238
+ ```bash
239
+ docker compose exec -T mj mj doctor --format json --scope ai # Check AI provider API keys
240
+ docker compose exec -T mj mj doctor --format json --scope runtime # Check base encryption key & ports
241
+ docker compose exec -T mj mj doctor --format json --scope install # Check node, npm, and packages
242
+ ```
243
+ If checks return warnings or failures with remediations (`Remediation.Command`), apply safe remediations or prompt the user for missing credentials.
244
+
245
+ ### Step 4: Reason & Plan the Configuration
246
+ Determine:
247
+ - Prompt decomposition: Is this a single-turn prompt or multi-step pipeline?
248
+ - Context window management: What data must be retrieved, filtered, or summarized before prompting?
249
+ - Error handling: For each step, should failures halt execution (`"OnError": "fail"`) or continue (`"OnError": "continue"`)?
250
+
251
+ ### Step 5: Select the Execution Pattern
252
+ - **Single Prompt**: Lightweight classification, summarization, or single-entity extraction.
253
+ - **Flow Agent (`Flow`)**: Best for deterministic, sequential, multi-step pipelines ("Step 1: Fetch order history -> Step 2: Compute risk score -> Step 3: Draft retention email"). Predictable, auditable, and low token overhead.
254
+ - **Loop Agent (`Loop`)**: Iterative problem-solving requiring dynamic tool calling, multi-step reasoning, or exploratory querying.
255
+ - **Orchestrator / Sub-Agent Tree**: Complex multi-domain tasks decomposed into specialist sub-agents (e.g., a triage agent dispatching to a risk agent and a billing agent).
256
+
257
+ ### Step 6: Author Declarative Metadata under `metadata/`
258
+ Author files following the strict Section 2 rules:
259
+ - Prompt template: `metadata/prompts/templates/<slug>.template.md`
260
+ - Prompt definition: `metadata/prompts/.<slug>-prompt.json`
261
+ - Agent definition: `metadata/agents/.<slug>-agent.json`
262
+ *(Remember: native nested JSON objects for `Configuration`, `@lookup:` for foreign keys, `@file:` for templates, uppercase UUIDs for `primaryKey`, never author `sync` blocks).*
263
+
264
+ ### Step 7: Pre-Sync Schema & Reference Validation
265
+ Before pushing:
266
+ - Check that every `@lookup:` targets a valid entity and field (e.g. `MJ: AI Agent Types.Name=Flow`).
267
+ - Check that `@file:` points to an existing `.template.md` file.
268
+ - Verify JSON syntax is valid and unescaped.
269
+
270
+ ### Step 8: Push Metadata to Target Database
271
+ Push declarative configuration to the local database:
272
+ ```bash
273
+ ./scripts/sync-metadata.sh
274
+ ```
275
+ MetadataSync crawls the tree, resolves `@lookup:` and `@file:` references, upserts records, and stamps checksums.
276
+
277
+ ### Step 9: Run and Test the Agent
278
+ Test the agent with representative test cases:
279
+ - **Headless CLI execution**:
280
+ ```bash
281
+ docker compose exec -T mj mj ai agents run -a "<Agent Name>" -p "<Test Input>" --format json
282
+ ```
283
+ - **Interactive UI testing**: Invite the user to test in their browser at `http://localhost:4202`.
284
+
285
+ ### Step 10: Audit Execution Traces & Assert Behavior
286
+ Inspect the run trace to verify internal execution paths and safety:
287
+ ```bash
288
+ # List recent runs
289
+ ./scripts/query-run-history.sh "<Agent Name>"
290
+
291
+ # Audit specific run with full JSON trace
292
+ ./scripts/query-run-history.sh <RunID> --format json
293
+
294
+ # Or inspect individual step details or errors
295
+ ./scripts/query-run-history.sh <RunID> --step 1 --detail full
296
+ ./scripts/query-run-history.sh <RunID> --errors
297
+ ```
298
+
299
+ **Trace Verification Assertions**:
300
+ - `actionsUsed`: Verify that the agent called the expected tools/actions.
301
+ - `actionsNotUsed`: Verify that the agent did NOT invoke unauthorized or destructive actions.
302
+ - `tokensUsed`: Verify token consumption is within reasonable bounds.
303
+ - `stepSuccess`: Verify every step completed with status `Success`.
304
+
305
+ ### Step 11: Package for Promotion
306
+ When verification passes:
307
+ 1. Run the **`package-agent` skill**.
308
+ 2. It validates Tier 1 guardrails, queries the latest run receipt from `[__mj].[vwAIAgentRuns]`, and generates `AGENT_MANIFEST.md`.
309
+ 3. It creates the distribution archive `dist/<agent-slug>-package.zip` containing the manifest and declarative metadata.
310
+ 4. Present the user with the package path and promotion instructions.
311
+
312
+ ---
313
+
314
+ ## 7. Available CLI Diagnostic & Execution Commands
315
+
316
+ When operating in the container, use these native MemberJunction CLI commands (all support `--format json`):
317
+
318
+ | Purpose | Command |
319
+ |---|---|
320
+ | **System Diagnostics** | `docker compose exec -T mj mj doctor --format json` |
321
+ | **Scoped Diagnostics** | `docker compose exec -T mj mj doctor --format json --scope [install\|runtime\|ai\|metadata\|agent]` |
322
+ | **List Available Actions** | `docker compose exec -T mj mj ai actions list --format json` |
323
+ | **List Configured Agents** | `docker compose exec -T mj mj ai agents list --format json` |
324
+ | **Execute Agent** | `docker compose exec -T mj mj ai agents run -a "<Name>" -p "<Prompt>" --format json` |
325
+ | **Audit Agent Run** | `docker compose exec -T mj mj ai audit agent-run <RunID> --format json` |
326
+ | **Audit Agent Step** | `docker compose exec -T mj mj ai audit agent-run <RunID> --step <N> --detail full` |
327
+ | **Audit Errors Only** | `docker compose exec -T mj mj ai audit agent-run <RunID> --errors` |
328
+ | **Sync Metadata** | `./scripts/sync-metadata.sh` |
329
+ | **Run History Helper** | `./scripts/query-run-history.sh ["<Agent Name>"\|<RunID>] [--format json]` |
330
+ | **Refresh Capabilities** | `./scripts/generate-capabilities.sh` |
331
+
@@ -0,0 +1,259 @@
1
+ # MemberJunction Citizen Agent Builder
2
+
3
+ > **Instructions for AI Coding Agents (Claude Code, Antigravity, Cursor, Codex, Windsurf):**
4
+ > If you are an AI coding agent reading this file, you have been tasked with setting up, authoring, testing, and packaging MemberJunction AI Agents for your user end-to-end.
5
+ > Follow the numbered steps below. You have the tools to run the bash commands, inspect database traces, author declarative metadata, and package the final agent bundle without requiring your user to write code or manage database migrations.
6
+
7
+ ---
8
+
9
+ ## ⚡ Getting Started (Choose Your Path)
10
+
11
+ ### Option A: The Agent-Driven Path (Recommended — Zero Manual Setup)
12
+ You don't need to manually run CLI commands, configure Docker files, or edit JSON files by hand. Simply create a new empty directory, open your favorite AI coding agent (**Claude Code**, **Antigravity**, **Cursor**, **Codex**, or **Windsurf**), and paste this prompt:
13
+
14
+ ```markdown
15
+ Please review the MemberJunction Citizen Agent Builder guide at:
16
+ https://github.com/MemberJunction/MJ/tree/next/citizen-builder
17
+
18
+ Follow the instructions in that guide:
19
+ 1. Initialize a new MemberJunction agent builder workspace here using `npx @memberjunction/cli agent init .`
20
+ 2. Start the local Docker environment and verify services are running.
21
+ 3. Review available entities and actions in CAPABILITIES.md.
22
+ 4. Build me an AI agent that:
23
+ [Describe your business goal here — e.g. "analyzes customer order frequency and overdue invoices, flags accounts at risk of churning, and drafts personalized retention outreach emails."]
24
+ 5. Push the metadata, run test executions, verify the run traces in the database, and package the final distributable bundle for promotion.
25
+ ```
26
+
27
+ Your coding agent will read the guide, scaffold the workspace, start the local database and API, author the declarative agent metadata, test it against local data, and hand you a packaged distribution `.zip` file with an `AGENT_MANIFEST.md` report.
28
+
29
+ ---
30
+
31
+ ### Option B: The Manual / Step-by-Step Path
32
+ If you prefer to initialize the workspace and start the Docker environment yourself before handing off to an agent:
33
+
34
+ 1. **Scaffold the workspace**:
35
+ ```bash
36
+ npx @memberjunction/cli agent init ./my-agents
37
+ cd ./my-agents
38
+ ```
39
+ 2. **Add your LLM API Key**:
40
+ Open `.env` and add your OpenAI, Anthropic, Gemini, or Groq API key:
41
+ ```bash
42
+ OPENAI_API_KEY=sk-...
43
+ ```
44
+ 3. **Start the local Docker stack**:
45
+ ```bash
46
+ docker compose up -d
47
+ ```
48
+ 4. **Launch your coding agent**:
49
+ Open your coding agent in `./my-agents` and tell it what you want to build:
50
+ ```
51
+ "Build me an agent that monitors accounts receivable aging and drafts payment follow-ups."
52
+ ```
53
+ The coding agent will detect `AGENTS.md`, adhere to the 3-tier safety boundaries, and build the agent for you.
54
+
55
+ ---
56
+
57
+ ## 1. Overview & Architecture
58
+
59
+ > **Product Principle:** *Make the human surface simple; keep the agent surface complete.*
60
+ > The business-user experience is a straightforward chat. The agent experience is comprehensive — giving coding agents full machine-readable access to live entity metadata, actions, progressive CLI discovery, diagnostic probes, execution traces, and packaging.
61
+
62
+ The **Citizen Agent Builder** provides an isolated, local MemberJunction environment that runs entirely inside Docker:
63
+ * **`sqlserver` (Port 1433)**: Microsoft SQL Server 2022.
64
+ * **`mj` (Ports 4000 & 4202)**: A Node 24 container that executes `mj install` on first boot, provisions the database schema, installs business context (More Cheese default, or enterprise apps like Blue Cypress), and serves:
65
+ * **MJAPI** at `http://localhost:4000` (GraphQL API and agent execution engine).
66
+ * **MJExplorer** at `http://localhost:4202` (Web UI for testing agents and viewing records; port 4202 is an authorized redirect URI for Auth0/MSAL).
67
+ * **Metadata Directory (`./metadata`)**: Local JSON and Markdown files mapped into the container. Pushing metadata to the database is done with a single command (`./scripts/sync-metadata.sh`).
68
+
69
+ ### Available Agent Tools & CLI Commands
70
+
71
+ Every tool and command in this workspace supports machine-readable output (`--format json`) for autonomous coding agents:
72
+
73
+ | Tool / Command | What It Does |
74
+ |---|---|
75
+ | `./scripts/sync-metadata.sh` | Pushes declarative metadata files in `./metadata/` to the database, resolving `@lookup` and `@file` references. |
76
+ | `./scripts/query-run-history.sh ["<Agent>"\|<ID>]` | Queries agent run history, step execution traces, and action logs via native CLI. |
77
+ | `./scripts/generate-capabilities.sh` | Re-scans the live database and regenerates `CAPABILITIES.md` with current entities and actions. |
78
+ | `docker compose exec -T mj mj doctor --format json` | Runs system diagnostics returning structured checks, failures, and auto-remediations. |
79
+ | `docker compose exec -T mj mj doctor --format json --scope [ai\|runtime\|install]` | Filters diagnostics by specific subsystem (e.g. AI provider credentials or encryption keys). |
80
+ | `docker compose exec -T mj mj ai actions list --format json` | Lists all available system and business actions with parameter schemas. |
81
+ | `docker compose exec -T mj mj ai agents list --format json` | Lists all existing agents, agent types, and categories in the instance. |
82
+ | `docker compose exec -T mj mj ai agents run -a "<Name>" -p "<Input>" --format json` | Executes an agent headlessly and emits structured execution results. |
83
+ | `docker compose exec -T mj mj ai audit agent-run <ID> --format json` | Audits an agent run: step-by-step prompts, LLM completions, token counts, and tool calls. |
84
+
85
+ ---
86
+
87
+ ## 2. Documentation & Architecture References
88
+
89
+ When authoring agents or researching MemberJunction APIs, consult these authoritative resources:
90
+
91
+ ### A. Official Documentation Portal (`docs.memberjunction.org`)
92
+ Use your web search or fetch tools to research topics across the documentation portal:
93
+ * **Documentation Portal**: [https://docs.memberjunction.org/](https://docs.memberjunction.org/)
94
+ * **AI Agents Architecture**: [https://docs.memberjunction.org/ai/](https://docs.memberjunction.org/ai/) — Details on Agent Types (`Flow` deterministic step graphs vs `Loop` iterative tool-calling), Prompt bindings, model selection, execution lifecycles, and sub-agents.
95
+ * **Actions Framework**: [https://docs.memberjunction.org/actions/](https://docs.memberjunction.org/actions/) — Available actions, parameter definitions, and result codes.
96
+ * **Metadata Sync System**: [https://docs.memberjunction.org/developer-guide/metadata-sync/](https://docs.memberjunction.org/developer-guide/metadata-sync/) — Complete specification for declarative metadata files, reference resolution, and upsert mechanics.
97
+ * **Entity Data Platform**: [https://docs.memberjunction.org/concepts/entities/](https://docs.memberjunction.org/concepts/entities/) — Core entities, schema relationships, permissions, and query patterns.
98
+
99
+ ### B. MemberJunction Repository Specifications
100
+ If you have access to the repository (or view them on GitHub at `https://github.com/MemberJunction/MJ/blob/next/`):
101
+ * [`metadata/CLAUDE.md`](https://github.com/MemberJunction/MJ/blob/next/metadata/CLAUDE.md): **The Definitive Metadata Specification**. Rules on `@lookup`, `@file`, `@parent`, native nested JSON objects, and `mj sync push` mechanics.
102
+ * [`packages/Actions/CLAUDE.md`](https://github.com/MemberJunction/MJ/blob/next/packages/Actions/CLAUDE.md): Action authoring conventions and parameter schemas.
103
+ * [`packages/AI/README.md`](https://github.com/MemberJunction/MJ/blob/next/packages/AI/README.md): AI Agent execution engine, state machines, and task graph dispatcher.
104
+
105
+ ---
106
+
107
+ ## 3. Step-by-Step Execution Guide for Coding Agents
108
+
109
+ ### Step 1: Initialize & Start the Environment
110
+
111
+ 1. **Verify Docker Status**:
112
+ Run `docker info` in the terminal.
113
+ * If running: proceed.
114
+ * If on macOS and Docker Desktop is stopped, run `open -a Docker` and wait 15–20 seconds for the daemon to start.
115
+ * If Docker is not installed, provide your user with the installation link: `https://www.docker.com/products/docker-desktop` (or `brew install --cask docker`).
116
+
117
+ 2. **Configure Environment Variables**:
118
+ If `.env` does not exist, copy `.env.example` to `.env`:
119
+ ```bash
120
+ cp .env.example .env
121
+ ```
122
+ Ask the user to supply their LLM API key (e.g. `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GEMINI_API_KEY`) and set it in `.env`.
123
+
124
+ 3. **Start the Stack**:
125
+ Run:
126
+ ```bash
127
+ docker compose up -d
128
+ ```
129
+ *On first start, the container runs `mj install`, applies core migrations, installs the business context app (More Cheese), and launches both MJAPI and MJExplorer.*
130
+ Monitor startup until ready:
131
+ ```bash
132
+ docker compose logs -f mj
133
+ ```
134
+ Once the banner appears:
135
+ * **MJAPI is live at**: `http://localhost:4000`
136
+ * **MJExplorer is live at**: `http://localhost:4202`
137
+
138
+ ---
139
+
140
+ ### Step 2: Understand the 3-Tier Boundary & Guardrails
141
+
142
+ Always enforce these constraints when authoring agents:
143
+
144
+ | Tier | Classification | What You May Author | Human Approval Needed? |
145
+ |---|---|---|---|
146
+ | **Tier 1** | **Declarative Only** | Flows, Loops, prompts, step mappings, action bindings, and sub-agent composition. | No — auto-promotable |
147
+ | **Tier 2** | **Runtime Code** | Sandboxed JavaScript **Runtime Actions** with explicit permission scopes. | Yes — admin code review |
148
+ | **Tier 3** | **Schema Changes** | New database tables, columns, migrations, or entity CodeGen. | **Strictly Off-Limits** |
149
+
150
+ #### Mandatory Defaults:
151
+ 1. **`ModelSelectionMode: "Agent Type"`**: Never hardcode specific provider models (`gpt-4o`, `claude-3-5-sonnet`). The destination environment maps models to Agent Types.
152
+ 2. **`ExposeAsAction: false`**: Do not set `true` unless the user explicitly wants other agents to call this agent as an action.
153
+ 3. **Dynamic Record Resolution**: Never hardcode record IDs or personal names. Use queries, parameters, or lookup actions.
154
+ 4. **Prefer `Flow` Agents**: Use `Flow` agents for predictable step-by-step tasks. Use `Loop` only for dynamic problem-solving with open-ended tool calling.
155
+
156
+ ---
157
+
158
+ ### Step 3: The Authoring Loop
159
+
160
+ 1. **Check Available Tools & Entities**:
161
+ Review `CAPABILITIES.md` (or run `./scripts/generate-capabilities.sh` to update it). This file contains the exact entity names, fields, and available actions in the running instance.
162
+
163
+ 2. **Metadata Formatting Rules (CRITICAL)**:
164
+ * **Native JSON Objects**: Fields storing JSON (such as `Configuration` or `Settings`) **MUST** be written as clean, native nested JSON objects. **NEVER** write escaped JSON strings (`"Configuration": "{\"Steps\":...}"`), as this breaks `@lookup` reference resolution!
165
+ * **No `sync` Blocks**: Do not author `sync` blocks (`lastModified`, `checksum`). `mj sync push` manages these automatically.
166
+ * **Assign Deterministic UUIDs**: Assign a fresh uppercase UUID for `primaryKey` (e.g. via CLI `uuidgen | tr '[:lower:]' '[:upper:]'`).
167
+ * **Use Dynamic References**:
168
+ - `@lookup:<EntityName>.<FieldName>=<Value>` for foreign keys (e.g. `@lookup:MJ: AI Agent Types.Name=Flow`).
169
+ - `@file:<relativePath>` for external template files (e.g. `@file:templates/<slug>.template.md`). Note that `@file:` paths are resolved at push time; running `./scripts/sync-metadata.sh` updates the database.
170
+ - `@parent:ID` for linking child records to parent records in nested structures.
171
+
172
+ 3. **Author Files**:
173
+ * Prompt Markdown template: `metadata/prompts/templates/<slug>.template.md`
174
+ * Prompt metadata JSON: `metadata/prompts/.<slug>-prompt.json`
175
+ * Agent metadata JSON: `metadata/agents/.<slug>-agent.json`
176
+ *(See `metadata/agents/.customer-insight-agent.json` for a reference Flow agent).*
177
+
178
+ 4. **Push to Local Database**:
179
+ ```bash
180
+ ./scripts/sync-metadata.sh
181
+ ```
182
+
183
+ ---
184
+
185
+ ### Step 4: Testing & Autonomous Diagnostics (The Dual Loop)
186
+
187
+ 1. **Interactive Testing (Explorer UI)**:
188
+ Invite the user to test in their browser at `http://localhost:4202`.
189
+
190
+ 2. **Headless Execution**:
191
+ You can trigger test runs directly via CLI with structured output:
192
+ ```bash
193
+ docker compose exec -T mj mj ai agents run -a "<Agent Name>" -p "<Test Input>" --format json
194
+ ```
195
+
196
+ 3. **Diagnosing Errors & Auditing Execution Traces**:
197
+ When an agent runs, **do not ask the user for console logs**. Audit execution traces directly via native CLI:
198
+ ```bash
199
+ # List recent runs for this agent
200
+ ./scripts/query-run-history.sh "<Agent Name>"
201
+
202
+ # View full machine-readable JSON trace for a specific run ID
203
+ ./scripts/query-run-history.sh <RunID> --format json
204
+
205
+ # Or drill down into specific steps or errors
206
+ ./scripts/query-run-history.sh <RunID> --step 1 --detail full
207
+ ./scripts/query-run-history.sh <RunID> --errors
208
+ ```
209
+
210
+ **Trace Verification Assertions**:
211
+ * Verify that `actionsUsed` matches expected actions and tools.
212
+ * Verify that `actionsNotUsed` contains sensitive or dangerous actions.
213
+ * Check step prompts, outputs, and token counts to spot prompt drift or infinite loops.
214
+
215
+ Analyze the trace, refine your prompt template or mapping, run `./scripts/sync-metadata.sh`, and re-test.
216
+
217
+ ---
218
+
219
+ ### Step 5: Packaging for Promotion
220
+
221
+ When the user is satisfied, package the agent for promotion to staging or production:
222
+
223
+ 1. Validate that all Tier 1 guardrails are met (no secrets, no hardcoded IDs, `ModelSelectionMode: "Agent Type"`).
224
+ 2. Query the last successful run metrics using `./scripts/query-run-history.sh "<Agent Name>"`.
225
+ 3. Generate `AGENT_MANIFEST.md` detailing:
226
+ * Agent Name, Purpose, and Author.
227
+ * Tier Classification (Tier 1 vs Tier 2).
228
+ * Data Footprint (Entities Read vs Entities Written).
229
+ * Bound Tools and Actions.
230
+ * Sample Execution Trace Receipt.
231
+ 4. Create the distribution archive:
232
+ ```bash
233
+ mkdir -p dist
234
+ zip -r "dist/<agent-slug>-package.zip" \
235
+ AGENT_MANIFEST.md \
236
+ metadata/agents/.*"<agent-slug>"*.json \
237
+ metadata/prompts/.*"<agent-slug>"*.json \
238
+ metadata/prompts/templates/"<agent-slug>"*.md
239
+ ```
240
+ 5. Give the user the path to `dist/<agent-slug>-package.zip` and explain how their platform admin can review and deploy it (see `docs/PROMOTION_GUIDE.md`).
241
+
242
+ ---
243
+
244
+ ## 4. Enterprise Organization Setup (e.g. Blue Cypress)
245
+
246
+ By default, the builder runs against **More Cheese** (a rich synthetic dataset covering 9 business apps).
247
+
248
+ To build agents against your organization's **real schemas and synthetic records** (e.g. **Blue Cypress / BC**):
249
+ 1. In `.env`, set:
250
+ ```bash
251
+ OPEN_APP_INSTALL_URL=https://github.com/BlueCypress/bc-sampledata
252
+ GITHUB_TOKEN=ghp_yourReadOnlyTokenHere
253
+ ```
254
+ 2. Restart the container:
255
+ ```bash
256
+ docker compose down -v && docker compose up -d
257
+ ```
258
+ 3. Run `./scripts/generate-capabilities.sh` to refresh `CAPABILITIES.md` with your organization's custom entities and actions.
259
+ 👉 For complete enterprise details, see [docs/ENTERPRISE_ORG_SETUP.md](docs/ENTERPRISE_ORG_SETUP.md).
@@ -0,0 +1,16 @@
1
+ FROM node:24-bullseye
2
+
3
+ # Install essential native build dependencies and git
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ git \
6
+ curl \
7
+ build-essential \
8
+ procps \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Install MemberJunction CLI and process manager globally
12
+ RUN npm install -g @memberjunction/cli pm2 pnpm
13
+
14
+ WORKDIR /workspace
15
+
16
+ EXPOSE 4000 4200
@@ -0,0 +1,59 @@
1
+ name: mj-citizen-builder
2
+
3
+ services:
4
+ sqlserver:
5
+ image: mcr.microsoft.com/mssql/server:2022-latest
6
+ platform: linux/amd64
7
+ restart: unless-stopped
8
+ environment:
9
+ ACCEPT_EULA: "Y"
10
+ MSSQL_SA_PASSWORD: "${DB_PASSWORD:-TestPassword123!}"
11
+ ports:
12
+ - "${DB_PORT:-1433}:1433"
13
+ healthcheck:
14
+ test: /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "$$MSSQL_SA_PASSWORD" -Q "SELECT 1" -C -No
15
+ interval: 10s
16
+ timeout: 5s
17
+ retries: 15
18
+ start_period: 20s
19
+ volumes:
20
+ - sqlserver-data:/var/opt/mssql
21
+
22
+ mj:
23
+ build:
24
+ context: .
25
+ dockerfile: docker/Dockerfile
26
+ platform: linux/amd64
27
+ restart: unless-stopped
28
+ depends_on:
29
+ sqlserver:
30
+ condition: service_healthy
31
+ ports:
32
+ - "${API_PORT:-4000}:4000"
33
+ - "${EXPLORER_PORT:-4202}:4200"
34
+ environment:
35
+ DB_HOST: "sqlserver"
36
+ DB_PORT: "1433"
37
+ DB_USERNAME: "sa"
38
+ DB_PASSWORD: "${DB_PASSWORD:-TestPassword123!}"
39
+ DB_DATABASE: "${DB_DATABASE:-MemberJunction}"
40
+ MJ_BASE_ENCRYPTION_KEY: "${MJ_BASE_ENCRYPTION_KEY:-0123456789abcdef0123456789abcdef}"
41
+ # LLM Provider API Keys
42
+ AI_VENDOR_API_KEY__OpenAILLM: "${OPENAI_API_KEY:-}"
43
+ AI_VENDOR_API_KEY__AnthropicLLM: "${ANTHROPIC_API_KEY:-}"
44
+ AI_VENDOR_API_KEY__GeminiLLM: "${GEMINI_API_KEY:-}"
45
+ AI_VENDOR_API_KEY__GroqLLM: "${GROQ_API_KEY:-}"
46
+ AI_VENDOR_API_KEY__MistralLLM: "${MISTRAL_API_KEY:-}"
47
+ # Business Context Open App (More Cheese default or custom enterprise app)
48
+ OPEN_APP_INSTALL_URL: "${OPEN_APP_INSTALL_URL:-https://github.com/MemberJunction/more-cheese}"
49
+ GITHUB_TOKEN: "${GITHUB_TOKEN:-}"
50
+ volumes:
51
+ - mj-workspace:/workspace
52
+ - ./metadata:/work/metadata
53
+ - ./scripts:/work/scripts
54
+ - ./dist:/work/dist
55
+ entrypoint: ["/bin/bash", "/work/scripts/docker-entrypoint.sh"]
56
+
57
+ volumes:
58
+ sqlserver-data:
59
+ mj-workspace: