@answerlayer/cli 0.1.9 → 0.1.10
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 +26 -2
- package/package.json +1 -1
- package/skills/answerlayer/SKILL.md +23 -5
- package/src/cli.js +5 -2
- package/src/local.js +350 -8
package/README.md
CHANGED
|
@@ -115,8 +115,9 @@ to change the local port. The CLI:
|
|
|
115
115
|
4. Starts Postgres, runs migrations, and waits for AnswerLayer readiness.
|
|
116
116
|
5. Creates a local-only organization and scoped key, verifies the key, and
|
|
117
117
|
saves the CLI configuration without printing the key.
|
|
118
|
-
6.
|
|
119
|
-
|
|
118
|
+
6. Seeds a versioned synthetic retail demo in a separate Postgres database,
|
|
119
|
+
registers its dedicated read-only connection, creates starter semantic
|
|
120
|
+
objects and a saved query, and verifies a deterministic result.
|
|
120
121
|
|
|
121
122
|
The local stack does not require a hosted AnswerLayer account, a source checkout,
|
|
122
123
|
private registry credentials, or a model-provider key for first boot. Add an
|
|
@@ -125,6 +126,28 @@ The skill requires agent confirmation before it starts containers, creates a
|
|
|
125
126
|
connection, or sends queries to a real database, and it instructs agents not to
|
|
126
127
|
print or persist database passwords.
|
|
127
128
|
|
|
129
|
+
The demo is installed by default. Use `answerlayer local start --no-demo` to
|
|
130
|
+
skip it, or install/verify it later with:
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
answerlayer local demo
|
|
134
|
+
answerlayer local demo --json
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`local demo --json` returns the demo version, connection ID, saved-query ID,
|
|
138
|
+
semantic-resource IDs, the verified result, and suggested natural-language
|
|
139
|
+
questions without returning credentials. The saved query works before a model
|
|
140
|
+
provider is configured:
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
answerlayer saved-queries execute <saved-query-id> --format table
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Natural-language inquiry still requires provider configuration. Re-running the
|
|
147
|
+
demo command reuses the same connection and semantic resources rather than
|
|
148
|
+
duplicating them. `local reset --force` explicitly removes both application and
|
|
149
|
+
demo data because they share the selected runtime's isolated Postgres volume.
|
|
150
|
+
|
|
128
151
|
Inspect and manage the lifecycle with:
|
|
129
152
|
|
|
130
153
|
```bash
|
|
@@ -160,6 +183,7 @@ answerlayer health
|
|
|
160
183
|
answerlayer openapi --output openapi.json
|
|
161
184
|
answerlayer local init
|
|
162
185
|
answerlayer local start
|
|
186
|
+
answerlayer local demo --json
|
|
163
187
|
answerlayer local status
|
|
164
188
|
answerlayer local logs
|
|
165
189
|
answerlayer local stop
|
package/package.json
CHANGED
|
@@ -48,18 +48,36 @@ already available in the Codex skills directory.
|
|
|
48
48
|
```
|
|
49
49
|
|
|
50
50
|
This starts Postgres, runs migrations, waits for readiness, creates the local
|
|
51
|
-
identity and scoped key, verifies it, and configures the CLI. It
|
|
52
|
-
|
|
51
|
+
identity and scoped key, verifies it, and configures the CLI. It also seeds a
|
|
52
|
+
versioned synthetic retail demo in a separate database, registers a
|
|
53
|
+
dedicated read-only connection, creates starter semantic resources and a
|
|
54
|
+
saved query, and verifies a deterministic result. It captures generated
|
|
55
|
+
credentials rather than printing them. Use `answerlayer local status` and
|
|
53
56
|
`answerlayer local logs` to inspect progress. `local stop` preserves data;
|
|
54
|
-
`local reset --force` is the explicit destructive reset.
|
|
57
|
+
`local reset --force` is the explicit destructive reset. Use `--no-demo`
|
|
58
|
+
only when the user explicitly wants an empty instance.
|
|
55
59
|
|
|
56
|
-
4.
|
|
60
|
+
4. Inspect the machine-readable demo handoff:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
answerlayer local demo --json
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Report the demo version, connection, verified result, and suggested next
|
|
67
|
+
action. Do not attempt a natural-language inquiry until a model provider is
|
|
68
|
+
configured. The demo saved query can be executed without a provider:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
answerlayer saved-queries execute <saved-query-id> --format table
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
5. Before connecting real data, require a dedicated database account that is
|
|
57
75
|
restricted to approved schemas and `SELECT` only. Show the proposed
|
|
58
76
|
connection host, database, and username, then get confirmation before
|
|
59
77
|
running `connections create` or any query. Put the password only in a local,
|
|
60
78
|
permission-restricted JSON file; never print it or commit it.
|
|
61
79
|
|
|
62
|
-
|
|
80
|
+
6. Start with a small approved schema and read-only inspection. Confirm before
|
|
63
81
|
creating connections, generating semantic objects, or executing queries.
|
|
64
82
|
|
|
65
83
|
This workflow is for Docker Compose development only. Do not run
|
package/src/cli.js
CHANGED
|
@@ -1438,6 +1438,7 @@ function normalizeFlagName(rawName) {
|
|
|
1438
1438
|
"--model": "model",
|
|
1439
1439
|
"--use-semantic-layer": "useSemanticLayer",
|
|
1440
1440
|
"--no-semantic-layer": "noSemanticLayer",
|
|
1441
|
+
"--no-demo": "noDemo",
|
|
1441
1442
|
"--options": "options",
|
|
1442
1443
|
"--status": "status",
|
|
1443
1444
|
"--summary": "summary",
|
|
@@ -1476,7 +1477,7 @@ function normalizeFlagName(rawName) {
|
|
|
1476
1477
|
}
|
|
1477
1478
|
|
|
1478
1479
|
function isBooleanFlag(rawName) {
|
|
1479
|
-
return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--follow", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot", "--use-semantic-layer", "--no-semantic-layer"].includes(rawName);
|
|
1480
|
+
return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--follow", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot", "--use-semantic-layer", "--no-semantic-layer", "--no-demo"].includes(rawName);
|
|
1480
1481
|
}
|
|
1481
1482
|
|
|
1482
1483
|
function setFlag(flags, name, value) {
|
|
@@ -1614,7 +1615,9 @@ function helpText() {
|
|
|
1614
1615
|
Usage:
|
|
1615
1616
|
answerlayer skills install [--path <directory>] [--force]
|
|
1616
1617
|
answerlayer local init [--image <image>] [--port <port>]
|
|
1617
|
-
answerlayer local start
|
|
1618
|
+
answerlayer local start [--no-demo]
|
|
1619
|
+
answerlayer local status|logs|stop
|
|
1620
|
+
answerlayer local demo [--json]
|
|
1618
1621
|
answerlayer local upgrade [--image <image>]
|
|
1619
1622
|
answerlayer local reset --force
|
|
1620
1623
|
answerlayer init --api-key <key> [--base-url <url>]
|
package/src/local.js
CHANGED
|
@@ -10,6 +10,16 @@ import { defaultConfigPath, readConfig, writeConfig } from "./config.js";
|
|
|
10
10
|
export const DEFAULT_LOCAL_IMAGE = "public.ecr.aws/s8d9x7y7/answerlayer:1.19.9";
|
|
11
11
|
const DEFAULT_PORT = 8000;
|
|
12
12
|
const MINIMUM_FREE_BYTES = 2 * 1024 * 1024 * 1024;
|
|
13
|
+
const LOCAL_DEMO_VERSION = "retail-v1";
|
|
14
|
+
const LOCAL_DEMO_CONNECTION_NAME = "AnswerLayer Demo";
|
|
15
|
+
const LOCAL_DEMO_SAVED_QUERY_NAME = "Monthly revenue by region";
|
|
16
|
+
const LOCAL_DEMO_DATABASE = "answerlayer_demo";
|
|
17
|
+
const LOCAL_DEMO_USER = "answerlayer_demo_reader";
|
|
18
|
+
const LOCAL_DEMO_QUESTIONS = [
|
|
19
|
+
"How much completed revenue did we generate each month?",
|
|
20
|
+
"Which region generated the most completed revenue?",
|
|
21
|
+
"How did completed revenue change from January to March?",
|
|
22
|
+
];
|
|
13
23
|
|
|
14
24
|
export async function handleLocal(command, parsed, io) {
|
|
15
25
|
if (command === "init") return localInit(parsed, io);
|
|
@@ -17,9 +27,10 @@ export async function handleLocal(command, parsed, io) {
|
|
|
17
27
|
if (command === "status") return localStatus(parsed, io);
|
|
18
28
|
if (command === "logs") return localLogs(parsed, io);
|
|
19
29
|
if (command === "stop") return localStop(parsed, io);
|
|
30
|
+
if (command === "demo") return localDemo(parsed, io);
|
|
20
31
|
if (command === "upgrade") return localUpgrade(parsed, io);
|
|
21
32
|
if (command === "reset") return localReset(parsed, io);
|
|
22
|
-
throw new Error("Expected `answerlayer local init|start|status|logs|stop|upgrade|reset`");
|
|
33
|
+
throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|upgrade|reset`");
|
|
23
34
|
}
|
|
24
35
|
|
|
25
36
|
export async function localUp(parsed, io) {
|
|
@@ -57,12 +68,46 @@ async function localStart(parsed, io) {
|
|
|
57
68
|
const baseUrl = `http://127.0.0.1:${runtime.state.port}`;
|
|
58
69
|
await waitUntilReady(baseUrl, io);
|
|
59
70
|
const configPath = await ensureLocalCredentials(runtime, baseUrl, io);
|
|
60
|
-
const
|
|
71
|
+
const demo = parsed.flags.noDemo
|
|
72
|
+
? { status: "skipped", version: LOCAL_DEMO_VERSION }
|
|
73
|
+
: await ensureLocalDemo(runtime, baseUrl, io);
|
|
74
|
+
const state = { ...runtime.state, demo, lastStatus: "ready", updatedAt: new Date().toISOString() };
|
|
61
75
|
writeState(runtime.statePath, state);
|
|
62
76
|
|
|
63
77
|
printRuntimeSummary({ ...runtime, state }, io, "Local AnswerLayer is ready.");
|
|
64
78
|
write(io.stdout, `CLI config: ${configPath}\n`);
|
|
65
|
-
|
|
79
|
+
if (demo.status === "ready") {
|
|
80
|
+
printDemoSummary(demo, io);
|
|
81
|
+
} else {
|
|
82
|
+
write(io.stdout, "Demo: skipped (--no-demo)\n");
|
|
83
|
+
write(io.stdout, "Install it later with: answerlayer local demo\n");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function localDemo(parsed, io) {
|
|
88
|
+
const run = io.runCommand || runCommand;
|
|
89
|
+
const runtime = loadRuntime(parsed, io);
|
|
90
|
+
requireCommand(run, "docker", ["compose", "version"]);
|
|
91
|
+
const status = inspectStatus(runtime, run, { tolerateFailure: true });
|
|
92
|
+
if (status.status !== "ready") {
|
|
93
|
+
throw new Error("Local AnswerLayer must be ready before installing the demo. Run `answerlayer local start` first.");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const baseUrl = `http://127.0.0.1:${runtime.state.port}`;
|
|
97
|
+
await ensureLocalCredentials(runtime, baseUrl, io, { quiet: Boolean(parsed.flags.json) });
|
|
98
|
+
const demo = await ensureLocalDemo(runtime, baseUrl, io, { quiet: Boolean(parsed.flags.json) });
|
|
99
|
+
writeState(runtime.statePath, {
|
|
100
|
+
...runtime.state,
|
|
101
|
+
demo,
|
|
102
|
+
lastStatus: "ready",
|
|
103
|
+
updatedAt: new Date().toISOString(),
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
if (parsed.flags.json) {
|
|
107
|
+
write(io.stdout, `${JSON.stringify(demo, null, 2)}\n`);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
printDemoSummary(demo, io);
|
|
66
111
|
}
|
|
67
112
|
|
|
68
113
|
async function localUpgrade(parsed, io) {
|
|
@@ -82,6 +127,7 @@ async function localStatus(parsed, io) {
|
|
|
82
127
|
image: runtime.state.requestedImage,
|
|
83
128
|
resolvedImage: runtime.state.resolvedImage,
|
|
84
129
|
runtimeDirectory: runtime.directory,
|
|
130
|
+
demo: runtime.state.demo || { status: "not-installed", version: LOCAL_DEMO_VERSION },
|
|
85
131
|
services: status.services,
|
|
86
132
|
};
|
|
87
133
|
|
|
@@ -93,6 +139,7 @@ async function localStatus(parsed, io) {
|
|
|
93
139
|
write(io.stdout, `URL: ${result.url}\n`);
|
|
94
140
|
write(io.stdout, `Image: ${result.resolvedImage}\n`);
|
|
95
141
|
write(io.stdout, `Runtime config: ${result.runtimeDirectory}\n`);
|
|
142
|
+
write(io.stdout, `Demo: ${result.demo.status} (${result.demo.version})\n`);
|
|
96
143
|
}
|
|
97
144
|
|
|
98
145
|
async function localLogs(parsed, io) {
|
|
@@ -127,7 +174,12 @@ async function localReset(parsed, io) {
|
|
|
127
174
|
const runtime = loadRuntime(parsed, io);
|
|
128
175
|
requireCommand(run, "docker", ["compose", "version"]);
|
|
129
176
|
checked(run, "docker", [...composeArgs(runtime), "down", "--volumes", "--remove-orphans"], { passthrough: true });
|
|
130
|
-
writeState(runtime.statePath, {
|
|
177
|
+
writeState(runtime.statePath, {
|
|
178
|
+
...runtime.state,
|
|
179
|
+
demo: { status: "not-installed", version: LOCAL_DEMO_VERSION },
|
|
180
|
+
lastStatus: "stopped",
|
|
181
|
+
resetAt: new Date().toISOString(),
|
|
182
|
+
});
|
|
131
183
|
write(io.stdout, "Deleted the local AnswerLayer database volume. Runtime configuration was preserved.\n");
|
|
132
184
|
write(io.stdout, "Create a fresh database with: answerlayer local start\n");
|
|
133
185
|
}
|
|
@@ -165,6 +217,7 @@ async function ensureInitialized(parsed, io) {
|
|
|
165
217
|
requestedImage,
|
|
166
218
|
resolvedImage,
|
|
167
219
|
port,
|
|
220
|
+
...(existingState?.demo ? { demo: existingState.demo } : {}),
|
|
168
221
|
...runtimeResourceNames(runtime.directory),
|
|
169
222
|
createdAt: existingState?.createdAt || new Date().toISOString(),
|
|
170
223
|
updatedAt: new Date().toISOString(),
|
|
@@ -232,7 +285,7 @@ function imageRepository(image) {
|
|
|
232
285
|
return colon > slash ? withoutDigest.slice(0, colon) : withoutDigest;
|
|
233
286
|
}
|
|
234
287
|
|
|
235
|
-
async function ensureLocalCredentials(runtime, baseUrl, io) {
|
|
288
|
+
async function ensureLocalCredentials(runtime, baseUrl, io, options = {}) {
|
|
236
289
|
const existing = readConfig(io.env);
|
|
237
290
|
const fetchImpl = io.fetch || globalThis.fetch;
|
|
238
291
|
if (existing.baseUrl === baseUrl && existing.apiKey) {
|
|
@@ -245,7 +298,9 @@ async function ensureLocalCredentials(runtime, baseUrl, io) {
|
|
|
245
298
|
}
|
|
246
299
|
}
|
|
247
300
|
|
|
248
|
-
|
|
301
|
+
if (!options.quiet) {
|
|
302
|
+
write(io.stdout, "Creating a local-only CLI identity...\n");
|
|
303
|
+
}
|
|
249
304
|
const run = io.runCommand || runCommand;
|
|
250
305
|
let bootstrap;
|
|
251
306
|
try {
|
|
@@ -355,6 +410,7 @@ function writeEnvironment(envPath, state) {
|
|
|
355
410
|
ANSWERLAYER_IMAGE: state.resolvedImage,
|
|
356
411
|
ANSWERLAYER_POSTGRES_PASSWORD: existing.ANSWERLAYER_POSTGRES_PASSWORD || crypto.randomBytes(24).toString("hex"),
|
|
357
412
|
ANSWERLAYER_ENCRYPTION_KEY: existing.ANSWERLAYER_ENCRYPTION_KEY || crypto.randomBytes(32).toString("hex"),
|
|
413
|
+
ANSWERLAYER_DEMO_PASSWORD: existing.ANSWERLAYER_DEMO_PASSWORD || crypto.randomBytes(24).toString("hex"),
|
|
358
414
|
ANSWERLAYER_PORT: String(state.port),
|
|
359
415
|
ANSWERLAYER_LOG_LEVEL: existing.ANSWERLAYER_LOG_LEVEL || "INFO",
|
|
360
416
|
ANSWERLAYER_WEB_CONCURRENCY: existing.ANSWERLAYER_WEB_CONCURRENCY || "1",
|
|
@@ -447,7 +503,7 @@ function requireCommand(run, command, args) {
|
|
|
447
503
|
}
|
|
448
504
|
|
|
449
505
|
function checked(run, command, args, options = {}) {
|
|
450
|
-
const result = run(command, args, { capture: !options.passthrough });
|
|
506
|
+
const result = run(command, args, { capture: !options.passthrough, input: options.input });
|
|
451
507
|
if (result.error) throw result.error;
|
|
452
508
|
if (result.status !== 0) {
|
|
453
509
|
const detail = String(result.stderr || result.stdout || "").trim();
|
|
@@ -459,7 +515,10 @@ function checked(run, command, args, options = {}) {
|
|
|
459
515
|
function runCommand(command, args, options = {}) {
|
|
460
516
|
return spawnSync(command, args, {
|
|
461
517
|
encoding: options.capture ? "utf8" : undefined,
|
|
462
|
-
|
|
518
|
+
input: options.input,
|
|
519
|
+
stdio: options.capture
|
|
520
|
+
? [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
|
|
521
|
+
: "inherit",
|
|
463
522
|
maxBuffer: 50 * 1024 * 1024,
|
|
464
523
|
});
|
|
465
524
|
}
|
|
@@ -472,6 +531,289 @@ function printRuntimeSummary(runtime, io, heading) {
|
|
|
472
531
|
write(io.stdout, `Runtime config: ${runtime.directory}\n`);
|
|
473
532
|
}
|
|
474
533
|
|
|
534
|
+
function printDemoSummary(demo, io) {
|
|
535
|
+
write(io.stdout, `Demo: ready (${demo.version})\n`);
|
|
536
|
+
write(io.stdout, `Demo connection: ${demo.connectionId}\n`);
|
|
537
|
+
write(io.stdout, `Verified result: ${demo.validation.completedOrderCount} completed orders, $${demo.validation.totalRevenue} revenue\n`);
|
|
538
|
+
write(io.stdout, `Try now: answerlayer saved-queries execute ${demo.savedQueryId} --format table\n`);
|
|
539
|
+
write(io.stdout, `After configuring a model provider, ask: answerlayer inquiry ask --connection ${demo.connectionId} "${demo.questions[0]}"\n`);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
async function ensureLocalDemo(runtime, baseUrl, io, options = {}) {
|
|
543
|
+
const environment = readEnvironment(runtime.envPath);
|
|
544
|
+
const demoPassword = environment.ANSWERLAYER_DEMO_PASSWORD;
|
|
545
|
+
if (!demoPassword || !/^[a-f0-9]{48}$/.test(demoPassword)) {
|
|
546
|
+
throw new Error("The local demo password is missing or invalid. Run `answerlayer local init` to repair runtime configuration.");
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const run = io.runCommand || runCommand;
|
|
550
|
+
if (!options.quiet) {
|
|
551
|
+
write(io.stdout, `Preparing deterministic demo data (${LOCAL_DEMO_VERSION})...\n`);
|
|
552
|
+
}
|
|
553
|
+
checked(run, "docker", [
|
|
554
|
+
...composeArgs(runtime),
|
|
555
|
+
"exec", "-T", "postgres", "psql",
|
|
556
|
+
"--set", "ON_ERROR_STOP=1",
|
|
557
|
+
"--username", "answerlayer",
|
|
558
|
+
"--dbname", "postgres",
|
|
559
|
+
], { input: demoSeedSql(demoPassword) });
|
|
560
|
+
|
|
561
|
+
const config = readConfig(io.env);
|
|
562
|
+
if (config.baseUrl !== baseUrl || !config.apiKey) {
|
|
563
|
+
throw new Error("Local CLI credentials are not configured. Run `answerlayer local start` first.");
|
|
564
|
+
}
|
|
565
|
+
const client = new AnswerLayerClient({ baseUrl, apiKey: config.apiKey, fetchImpl: io.fetch || globalThis.fetch });
|
|
566
|
+
|
|
567
|
+
const connection = await ensureDemoConnection(client, demoPassword);
|
|
568
|
+
const connectionId = String(connection.id);
|
|
569
|
+
const entities = [
|
|
570
|
+
await ensureSemanticResource(client, "entities", connectionId, "Orders", {
|
|
571
|
+
name: "Orders",
|
|
572
|
+
source_table: "demo.orders",
|
|
573
|
+
identifier: "id",
|
|
574
|
+
temporal_key: "order_date",
|
|
575
|
+
description: "Completed and refunded retail orders in the AnswerLayer onboarding demo.",
|
|
576
|
+
}),
|
|
577
|
+
await ensureSemanticResource(client, "entities", connectionId, "Customers", {
|
|
578
|
+
name: "Customers",
|
|
579
|
+
source_table: "demo.customers",
|
|
580
|
+
identifier: "id",
|
|
581
|
+
description: "Synthetic customers grouped by region and business segment.",
|
|
582
|
+
}),
|
|
583
|
+
];
|
|
584
|
+
const relationship = await ensureSemanticResource(client, "relationships", connectionId, "Orders to Customers", {
|
|
585
|
+
name: "Orders to Customers",
|
|
586
|
+
description: "Each order belongs to one customer.",
|
|
587
|
+
from_entity: "Orders",
|
|
588
|
+
to_entity: "Customers",
|
|
589
|
+
join_keys: { from: "customer_id", to: "id" },
|
|
590
|
+
cardinality: "many_to_one",
|
|
591
|
+
});
|
|
592
|
+
const dimensions = [
|
|
593
|
+
await ensureSemanticResource(client, "dimensions", connectionId, "Order date", {
|
|
594
|
+
name: "Order date",
|
|
595
|
+
entity: "Orders",
|
|
596
|
+
expression: "order_date",
|
|
597
|
+
description: "Calendar date on which the order was placed.",
|
|
598
|
+
}),
|
|
599
|
+
await ensureSemanticResource(client, "dimensions", connectionId, "Customer region", {
|
|
600
|
+
name: "Customer region",
|
|
601
|
+
entity: "Customers",
|
|
602
|
+
expression: "region",
|
|
603
|
+
description: "North, South, East, or West sales region.",
|
|
604
|
+
}),
|
|
605
|
+
];
|
|
606
|
+
const measure = await ensureSemanticResource(client, "measures", connectionId, "Revenue", {
|
|
607
|
+
name: "Revenue",
|
|
608
|
+
entity: "Orders",
|
|
609
|
+
expression: "quantity * unit_price",
|
|
610
|
+
aggregation: "sum",
|
|
611
|
+
default_filters: [],
|
|
612
|
+
description: "Gross order value before refunds; use order status to select completed revenue.",
|
|
613
|
+
});
|
|
614
|
+
const savedQuery = await ensureDemoSavedQuery(client, connectionId);
|
|
615
|
+
const queryResult = await client.runQuery(connectionId, {
|
|
616
|
+
query: DEMO_VALIDATION_SQL,
|
|
617
|
+
row_limit: 1,
|
|
618
|
+
timeout: 30,
|
|
619
|
+
});
|
|
620
|
+
const completedOrderCount = Number(queryResult?.rows?.[0]?.[0]);
|
|
621
|
+
const totalRevenue = Number(queryResult?.rows?.[0]?.[1]);
|
|
622
|
+
if (completedOrderCount !== 11 || totalRevenue !== 12200) {
|
|
623
|
+
throw new Error(
|
|
624
|
+
`Demo verification returned an unexpected result (${completedOrderCount} orders, ${totalRevenue} revenue). Run \`answerlayer local demo\` to retry.`,
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return {
|
|
629
|
+
status: "ready",
|
|
630
|
+
version: LOCAL_DEMO_VERSION,
|
|
631
|
+
connectionId,
|
|
632
|
+
savedQueryId: String(savedQuery.id),
|
|
633
|
+
semantic: {
|
|
634
|
+
entityIds: entities.map(item => String(item.id)),
|
|
635
|
+
relationshipId: String(relationship.id),
|
|
636
|
+
dimensionIds: dimensions.map(item => String(item.id)),
|
|
637
|
+
measureId: String(measure.id),
|
|
638
|
+
},
|
|
639
|
+
validation: {
|
|
640
|
+
completedOrderCount,
|
|
641
|
+
totalRevenue: totalRevenue.toFixed(2),
|
|
642
|
+
},
|
|
643
|
+
questions: LOCAL_DEMO_QUESTIONS,
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
async function ensureDemoConnection(client, demoPassword) {
|
|
648
|
+
const connections = await client.listConnections();
|
|
649
|
+
const existing = Array.isArray(connections)
|
|
650
|
+
? connections.find(item => item.name === LOCAL_DEMO_CONNECTION_NAME)
|
|
651
|
+
: null;
|
|
652
|
+
if (existing) {
|
|
653
|
+
if (existing.db_type !== "postgresql") {
|
|
654
|
+
throw new Error(`The reserved connection name "${LOCAL_DEMO_CONNECTION_NAME}" is already used by a non-PostgreSQL connection.`);
|
|
655
|
+
}
|
|
656
|
+
const config = existing.config || {};
|
|
657
|
+
const ownsDemoDatabase = config.pg_host === "postgres"
|
|
658
|
+
&& Number(config.pg_port) === 5432
|
|
659
|
+
&& config.db_name === LOCAL_DEMO_DATABASE
|
|
660
|
+
&& config.pg_username === LOCAL_DEMO_USER;
|
|
661
|
+
if (!ownsDemoDatabase) {
|
|
662
|
+
throw new Error(
|
|
663
|
+
`The reserved connection name "${LOCAL_DEMO_CONNECTION_NAME}" is already used by a different PostgreSQL database. Rename or remove that connection, then rerun \`answerlayer local demo\`.`,
|
|
664
|
+
);
|
|
665
|
+
}
|
|
666
|
+
return existing;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
return client.request("POST", "/api/v1/connections/", {
|
|
670
|
+
body: {
|
|
671
|
+
name: LOCAL_DEMO_CONNECTION_NAME,
|
|
672
|
+
description: `Versioned synthetic retail data for local onboarding (${LOCAL_DEMO_VERSION}).`,
|
|
673
|
+
db_type: "postgresql",
|
|
674
|
+
config: {
|
|
675
|
+
host: "postgres",
|
|
676
|
+
port: 5432,
|
|
677
|
+
database_name: LOCAL_DEMO_DATABASE,
|
|
678
|
+
username: LOCAL_DEMO_USER,
|
|
679
|
+
password: demoPassword,
|
|
680
|
+
},
|
|
681
|
+
auto_pii_detection: false,
|
|
682
|
+
},
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
async function ensureSemanticResource(client, resource, connectionId, name, payload) {
|
|
687
|
+
const pathName = `/api/v1/semantic/${resource}`;
|
|
688
|
+
const result = await client.request("GET", pathName, { query: { connection_id: connectionId } });
|
|
689
|
+
const items = Array.isArray(result?.[resource]) ? result[resource] : [];
|
|
690
|
+
const existing = items.find(item => item.name === name);
|
|
691
|
+
if (existing) return existing;
|
|
692
|
+
return client.request("POST", pathName, {
|
|
693
|
+
query: { connection_id: connectionId },
|
|
694
|
+
body: payload,
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async function ensureDemoSavedQuery(client, connectionId) {
|
|
699
|
+
const result = await client.listSavedQueries();
|
|
700
|
+
const items = Array.isArray(result?.saved_queries) ? result.saved_queries : [];
|
|
701
|
+
const existing = items.find(item => item.name === LOCAL_DEMO_SAVED_QUERY_NAME && String(item.connection_id) === connectionId);
|
|
702
|
+
if (existing) return existing;
|
|
703
|
+
return client.createSavedQuery({
|
|
704
|
+
name: LOCAL_DEMO_SAVED_QUERY_NAME,
|
|
705
|
+
description: "Completed order revenue grouped by month and customer region.",
|
|
706
|
+
visibility: "org",
|
|
707
|
+
sql: DEMO_SAVED_QUERY_SQL,
|
|
708
|
+
connection_id: connectionId,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function demoSeedSql(password) {
|
|
713
|
+
const passwordLiteral = `'${password.replaceAll("'", "''")}'`;
|
|
714
|
+
return `\\set ON_ERROR_STOP on
|
|
715
|
+
DO $role$
|
|
716
|
+
BEGIN
|
|
717
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${LOCAL_DEMO_USER}') THEN
|
|
718
|
+
CREATE ROLE ${LOCAL_DEMO_USER} LOGIN PASSWORD ${passwordLiteral};
|
|
719
|
+
ELSE
|
|
720
|
+
ALTER ROLE ${LOCAL_DEMO_USER} LOGIN PASSWORD ${passwordLiteral};
|
|
721
|
+
END IF;
|
|
722
|
+
END
|
|
723
|
+
$role$;
|
|
724
|
+
|
|
725
|
+
SELECT 'CREATE DATABASE ${LOCAL_DEMO_DATABASE} OWNER answerlayer'
|
|
726
|
+
WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = '${LOCAL_DEMO_DATABASE}')\\gexec
|
|
727
|
+
|
|
728
|
+
REVOKE ALL ON DATABASE ${LOCAL_DEMO_DATABASE} FROM PUBLIC;
|
|
729
|
+
GRANT CONNECT ON DATABASE ${LOCAL_DEMO_DATABASE} TO ${LOCAL_DEMO_USER};
|
|
730
|
+
|
|
731
|
+
\\connect ${LOCAL_DEMO_DATABASE}
|
|
732
|
+
|
|
733
|
+
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
|
734
|
+
CREATE SCHEMA IF NOT EXISTS demo AUTHORIZATION answerlayer;
|
|
735
|
+
REVOKE ALL ON SCHEMA demo FROM PUBLIC;
|
|
736
|
+
|
|
737
|
+
CREATE TABLE IF NOT EXISTS demo.bootstrap_versions (
|
|
738
|
+
version text PRIMARY KEY,
|
|
739
|
+
installed_at timestamptz NOT NULL DEFAULT now()
|
|
740
|
+
);
|
|
741
|
+
|
|
742
|
+
CREATE TABLE IF NOT EXISTS demo.customers (
|
|
743
|
+
id integer PRIMARY KEY,
|
|
744
|
+
name text NOT NULL,
|
|
745
|
+
region text NOT NULL,
|
|
746
|
+
segment text NOT NULL,
|
|
747
|
+
signup_date date NOT NULL
|
|
748
|
+
);
|
|
749
|
+
|
|
750
|
+
CREATE TABLE IF NOT EXISTS demo.orders (
|
|
751
|
+
id integer PRIMARY KEY,
|
|
752
|
+
customer_id integer NOT NULL REFERENCES demo.customers(id),
|
|
753
|
+
order_date date NOT NULL,
|
|
754
|
+
product text NOT NULL,
|
|
755
|
+
category text NOT NULL,
|
|
756
|
+
quantity integer NOT NULL CHECK (quantity > 0),
|
|
757
|
+
unit_price numeric(12, 2) NOT NULL CHECK (unit_price >= 0),
|
|
758
|
+
status text NOT NULL CHECK (status IN ('completed', 'refunded'))
|
|
759
|
+
);
|
|
760
|
+
|
|
761
|
+
DO $seed$
|
|
762
|
+
BEGIN
|
|
763
|
+
IF NOT EXISTS (SELECT 1 FROM demo.bootstrap_versions WHERE version = '${LOCAL_DEMO_VERSION}') THEN
|
|
764
|
+
DELETE FROM demo.orders;
|
|
765
|
+
DELETE FROM demo.customers;
|
|
766
|
+
INSERT INTO demo.customers (id, name, region, segment, signup_date) VALUES
|
|
767
|
+
(1, 'Maple & Co', 'North', 'SMB', '2025-10-12'),
|
|
768
|
+
(2, 'Harbour Goods', 'South', 'Mid-market', '2025-11-03'),
|
|
769
|
+
(3, 'Summit Systems', 'East', 'Enterprise', '2025-11-18'),
|
|
770
|
+
(4, 'Cedar Studio', 'West', 'SMB', '2025-12-01'),
|
|
771
|
+
(5, 'Northstar Labs', 'North', 'Enterprise', '2025-12-09'),
|
|
772
|
+
(6, 'Lakeside Market', 'South', 'SMB', '2025-12-21');
|
|
773
|
+
INSERT INTO demo.orders (id, customer_id, order_date, product, category, quantity, unit_price, status) VALUES
|
|
774
|
+
(1, 1, '2026-01-05', 'Analytics seats', 'Subscription', 10, 50.00, 'completed'),
|
|
775
|
+
(2, 2, '2026-01-08', 'Data connectors', 'Platform', 2, 900.00, 'completed'),
|
|
776
|
+
(3, 3, '2026-01-12', 'Analytics seats', 'Subscription', 25, 50.00, 'completed'),
|
|
777
|
+
(4, 4, '2026-01-20', 'Onboarding', 'Services', 1, 750.00, 'completed'),
|
|
778
|
+
(5, 1, '2026-02-02', 'Analytics seats', 'Subscription', 12, 50.00, 'completed'),
|
|
779
|
+
(6, 5, '2026-02-10', 'Data connectors', 'Platform', 3, 900.00, 'completed'),
|
|
780
|
+
(7, 6, '2026-02-14', 'Onboarding', 'Services', 1, 750.00, 'completed'),
|
|
781
|
+
(8, 3, '2026-02-22', 'Data connectors', 'Platform', 1, 900.00, 'refunded'),
|
|
782
|
+
(9, 2, '2026-03-03', 'Analytics seats', 'Subscription', 18, 50.00, 'completed'),
|
|
783
|
+
(10, 4, '2026-03-08', 'Data connectors', 'Platform', 2, 900.00, 'completed'),
|
|
784
|
+
(11, 5, '2026-03-15', 'Onboarding', 'Services', 1, 750.00, 'completed'),
|
|
785
|
+
(12, 6, '2026-03-25', 'Analytics seats', 'Subscription', 8, 50.00, 'completed');
|
|
786
|
+
INSERT INTO demo.bootstrap_versions (version) VALUES ('${LOCAL_DEMO_VERSION}');
|
|
787
|
+
END IF;
|
|
788
|
+
END
|
|
789
|
+
$seed$;
|
|
790
|
+
|
|
791
|
+
GRANT USAGE ON SCHEMA demo TO ${LOCAL_DEMO_USER};
|
|
792
|
+
GRANT SELECT ON ALL TABLES IN SCHEMA demo TO ${LOCAL_DEMO_USER};
|
|
793
|
+
ALTER DEFAULT PRIVILEGES IN SCHEMA demo GRANT SELECT ON TABLES TO ${LOCAL_DEMO_USER};
|
|
794
|
+
`;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
const DEMO_VALIDATION_SQL = `
|
|
798
|
+
SELECT
|
|
799
|
+
count(*)::integer AS completed_order_count,
|
|
800
|
+
round(sum(quantity * unit_price), 2) AS total_revenue
|
|
801
|
+
FROM demo.orders
|
|
802
|
+
WHERE status = 'completed'
|
|
803
|
+
`.trim();
|
|
804
|
+
|
|
805
|
+
const DEMO_SAVED_QUERY_SQL = `
|
|
806
|
+
SELECT
|
|
807
|
+
date_trunc('month', o.order_date)::date AS month,
|
|
808
|
+
c.region,
|
|
809
|
+
round(sum(o.quantity * o.unit_price), 2) AS revenue
|
|
810
|
+
FROM demo.orders AS o
|
|
811
|
+
JOIN demo.customers AS c ON c.id = o.customer_id
|
|
812
|
+
WHERE o.status = 'completed'
|
|
813
|
+
GROUP BY 1, 2
|
|
814
|
+
ORDER BY 1, 2
|
|
815
|
+
`.trim();
|
|
816
|
+
|
|
475
817
|
function firstValue(value) {
|
|
476
818
|
return Array.isArray(value) ? value[0] : value;
|
|
477
819
|
}
|