@answerlayer/cli 0.1.8 → 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 CHANGED
@@ -97,30 +97,73 @@ This installs to `~/.codex/skills/answerlayer` by default. Use `--path` for a
97
97
  different skill directory; an existing skill is never replaced unless you pass
98
98
  `--force`.
99
99
 
100
- Set the model-provider key privately, then let the CLI prepare the stack and
101
- configure itself:
100
+ Initialize and start the local runtime:
102
101
 
103
102
  ```bash
104
- read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
105
- answerlayer local up
103
+ answerlayer local init
104
+ answerlayer local start
106
105
  ```
107
106
 
108
- Use `--stack-dir <directory>` to reuse a different core checkout. If that
109
- checkout already has a `.env`, the provider key does not need to be exported.
110
- The command:
107
+ `local init` selects the CLI's supported public image by default. Use
108
+ `--image <tag-or-digest>` to select a different published version and `--port`
109
+ to change the local port. The CLI:
111
110
 
112
- 1. Verifies Git and Docker and clones `answerlayer-core` when needed.
113
- 2. Creates a permission-restricted `.env` and generates its encryption key.
114
- 3. Starts Docker Compose and waits for the API to become healthy.
115
- 4. Creates a local-only organization and scoped key, verifies the key, and
111
+ 1. Verifies Docker, its architecture and version, the port, and available disk.
112
+ 2. Pulls the public AnswerLayer image and pins its resolved immutable digest.
113
+ 3. Generates permission-restricted Compose, state, and secret files in the
114
+ platform application-data directory.
115
+ 4. Starts Postgres, runs migrations, and waits for AnswerLayer readiness.
116
+ 5. Creates a local-only organization and scoped key, verifies the key, and
116
117
  saves the CLI configuration without printing the key.
117
- 5. Leaves you ready to connect a dedicated, read-only database user and test a
118
- small, approved schema first.
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.
119
121
 
120
- The local stack never needs a hosted AnswerLayer account. The skill requires
121
- agent confirmation before it starts containers, creates a connection, or sends
122
- queries to a real database, and it instructs agents not to print or persist
123
- database passwords.
122
+ The local stack does not require a hosted AnswerLayer account, a source checkout,
123
+ private registry credentials, or a model-provider key for first boot. Add an
124
+ optional provider key later only when using features that call that provider.
125
+ The skill requires agent confirmation before it starts containers, creates a
126
+ connection, or sends queries to a real database, and it instructs agents not to
127
+ print or persist database passwords.
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
+
151
+ Inspect and manage the lifecycle with:
152
+
153
+ ```bash
154
+ answerlayer local status [--json]
155
+ answerlayer local logs [--follow] [answerlayer|migrate|postgres]
156
+ answerlayer local stop # preserves Postgres data
157
+ answerlayer local upgrade # moves to this CLI's supported default
158
+ answerlayer local upgrade --image <tag> # selects an explicit release
159
+ answerlayer local reset --force # permanently deletes local data
160
+ ```
161
+
162
+ The selected tag and resolved digest are recorded in `state.json` and displayed
163
+ by `local status`. Set `ANSWERLAYER_LOCAL_DIR` to override the application-data
164
+ directory or `ANSWERLAYER_LOCAL_IMAGE` to override the default image.
165
+ Each runtime directory receives stable, isolated Compose project, volume, and
166
+ network names, so stopping or resetting one runtime cannot affect another.
124
167
 
125
168
  Useful scopes:
126
169
 
@@ -138,7 +181,12 @@ Useful scopes:
138
181
  ```bash
139
182
  answerlayer health
140
183
  answerlayer openapi --output openapi.json
141
- answerlayer local up
184
+ answerlayer local init
185
+ answerlayer local start
186
+ answerlayer local demo --json
187
+ answerlayer local status
188
+ answerlayer local logs
189
+ answerlayer local stop
142
190
 
143
191
  answerlayer connections list
144
192
  answerlayer connections get <connection-id>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@answerlayer/cli",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -30,34 +30,54 @@ already available in the Codex skills directory.
30
30
  npm install -g @answerlayer/cli
31
31
  ```
32
32
 
33
- 2. Ask the user to set their Anthropic key privately in their own terminal. Do
34
- not ask them to paste it into chat or put it in shell history:
33
+ 2. After confirmation, initialize the repository-free local runtime:
35
34
 
36
35
  ```bash
37
- read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
36
+ answerlayer local init
38
37
  ```
39
38
 
40
- 3. After confirmation, run the complete local setup:
39
+ This checks Docker, pulls the supported public AnswerLayer image, pins its
40
+ immutable digest, and generates permission-restricted runtime configuration
41
+ in the platform application-data directory. It does not require Git, a
42
+ source checkout, registry credentials, or a model-provider key.
43
+
44
+ 3. After confirmation, start and configure the stack:
41
45
 
42
46
  ```bash
43
- answerlayer local up
47
+ answerlayer local start
44
48
  ```
45
49
 
46
- This verifies Git and Docker, clones the core stack to
47
- `~/.answerlayer/core` when needed, creates a permission-restricted `.env`
48
- with a generated encryption key, starts Docker Compose, waits for health,
49
- creates the local identity and scoped key, verifies it, and configures the
50
- CLI. It captures the one-time key rather than printing it. Use
51
- `--stack-dir <directory>` to reuse a different core checkout; when that
52
- checkout already has a `.env`, `ANTHROPIC_API_KEY` need not be exported.
50
+ This starts Postgres, runs migrations, waits for readiness, creates the local
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
56
+ `answerlayer local logs` to inspect progress. `local stop` preserves data;
57
+ `local reset --force` is the explicit destructive reset. Use `--no-demo`
58
+ only when the user explicitly wants an empty instance.
59
+
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
+ ```
53
73
 
54
- 4. Before connecting real data, require a dedicated database account that is
74
+ 5. Before connecting real data, require a dedicated database account that is
55
75
  restricted to approved schemas and `SELECT` only. Show the proposed
56
76
  connection host, database, and username, then get confirmation before
57
77
  running `connections create` or any query. Put the password only in a local,
58
78
  permission-restricted JSON file; never print it or commit it.
59
79
 
60
- 5. Start with a small approved schema and read-only inspection. Confirm before
80
+ 6. Start with a small approved schema and read-only inspection. Confirm before
61
81
  creating connections, generating semantic objects, or executing queries.
62
82
 
63
83
  This workflow is for Docker Compose development only. Do not run
package/src/cli.js CHANGED
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { AnswerLayerClient } from "./client.js";
6
6
  import { formatJson, formatList, formatQueryResult } from "./format.js";
7
7
  import { DEFAULT_BASE_URL, readConfig, resolveAuth, writeConfig } from "./config.js";
8
- import { localUp } from "./local.js";
8
+ import { handleLocal } from "./local.js";
9
9
 
10
10
  const SEMANTIC_RESOURCES = new Set([
11
11
  "entities",
@@ -38,8 +38,7 @@ export async function main(argv, io) {
38
38
  }
39
39
 
40
40
  if (group === "local") {
41
- if (command !== "up") throw usage("Expected `answerlayer local up`");
42
- return localUp(parsed, io);
41
+ return handleLocal(command, parsed, io);
43
42
  }
44
43
 
45
44
  const { baseUrl, apiKey } = resolveAuth(parsed.flags, io.env);
@@ -1439,6 +1438,7 @@ function normalizeFlagName(rawName) {
1439
1438
  "--model": "model",
1440
1439
  "--use-semantic-layer": "useSemanticLayer",
1441
1440
  "--no-semantic-layer": "noSemanticLayer",
1441
+ "--no-demo": "noDemo",
1442
1442
  "--options": "options",
1443
1443
  "--status": "status",
1444
1444
  "--summary": "summary",
@@ -1471,14 +1471,13 @@ function normalizeFlagName(rawName) {
1471
1471
  "--relationship-type": "relationshipType",
1472
1472
  "--join": "join",
1473
1473
  "--form": "form",
1474
- "--stack-dir": "stackDir",
1475
1474
  };
1476
1475
 
1477
1476
  return aliases[rawName] || rawName.replace(/^-+/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1478
1477
  }
1479
1478
 
1480
1479
  function isBooleanFlag(rawName) {
1481
- return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--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);
1482
1481
  }
1483
1482
 
1484
1483
  function setFlag(flags, name, value) {
@@ -1615,7 +1614,12 @@ function helpText() {
1615
1614
 
1616
1615
  Usage:
1617
1616
  answerlayer skills install [--path <directory>] [--force]
1618
- answerlayer local up [--stack-dir <directory>]
1617
+ answerlayer local init [--image <image>] [--port <port>]
1618
+ answerlayer local start [--no-demo]
1619
+ answerlayer local status|logs|stop
1620
+ answerlayer local demo [--json]
1621
+ answerlayer local upgrade [--image <image>]
1622
+ answerlayer local reset --force
1619
1623
  answerlayer init --api-key <key> [--base-url <url>]
1620
1624
  answerlayer configure --base-url <url> --api-key <key>
1621
1625
  answerlayer health
package/src/local.js CHANGED
@@ -1,148 +1,468 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
+ import net from "node:net";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
5
6
  import { spawnSync } from "node:child_process";
6
7
  import { AnswerLayerClient } from "./client.js";
7
- import { readConfig, writeConfig } from "./config.js";
8
-
9
- const CORE_REPOSITORY = "https://github.com/AnswerLayer/answerlayer-core.git";
10
- const CORE_REMOTE_PATTERN = /(?:^|@|\/\/)github\.com[:/]AnswerLayer\/answerlayer-core(?:\.git)?\/?$/i;
11
- const REQUIRED_CORE_PATHS = [
12
- "docker-compose.yml",
13
- ".env.example",
14
- "Makefile",
15
- "backend/app/scripts/bootstrap_local.py",
8
+ import { defaultConfigPath, readConfig, writeConfig } from "./config.js";
9
+
10
+ export const DEFAULT_LOCAL_IMAGE = "public.ecr.aws/s8d9x7y7/answerlayer:1.19.9";
11
+ const DEFAULT_PORT = 8000;
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?",
16
22
  ];
17
23
 
24
+ export async function handleLocal(command, parsed, io) {
25
+ if (command === "init") return localInit(parsed, io);
26
+ if (command === "start" || command === "up") return localStart(parsed, io);
27
+ if (command === "status") return localStatus(parsed, io);
28
+ if (command === "logs") return localLogs(parsed, io);
29
+ if (command === "stop") return localStop(parsed, io);
30
+ if (command === "demo") return localDemo(parsed, io);
31
+ if (command === "upgrade") return localUpgrade(parsed, io);
32
+ if (command === "reset") return localReset(parsed, io);
33
+ throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|upgrade|reset`");
34
+ }
35
+
18
36
  export async function localUp(parsed, io) {
19
- const stackDir = path.resolve(firstValue(parsed.flags.stackDir) || path.join(os.homedir(), ".answerlayer", "core"));
20
- const envPath = path.join(stackDir, ".env");
21
- const run = io.runCommand || runCommand;
37
+ return localStart(parsed, io);
38
+ }
22
39
 
23
- requireCommand(run, "git", ["--version"]);
24
- requireCommand(run, "docker", ["compose", "version"]);
40
+ async function localInit(parsed, io) {
41
+ const runtime = await ensureInitialized(parsed, io);
42
+ printRuntimeSummary(runtime, io, "Local AnswerLayer is initialized.");
43
+ write(io.stdout, "Next: answerlayer local start\n");
44
+ }
45
+
46
+ async function localStart(parsed, io) {
47
+ const run = io.runCommand || runCommand;
48
+ const runtime = await ensureInitialized(parsed, io);
49
+ const before = inspectStatus(runtime, run);
25
50
 
26
- const stackExists = fs.existsSync(stackDir);
27
- if (!fs.existsSync(envPath) && !io.env.ANTHROPIC_API_KEY) {
51
+ if (before.status === "stopped" && !(await portIsAvailable(runtime.state.port, io))) {
28
52
  throw new Error(
29
- "Set ANTHROPIC_API_KEY in your environment before the first `answerlayer local up`. It is written only to the local stack's permission-restricted .env file.",
53
+ `Port ${runtime.state.port} is already in use. Stop the process using it or choose another port with --port <port>.`,
30
54
  );
31
55
  }
32
56
 
33
- if (!stackExists) {
34
- fs.mkdirSync(path.dirname(stackDir), { recursive: true, mode: 0o700 });
35
- write(io.stdout, `Cloning the AnswerLayer stack into ${stackDir}\n`);
36
- checked(run, "git", ["clone", "--depth", "1", CORE_REPOSITORY, stackDir]);
57
+ write(io.stdout, `Starting AnswerLayer ${runtime.state.resolvedImage}...\n`);
58
+ try {
59
+ checked(run, "docker", [...composeArgs(runtime), "up", "--detach", "--wait", "--wait-timeout", "180"]);
60
+ } catch (error) {
61
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
62
+ const hint = status.status === "failed"
63
+ ? " Inspect `answerlayer local logs` for the migration or application error."
64
+ : " Check Docker Desktop/Engine and retry.";
65
+ throw new Error(`Local stack failed to start: ${error.message}.${hint}`);
37
66
  }
38
- validateCheckout(stackDir, run);
39
67
 
40
- if (!fs.existsSync(envPath)) {
41
- prepareEnvironment(stackDir, io.env.ANTHROPIC_API_KEY);
42
- write(io.stdout, `Created ${envPath} with permissions 0600\n`);
68
+ const baseUrl = `http://127.0.0.1:${runtime.state.port}`;
69
+ await waitUntilReady(baseUrl, io);
70
+ const configPath = await ensureLocalCredentials(runtime, baseUrl, io);
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() };
75
+ writeState(runtime.statePath, state);
76
+
77
+ printRuntimeSummary({ ...runtime, state }, io, "Local AnswerLayer is ready.");
78
+ write(io.stdout, `CLI config: ${configPath}\n`);
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");
43
84
  }
85
+ }
44
86
 
45
- write(io.stdout, "Starting the local AnswerLayer stack...\n");
46
- checked(run, "docker", ["compose", "up", "--build", "-d"], { cwd: stackDir, passthrough: true });
47
- const publishedPort = checked(
48
- run,
49
- "docker",
50
- ["compose", "port", "answerlayer", "8000"],
51
- { cwd: stackDir },
52
- );
53
- const baseUrl = parsePublishedBaseUrl(publishedPort.stdout);
54
- await waitUntilHealthy(baseUrl, io);
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
+ }
55
95
 
56
- write(io.stdout, "Creating a local CLI identity and rotating its scoped key...\n");
57
- const bootstrap = checked(run, "make", ["local-bootstrap"], { cwd: stackDir });
58
- const credentials = { baseUrl, apiKey: parseBootstrapApiKey(bootstrap.stdout) };
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
+ });
59
105
 
60
- // Bootstrap rotates the previous key, so persist the replacement before any
61
- // network verification that may fail transiently. This keeps the only valid
62
- // credential recoverable for a retry.
63
- const existing = readConfig(io.env);
64
- const configPath = writeConfig({ ...existing, ...credentials }, io.env);
106
+ if (parsed.flags.json) {
107
+ write(io.stdout, `${JSON.stringify(demo, null, 2)}\n`);
108
+ return;
109
+ }
110
+ printDemoSummary(demo, io);
111
+ }
65
112
 
66
- const client = new AnswerLayerClient({ ...credentials, fetchImpl: io.fetch || globalThis.fetch });
67
- try {
68
- await client.rawRequest("GET", "/api/v1/auth/me");
69
- } catch (error) {
70
- throw new Error(`Saved rotated local credentials to ${configPath}, but verification failed: ${error.message}`);
113
+ async function localUpgrade(parsed, io) {
114
+ const image = firstValue(parsed.flags.image) || io.env.ANSWERLAYER_LOCAL_IMAGE || DEFAULT_LOCAL_IMAGE;
115
+ write(io.stdout, `Upgrading the local runtime to ${image}...\n`);
116
+ return localStart({ ...parsed, flags: { ...parsed.flags, image, forcePull: true } }, io);
117
+ }
118
+
119
+ async function localStatus(parsed, io) {
120
+ const run = io.runCommand || runCommand;
121
+ const runtime = loadRuntime(parsed, io);
122
+ requireCommand(run, "docker", ["compose", "version"]);
123
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
124
+ const result = {
125
+ status: status.status,
126
+ url: `http://127.0.0.1:${runtime.state.port}`,
127
+ image: runtime.state.requestedImage,
128
+ resolvedImage: runtime.state.resolvedImage,
129
+ runtimeDirectory: runtime.directory,
130
+ demo: runtime.state.demo || { status: "not-installed", version: LOCAL_DEMO_VERSION },
131
+ services: status.services,
132
+ };
133
+
134
+ if (parsed.flags.json) {
135
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
136
+ return;
71
137
  }
138
+ write(io.stdout, `Status: ${result.status}\n`);
139
+ write(io.stdout, `URL: ${result.url}\n`);
140
+ write(io.stdout, `Image: ${result.resolvedImage}\n`);
141
+ write(io.stdout, `Runtime config: ${result.runtimeDirectory}\n`);
142
+ write(io.stdout, `Demo: ${result.demo.status} (${result.demo.version})\n`);
143
+ }
72
144
 
73
- write(io.stdout, `Local AnswerLayer is ready. Verified credentials and saved config to ${configPath}\n`);
74
- write(io.stdout, "Next: answerlayer connections list\n");
145
+ async function localLogs(parsed, io) {
146
+ const run = io.runCommand || runCommand;
147
+ const runtime = loadRuntime(parsed, io);
148
+ requireCommand(run, "docker", ["compose", "version"]);
149
+ const args = [...composeArgs(runtime), "logs"];
150
+ if (parsed.flags.follow) args.push("--follow");
151
+ args.push("--tail", String(firstValue(parsed.flags.tail) || 100));
152
+ const service = parsed.positionals[2];
153
+ if (service) args.push(service);
154
+ checked(run, "docker", args, { passthrough: true });
75
155
  }
76
156
 
77
- function prepareEnvironment(stackDir, anthropicApiKey) {
78
- const examplePath = path.join(stackDir, ".env.example");
79
- if (!fs.existsSync(examplePath)) throw new Error(`Missing ${examplePath}`);
157
+ async function localStop(parsed, io) {
158
+ const run = io.runCommand || runCommand;
159
+ const runtime = loadRuntime(parsed, io);
160
+ requireCommand(run, "docker", ["compose", "version"]);
161
+ checked(run, "docker", [...composeArgs(runtime), "down"], { passthrough: true });
162
+ writeState(runtime.statePath, { ...runtime.state, lastStatus: "stopped", updatedAt: new Date().toISOString() });
163
+ write(io.stdout, "Local AnswerLayer stopped. Persistent data was preserved.\n");
164
+ write(io.stdout, "Resume with: answerlayer local start\n");
165
+ }
80
166
 
81
- if (/[\r\n]/.test(anthropicApiKey)) throw new Error("ANTHROPIC_API_KEY must not contain a newline");
82
- const encryptionKey = crypto.randomBytes(32).toString("hex");
83
- const template = fs.readFileSync(examplePath, "utf8");
84
- const replacements = {
85
- ANTHROPIC_API_KEY: anthropicApiKey,
86
- ENCRYPTION_KEY: encryptionKey,
87
- };
88
- let contents = template;
89
- for (const [name, value] of Object.entries(replacements)) {
90
- const pattern = new RegExp(`^${name}=.*$`, "gm");
91
- if ([...template.matchAll(pattern)].length !== 1) {
92
- throw new Error(`${examplePath} must contain exactly one ${name}= entry`);
167
+ async function localReset(parsed, io) {
168
+ if (!parsed.flags.force) {
169
+ throw new Error(
170
+ "Reset permanently deletes the local AnswerLayer database. Rerun with `answerlayer local reset --force` to confirm.",
171
+ );
172
+ }
173
+ const run = io.runCommand || runCommand;
174
+ const runtime = loadRuntime(parsed, io);
175
+ requireCommand(run, "docker", ["compose", "version"]);
176
+ checked(run, "docker", [...composeArgs(runtime), "down", "--volumes", "--remove-orphans"], { passthrough: true });
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
+ });
183
+ write(io.stdout, "Deleted the local AnswerLayer database volume. Runtime configuration was preserved.\n");
184
+ write(io.stdout, "Create a fresh database with: answerlayer local start\n");
185
+ }
186
+
187
+ async function ensureInitialized(parsed, io) {
188
+ const run = io.runCommand || runCommand;
189
+ const runtime = runtimePaths(parsed, io);
190
+ fs.mkdirSync(runtime.directory, { recursive: true, mode: 0o700 });
191
+
192
+ preflight(run, runtime.directory, io);
193
+
194
+ const existingState = readState(runtime.statePath);
195
+ const explicitImage = firstValue(parsed.flags.image) || io.env.ANSWERLAYER_LOCAL_IMAGE;
196
+ const requestedImage = explicitImage || existingState?.requestedImage || DEFAULT_LOCAL_IMAGE;
197
+ const port = parsePort(firstValue(parsed.flags.port) || existingState?.port || DEFAULT_PORT);
198
+ const needsPull = parsed.flags.forcePull
199
+ || !existingState?.resolvedImage
200
+ || requestedImage !== existingState.requestedImage;
201
+
202
+ let resolvedImage = existingState?.resolvedImage;
203
+ if (needsPull) {
204
+ write(io.stdout, `Pulling ${requestedImage} from the public registry...\n`);
205
+ try {
206
+ checked(run, "docker", ["pull", requestedImage]);
207
+ resolvedImage = resolveDigest(run, requestedImage);
208
+ } catch (error) {
209
+ throw new Error(
210
+ `Could not pull the public AnswerLayer image ${requestedImage}: ${error.message}. Check network access and the image version, then retry.`,
211
+ );
93
212
  }
94
- contents = contents.replace(pattern, () => `${name}=${value}`);
95
213
  }
96
- const envPath = path.join(stackDir, ".env");
97
- fs.writeFileSync(envPath, contents, { encoding: "utf8", mode: 0o600 });
98
- fs.chmodSync(envPath, 0o600);
214
+
215
+ const state = {
216
+ schemaVersion: 1,
217
+ requestedImage,
218
+ resolvedImage,
219
+ port,
220
+ ...(existingState?.demo ? { demo: existingState.demo } : {}),
221
+ ...runtimeResourceNames(runtime.directory),
222
+ createdAt: existingState?.createdAt || new Date().toISOString(),
223
+ updatedAt: new Date().toISOString(),
224
+ lastStatus: existingState?.lastStatus || "stopped",
225
+ };
226
+
227
+ writeCompose(runtime.composePath);
228
+ writeEnvironment(runtime.envPath, state);
229
+ writeState(runtime.statePath, state);
230
+ return { ...runtime, state };
99
231
  }
100
232
 
101
- function validateCheckout(stackDir, run) {
102
- if (!fs.existsSync(path.join(stackDir, ".git"))) {
103
- throw new Error(`${stackDir} is not a Git checkout`);
233
+ function preflight(run, directory, io) {
234
+ requireCommand(run, "docker", ["compose", "version"]);
235
+ const dockerVersion = checked(run, "docker", ["version", "--format", "{{.Server.Version}}"]).stdout.trim();
236
+ requireMinimumVersion(dockerVersion, [20, 10], "Docker Engine");
237
+ const composeVersion = checked(run, "docker", ["compose", "version", "--short"]).stdout.trim();
238
+ requireMinimumVersion(composeVersion, [2, 20], "Docker Compose");
239
+
240
+ const engine = checked(run, "docker", ["info", "--format", "{{.OSType}}/{{.Architecture}}"]).stdout.trim();
241
+ if (!/^linux\/(amd64|x86_64|arm64|aarch64)$/.test(engine)) {
242
+ throw new Error(`Unsupported Docker platform ${engine || "unknown"}. AnswerLayer supports linux/amd64 and linux/arm64 containers.`);
243
+ }
244
+
245
+ const availableBytes = io.availableBytes ?? freeBytes(directory);
246
+ if (availableBytes < MINIMUM_FREE_BYTES) {
247
+ throw new Error("AnswerLayer local setup requires at least 2 GB of free disk space for images and persistent data.");
104
248
  }
105
- for (const relativePath of REQUIRED_CORE_PATHS) {
106
- if (!fs.existsSync(path.join(stackDir, relativePath))) {
107
- throw new Error(`${stackDir} is missing required AnswerLayer core file ${relativePath}`);
249
+ }
250
+
251
+ function requireMinimumVersion(raw, minimum, label) {
252
+ const match = String(raw).match(/(\d+)\.(\d+)(?:\.(\d+))?/);
253
+ if (!match) throw new Error(`Could not determine ${label} version from ${raw || "empty output"}`);
254
+ const current = match.slice(1, 4).map(value => Number.parseInt(value || "0", 10));
255
+ for (let index = 0; index < minimum.length; index += 1) {
256
+ if (current[index] > minimum[index]) return;
257
+ if (current[index] < minimum[index]) {
258
+ throw new Error(`${label} ${minimum.join(".")} or newer is required; found ${raw}`);
108
259
  }
109
260
  }
261
+ }
110
262
 
111
- const remote = checked(run, "git", ["-C", stackDir, "remote", "get-url", "origin"]);
112
- if (!CORE_REMOTE_PATTERN.test(String(remote.stdout).trim())) {
113
- throw new Error(`${stackDir} does not use the official AnswerLayer core origin`);
263
+ function resolveDigest(run, requestedImage) {
264
+ const inspected = checked(
265
+ run,
266
+ "docker",
267
+ ["image", "inspect", "--format", "{{json .RepoDigests}}", requestedImage],
268
+ ).stdout.trim();
269
+ let digests;
270
+ try {
271
+ digests = JSON.parse(inspected);
272
+ } catch {
273
+ throw new Error("Docker did not return parseable image digest metadata");
114
274
  }
275
+ const repository = imageRepository(requestedImage);
276
+ const resolved = digests.find(item => String(item).startsWith(`${repository}@sha256:`));
277
+ if (!resolved) throw new Error("Docker did not return an immutable digest for the pulled image");
278
+ return resolved;
279
+ }
280
+
281
+ function imageRepository(image) {
282
+ const withoutDigest = String(image).split("@")[0];
283
+ const slash = withoutDigest.lastIndexOf("/");
284
+ const colon = withoutDigest.lastIndexOf(":");
285
+ return colon > slash ? withoutDigest.slice(0, colon) : withoutDigest;
115
286
  }
116
287
 
117
- function parsePublishedBaseUrl(stdout) {
118
- const publishedAddress = String(stdout)
119
- .split(/\r?\n/)
120
- .map(line => line.trim())
121
- .map(line => line.match(/^(0\.0\.0\.0|127\.0\.0\.1|localhost|\[::\]|\[::1\]|::):(\d+)$/))
122
- .find(Boolean);
123
- const port = publishedAddress ? Number.parseInt(publishedAddress[2], 10) : 0;
124
- if (port < 1 || port > 65535) {
125
- throw new Error("Docker Compose did not publish answerlayer port 8000 on a local host interface");
288
+ async function ensureLocalCredentials(runtime, baseUrl, io, options = {}) {
289
+ const existing = readConfig(io.env);
290
+ const fetchImpl = io.fetch || globalThis.fetch;
291
+ if (existing.baseUrl === baseUrl && existing.apiKey) {
292
+ const client = new AnswerLayerClient({ baseUrl, apiKey: existing.apiKey, fetchImpl });
293
+ try {
294
+ await client.rawRequest("GET", "/api/v1/auth/me");
295
+ return defaultConfigPath(io.env);
296
+ } catch {
297
+ // The database may have been reset. Bootstrap a replacement local key.
298
+ }
299
+ }
300
+
301
+ if (!options.quiet) {
302
+ write(io.stdout, "Creating a local-only CLI identity...\n");
303
+ }
304
+ const run = io.runCommand || runCommand;
305
+ let bootstrap;
306
+ try {
307
+ bootstrap = checked(run, "docker", [
308
+ ...composeArgs(runtime),
309
+ "exec", "-T", "answerlayer", "python", "-m", "app.scripts.bootstrap_local",
310
+ ]);
311
+ } catch (error) {
312
+ throw new Error(`Local credential bootstrap failed: ${error.message}. Run \`answerlayer local logs answerlayer\` for details.`);
126
313
  }
127
- const host = publishedAddress[1] === "[::1]" ? "[::1]" : "127.0.0.1";
128
- return `http://${host}:${port}`;
314
+ const credentials = { baseUrl, apiKey: parseBootstrapApiKey(bootstrap.stdout) };
315
+ const configPath = writeConfig({ ...existing, ...credentials }, io.env);
316
+ const client = new AnswerLayerClient({ ...credentials, fetchImpl });
317
+ try {
318
+ await client.rawRequest("GET", "/api/v1/auth/me");
319
+ } catch (error) {
320
+ throw new Error(`Saved local credentials to ${configPath}, but verification failed: ${error.message}`);
321
+ }
322
+ return configPath;
129
323
  }
130
324
 
131
- async function waitUntilHealthy(baseUrl, io) {
325
+ async function waitUntilReady(baseUrl, io) {
132
326
  const fetchImpl = io.fetch || globalThis.fetch;
133
- const sleep = io.sleep || ((milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds)));
327
+ const sleep = io.sleep || (milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)));
134
328
  const attempts = io.healthAttempts || 60;
135
-
136
329
  for (let attempt = 0; attempt < attempts; attempt += 1) {
137
330
  try {
138
- const response = await fetchImpl(`${baseUrl}/healthz`);
331
+ const response = await fetchImpl(`${baseUrl}/readyz`);
139
332
  if (response.ok) return;
140
333
  } catch {
141
- // The container may still be starting.
334
+ // Docker may have reported healthy just before the host port was reachable.
142
335
  }
143
336
  await sleep(2000);
144
337
  }
145
- throw new Error(`Local stack did not become healthy at ${baseUrl}/healthz`);
338
+ throw new Error(`AnswerLayer did not become ready at ${baseUrl}/readyz. Run \`answerlayer local logs\` for details.`);
339
+ }
340
+
341
+ function inspectStatus(runtime, run, options = {}) {
342
+ const result = run("docker", [...composeArgs(runtime), "ps", "--all", "--format", "json"], { capture: true });
343
+ if (result.error || result.status !== 0) {
344
+ if (options.tolerateFailure) return { status: "failed", services: [] };
345
+ throw new Error("Could not inspect the local Docker Compose stack");
346
+ }
347
+ const services = parseComposePs(result.stdout);
348
+ const migrate = services.find(service => String(service.Service).toLowerCase() === "migrate");
349
+ const app = services.find(service => String(service.Service).toLowerCase() === "answerlayer");
350
+ const state = value => String(value || "").toLowerCase();
351
+
352
+ if ([migrate, app].some(service => service && (state(service.Health) === "unhealthy" || (state(service.State) === "exited" && Number(service.ExitCode) !== 0)))) {
353
+ return { status: "failed", services };
354
+ }
355
+ if (migrate && state(migrate.State) === "running") return { status: "migrating", services };
356
+ if (app && state(app.State) === "running" && state(app.Health) === "healthy") return { status: "ready", services };
357
+ if (app && state(app.State) === "running") return { status: "starting", services };
358
+ return { status: "stopped", services };
359
+ }
360
+
361
+ function parseComposePs(stdout) {
362
+ const raw = String(stdout || "").trim();
363
+ if (!raw) return [];
364
+ try {
365
+ const parsed = JSON.parse(raw);
366
+ return Array.isArray(parsed) ? parsed : [parsed];
367
+ } catch {
368
+ return raw.split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
369
+ }
370
+ }
371
+
372
+ function loadRuntime(parsed, io) {
373
+ const runtime = runtimePaths(parsed, io);
374
+ const state = readState(runtime.statePath);
375
+ if (!state || !fs.existsSync(runtime.composePath) || !fs.existsSync(runtime.envPath)) {
376
+ throw new Error("Local AnswerLayer is not initialized. Run `answerlayer local init` first.");
377
+ }
378
+ return { ...runtime, state };
379
+ }
380
+
381
+ function runtimePaths(parsed, io) {
382
+ const directory = path.resolve(
383
+ firstValue(parsed.flags.runtimeDir)
384
+ || io.env.ANSWERLAYER_LOCAL_DIR
385
+ || defaultRuntimeDirectory(io.env, io.platform || process.platform),
386
+ );
387
+ return {
388
+ directory,
389
+ composePath: path.join(directory, "compose.yaml"),
390
+ envPath: path.join(directory, "runtime.env"),
391
+ statePath: path.join(directory, "state.json"),
392
+ };
393
+ }
394
+
395
+ function defaultRuntimeDirectory(env, platform) {
396
+ const home = env.HOME || os.homedir();
397
+ if (platform === "darwin") return path.join(home, "Library", "Application Support", "AnswerLayer", "local");
398
+ if (platform === "win32") return path.join(env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "AnswerLayer", "local");
399
+ return path.join(env.XDG_DATA_HOME || path.join(home, ".local", "share"), "answerlayer", "local");
400
+ }
401
+
402
+ function writeCompose(composePath) {
403
+ fs.writeFileSync(composePath, `${COMPOSE_FILE}\n`, { encoding: "utf8", mode: 0o600 });
404
+ fs.chmodSync(composePath, 0o600);
405
+ }
406
+
407
+ function writeEnvironment(envPath, state) {
408
+ const existing = readEnvironment(envPath);
409
+ const values = {
410
+ ANSWERLAYER_IMAGE: state.resolvedImage,
411
+ ANSWERLAYER_POSTGRES_PASSWORD: existing.ANSWERLAYER_POSTGRES_PASSWORD || crypto.randomBytes(24).toString("hex"),
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"),
414
+ ANSWERLAYER_PORT: String(state.port),
415
+ ANSWERLAYER_LOG_LEVEL: existing.ANSWERLAYER_LOG_LEVEL || "INFO",
416
+ ANSWERLAYER_WEB_CONCURRENCY: existing.ANSWERLAYER_WEB_CONCURRENCY || "1",
417
+ ANSWERLAYER_ANTHROPIC_API_KEY: existing.ANSWERLAYER_ANTHROPIC_API_KEY || "",
418
+ ANSWERLAYER_POSTGRES_VOLUME: state.postgresVolume,
419
+ ANSWERLAYER_NETWORK: state.networkName,
420
+ };
421
+ const contents = Object.entries(values).map(([name, value]) => `${name}=${value}`).join("\n");
422
+ fs.writeFileSync(envPath, `${contents}\n`, { encoding: "utf8", mode: 0o600 });
423
+ fs.chmodSync(envPath, 0o600);
424
+ }
425
+
426
+ function readEnvironment(envPath) {
427
+ if (!fs.existsSync(envPath)) return {};
428
+ return Object.fromEntries(
429
+ fs.readFileSync(envPath, "utf8").split(/\r?\n/).filter(line => line && !line.startsWith("#")).map(line => {
430
+ const separator = line.indexOf("=");
431
+ return [line.slice(0, separator), line.slice(separator + 1)];
432
+ }),
433
+ );
434
+ }
435
+
436
+ function readState(statePath) {
437
+ if (!fs.existsSync(statePath)) return null;
438
+ try {
439
+ return JSON.parse(fs.readFileSync(statePath, "utf8"));
440
+ } catch (error) {
441
+ throw new Error(`Invalid local runtime state at ${statePath}: ${error.message}`);
442
+ }
443
+ }
444
+
445
+ function writeState(statePath, state) {
446
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
447
+ fs.chmodSync(statePath, 0o600);
448
+ }
449
+
450
+ function composeArgs(runtime) {
451
+ return [
452
+ "compose", "--project-name", runtime.state.projectName,
453
+ "--file", runtime.composePath,
454
+ "--env-file", runtime.envPath,
455
+ ];
456
+ }
457
+
458
+ function runtimeResourceNames(directory) {
459
+ const id = crypto.createHash("sha256").update(path.resolve(directory)).digest("hex").slice(0, 12);
460
+ return {
461
+ runtimeId: id,
462
+ projectName: `answerlayer-local-${id}`,
463
+ postgresVolume: `answerlayer-local-${id}-postgres-data`,
464
+ networkName: `answerlayer-local-${id}-network`,
465
+ };
146
466
  }
147
467
 
148
468
  function parseBootstrapApiKey(stdout) {
@@ -152,31 +472,348 @@ function parseBootstrapApiKey(stdout) {
152
472
  return match[1];
153
473
  }
154
474
 
475
+ function parsePort(value) {
476
+ const port = Number(value);
477
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
478
+ throw new Error(`Expected --port to be an integer from 1 to 65535; received ${value}`);
479
+ }
480
+ return port;
481
+ }
482
+
483
+ function freeBytes(directory) {
484
+ const stats = fs.statfsSync(directory);
485
+ return Number(stats.bavail) * Number(stats.bsize);
486
+ }
487
+
488
+ function portIsAvailable(port, io) {
489
+ if (io.portIsAvailable) return Promise.resolve(io.portIsAvailable(port));
490
+ return new Promise(resolve => {
491
+ const server = net.createServer();
492
+ server.unref();
493
+ server.once("error", () => resolve(false));
494
+ server.listen({ host: "127.0.0.1", port }, () => server.close(() => resolve(true)));
495
+ });
496
+ }
497
+
155
498
  function requireCommand(run, command, args) {
156
499
  const result = run(command, args, { capture: true });
157
- if (result.error?.code === "ENOENT") throw new Error(`${command} is required for local setup`);
158
- if (result.status !== 0) throw new Error(`${command} is required for local setup`);
500
+ if (result.error?.code === "ENOENT" || result.status !== 0) {
501
+ throw new Error(`${command} is required for local setup and must be running`);
502
+ }
159
503
  }
160
504
 
161
505
  function checked(run, command, args, options = {}) {
162
- const result = run(command, args, { capture: !options.passthrough, cwd: options.cwd });
506
+ const result = run(command, args, { capture: !options.passthrough, input: options.input });
163
507
  if (result.error) throw result.error;
164
508
  if (result.status !== 0) {
165
- const detail = String(result.stderr || "").trim();
509
+ const detail = String(result.stderr || result.stdout || "").trim();
166
510
  throw new Error(`${command} ${args.join(" ")} failed${detail ? `: ${detail}` : ""}`);
167
511
  }
168
- return result;
512
+ return { ...result, stdout: String(result.stdout || "") };
169
513
  }
170
514
 
171
515
  function runCommand(command, args, options = {}) {
172
516
  return spawnSync(command, args, {
173
- cwd: options.cwd,
174
517
  encoding: options.capture ? "utf8" : undefined,
175
- stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit",
518
+ input: options.input,
519
+ stdio: options.capture
520
+ ? [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
521
+ : "inherit",
176
522
  maxBuffer: 50 * 1024 * 1024,
177
523
  });
178
524
  }
179
525
 
526
+ function printRuntimeSummary(runtime, io, heading) {
527
+ write(io.stdout, `${heading}\n`);
528
+ write(io.stdout, `URL: http://127.0.0.1:${runtime.state.port}\n`);
529
+ write(io.stdout, `Image: ${runtime.state.requestedImage}\n`);
530
+ write(io.stdout, `Resolved image: ${runtime.state.resolvedImage}\n`);
531
+ write(io.stdout, `Runtime config: ${runtime.directory}\n`);
532
+ }
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
+
180
817
  function firstValue(value) {
181
818
  return Array.isArray(value) ? value[0] : value;
182
819
  }
@@ -184,3 +821,84 @@ function firstValue(value) {
184
821
  function write(stream, text) {
185
822
  stream.write(text);
186
823
  }
824
+
825
+ const COMPOSE_FILE = [
826
+ "name: answerlayer-local",
827
+ "",
828
+ "x-answerlayer-database-environment: &answerlayer-database-environment",
829
+ " DB_HOST: postgres",
830
+ " DB_PORT: \"5432\"",
831
+ " DB_USER: answerlayer",
832
+ " DB_PASSWORD: ${ANSWERLAYER_POSTGRES_PASSWORD:?Set ANSWERLAYER_POSTGRES_PASSWORD}",
833
+ " DB_NAME: answerlayer",
834
+ "",
835
+ "services:",
836
+ " postgres:",
837
+ " image: postgres:14",
838
+ " environment:",
839
+ " POSTGRES_USER: answerlayer",
840
+ " POSTGRES_PASSWORD: ${ANSWERLAYER_POSTGRES_PASSWORD:?Set ANSWERLAYER_POSTGRES_PASSWORD}",
841
+ " POSTGRES_DB: answerlayer",
842
+ " volumes:",
843
+ " - postgres-data:/var/lib/postgresql/data",
844
+ " healthcheck:",
845
+ " test: [\"CMD-SHELL\", \"pg_isready -U answerlayer -d answerlayer\"]",
846
+ " interval: 5s",
847
+ " timeout: 5s",
848
+ " retries: 12",
849
+ " restart: unless-stopped",
850
+ " networks: [internal]",
851
+ "",
852
+ " migrate:",
853
+ " image: ${ANSWERLAYER_IMAGE:?Set ANSWERLAYER_IMAGE}",
854
+ " command: [\"alembic\", \"upgrade\", \"head\"]",
855
+ " environment:",
856
+ " <<: *answerlayer-database-environment",
857
+ " depends_on:",
858
+ " postgres:",
859
+ " condition: service_healthy",
860
+ " restart: \"no\"",
861
+ " networks: [internal]",
862
+ "",
863
+ " answerlayer:",
864
+ " image: ${ANSWERLAYER_IMAGE:?Set ANSWERLAYER_IMAGE}",
865
+ " environment:",
866
+ " <<: *answerlayer-database-environment",
867
+ " ENVIRONMENT: development",
868
+ " LOG_LEVEL: ${ANSWERLAYER_LOG_LEVEL:-INFO}",
869
+ " WEB_CONCURRENCY: ${ANSWERLAYER_WEB_CONCURRENCY:-1}",
870
+ " ENCRYPTION_KEY: ${ANSWERLAYER_ENCRYPTION_KEY:?Set ANSWERLAYER_ENCRYPTION_KEY}",
871
+ " ANTHROPIC_API_KEY: ${ANSWERLAYER_ANTHROPIC_API_KEY:-}",
872
+ " ALLOW_INTERNAL_AUTH: \"true\"",
873
+ " LOCAL_BOOTSTRAP_ENABLED: \"true\"",
874
+ " DEBUG_ENDPOINTS_ENABLED: \"false\"",
875
+ " EVAL_WORKER_ENABLED: \"false\"",
876
+ " RESULT_GC_INTERVAL_SECONDS: \"0\"",
877
+ " TELEMETRY_PUSH_INTERVAL_SECONDS: \"0\"",
878
+ " METER_SYNC_INTERVAL_SECONDS: \"0\"",
879
+ " FRONTEND_BASE_URL: http://127.0.0.1:${ANSWERLAYER_PORT:-8000}",
880
+ " CORS_ORIGINS: http://127.0.0.1:${ANSWERLAYER_PORT:-8000},http://localhost:${ANSWERLAYER_PORT:-8000}",
881
+ " ports:",
882
+ " - \"127.0.0.1:${ANSWERLAYER_PORT:-8000}:8000\"",
883
+ " depends_on:",
884
+ " postgres:",
885
+ " condition: service_healthy",
886
+ " migrate:",
887
+ " condition: service_completed_successfully",
888
+ " healthcheck:",
889
+ " test: [\"CMD\", \"curl\", \"--fail\", \"http://localhost:8000/readyz\"]",
890
+ " interval: 5s",
891
+ " timeout: 5s",
892
+ " start_period: 10s",
893
+ " retries: 12",
894
+ " restart: unless-stopped",
895
+ " networks: [internal]",
896
+ "",
897
+ "volumes:",
898
+ " postgres-data:",
899
+ " name: ${ANSWERLAYER_POSTGRES_VOLUME:-answerlayer-local-postgres-data}",
900
+ "",
901
+ "networks:",
902
+ " internal:",
903
+ " name: ${ANSWERLAYER_NETWORK:-answerlayer-local-network}",
904
+ ].join("\n");