backant-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,48 @@
1
+ import { Command } from "commander";
2
+ import { request, withServer } from "./data-exploration.js";
3
+ const secrets = new Command("secrets").description("Manage encrypted server environment secrets");
4
+ const targetOptions = (command) => command
5
+ .option("--server <id-or-name>", "Target server ID or accessible server name")
6
+ .option("--env <environment>", "Environment on the selected target (default: BESTUDIO_ENV or dev)")
7
+ .option("--local", "Target local BE Studio at http://localhost:3000")
8
+ .option("--url <apiUrl>", "API URL for a custom BE Studio instance; cannot be combined with --local")
9
+ .option("--token <token>", "Access token for this command; otherwise use saved target credentials");
10
+ targetOptions(secrets.command("list")).action(async (options) => {
11
+ try {
12
+ const ctx = await withServer(options);
13
+ const result = await request(ctx, `/system/servers/${encodeURIComponent(ctx.serverId)}/environments/${ctx.env}/secrets`);
14
+ console.log(JSON.stringify({ env: ctx.env, secrets: result.data.secrets }, null, 2));
15
+ }
16
+ catch (error) {
17
+ console.error("✖ " + error.message);
18
+ process.exitCode = 1;
19
+ }
20
+ });
21
+ targetOptions(secrets.command("set <name>").requiredOption("--from-env <variable>", "Read the secret from this local environment variable")).action(async (name, options) => {
22
+ try {
23
+ const value = process.env[options.fromEnv];
24
+ if (!value)
25
+ throw new Error("The requested environment variable is not set or empty.");
26
+ const ctx = await withServer(options);
27
+ const result = await request(ctx, `/system/servers/${encodeURIComponent(ctx.serverId)}/environments/${ctx.env}/secrets`, {
28
+ method: "PUT", body: JSON.stringify({ secrets: { [name]: value } }),
29
+ });
30
+ console.log("✔ Secret stored for " + ctx.env + ": " + result.data.configured.join(", "));
31
+ }
32
+ catch (error) {
33
+ console.error("✖ " + error.message);
34
+ process.exitCode = 1;
35
+ }
36
+ });
37
+ targetOptions(secrets.command("unset <name>")).action(async (name, options) => {
38
+ try {
39
+ const ctx = await withServer(options);
40
+ await request(ctx, `/system/servers/${encodeURIComponent(ctx.serverId)}/environments/${ctx.env}/secrets/${encodeURIComponent(name)}`, { method: "DELETE" });
41
+ console.log("✔ Secret removed for " + ctx.env + ": " + name);
42
+ }
43
+ catch (error) {
44
+ console.error("✖ " + error.message);
45
+ process.exitCode = 1;
46
+ }
47
+ });
48
+ export { secrets as secretsCommand };
@@ -0,0 +1,57 @@
1
+ import { Command } from "commander";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { installProjectSkills } from "../utils/skill-installer.js";
6
+ const skillDirectory = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../skills/bestudio");
7
+ const skillDocuments = {
8
+ main: "SKILL.md",
9
+ "project-definitions": path.join("references", "project-definitions.md"),
10
+ };
11
+ export function readSkillDocument(reference = "main") {
12
+ const documentPath = skillDocuments[reference];
13
+ if (!documentPath) {
14
+ throw new Error(`Unknown skill reference "${reference}". Available references: ${Object.keys(skillDocuments).join(", ")}`);
15
+ }
16
+ return fs.readFileSync(path.join(skillDirectory, documentPath), "utf8");
17
+ }
18
+ const showCommand = new Command("show")
19
+ .description("Print a bundled Backant agent skill document")
20
+ .option("--ref <name>", "Skill document to print (project-definitions)")
21
+ .action((options) => {
22
+ try {
23
+ process.stdout.write(readSkillDocument(options.ref ?? "main"));
24
+ }
25
+ catch (error) {
26
+ console.error(`✖ ${error.message || "Could not read skill document"}`);
27
+ process.exitCode = 1;
28
+ }
29
+ });
30
+ const syncCommand = new Command("sync")
31
+ .description("Install or update project-local Backant agent skills")
32
+ .option("--force", "Replace existing skill files, including user-modified files")
33
+ .action((options) => {
34
+ try {
35
+ const result = installProjectSkills(process.cwd(), { force: options.force });
36
+ if (result.created.length)
37
+ console.log(`✔ Created: ${result.created.join(", ")}`);
38
+ if (result.updated.length)
39
+ console.log(`✔ Updated: ${result.updated.join(", ")}`);
40
+ if (result.unchanged.length)
41
+ console.log(`✔ Already current: ${result.unchanged.join(", ")}`);
42
+ for (const skipped of result.skipped) {
43
+ console.warn(`⚠ Skipped ${skipped}. Use "backant skill sync --force" to replace an existing regular file.`);
44
+ }
45
+ if (!result.created.length && !result.updated.length && !result.unchanged.length && !result.skipped.length) {
46
+ console.log("✔ No project skill files found to sync.");
47
+ }
48
+ }
49
+ catch (error) {
50
+ console.error(`✖ ${error.message || "Could not sync project skills"}`);
51
+ process.exitCode = 1;
52
+ }
53
+ });
54
+ export const skillCommand = new Command("skill")
55
+ .description("Read bundled Backant agent skills")
56
+ .addCommand(showCommand)
57
+ .addCommand(syncCommand);
@@ -0,0 +1,312 @@
1
+ import { Command } from "commander";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { scanJobs } from "../utils/job-scanner.js";
5
+ import { scanServices } from "../utils/services-scanner.js";
6
+ import { scanAssets } from "../utils/assets-scanner.js";
7
+ import { scanModels } from "../utils/model-scanner.js";
8
+ import { scanFlows } from "../utils/flow-scanner.js";
9
+ import { calculateDomainHash, calculateAlgorithmHash, } from "../utils/hash-utils.js";
10
+ import { canonicalizeRoutes, canonicalizeJobs, canonicalizeModels, canonicalizeActions, } from "../utils/format-utils.js";
11
+ function loadConfig(projectRoot) {
12
+ const configPath = path.join(projectRoot, "bestudio.config.json");
13
+ if (!fs.existsSync(configPath)) {
14
+ throw new Error("bestudio.config.json not found");
15
+ }
16
+ let config;
17
+ try {
18
+ const content = fs.readFileSync(configPath, "utf-8");
19
+ config = JSON.parse(content);
20
+ }
21
+ catch (error) {
22
+ throw new Error(`Failed to parse bestudio.config.json: ${error.message}`);
23
+ }
24
+ if (!config.name) {
25
+ throw new Error("config.name is required");
26
+ }
27
+ return config;
28
+ }
29
+ function readRouteJson(routeJsonPath) {
30
+ if (!fs.existsSync(routeJsonPath)) {
31
+ return null;
32
+ }
33
+ try {
34
+ const content = fs.readFileSync(routeJsonPath, "utf-8");
35
+ return JSON.parse(content);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function getRelativePath(fullPath, projectRoot) {
42
+ return path.relative(projectRoot, fullPath).replace(/\\/g, "/");
43
+ }
44
+ function collectRouteJsonFiles(dir) {
45
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
46
+ const files = [];
47
+ for (const entry of entries) {
48
+ const fullPath = path.join(dir, entry.name);
49
+ if (entry.isDirectory()) {
50
+ files.push(...collectRouteJsonFiles(fullPath));
51
+ }
52
+ else if (entry.isFile() && entry.name === "route.json") {
53
+ files.push(fullPath);
54
+ }
55
+ }
56
+ return files;
57
+ }
58
+ function scanRoutes(projectRoot) {
59
+ const routesDir = path.join(projectRoot, "routes");
60
+ const routes = [];
61
+ if (!fs.existsSync(routesDir)) {
62
+ return routes;
63
+ }
64
+ const routeJsonPaths = collectRouteJsonFiles(routesDir);
65
+ for (let index = 0; index < routeJsonPaths.length; index++) {
66
+ const routeJsonPath = routeJsonPaths[index];
67
+ const routeJson = readRouteJson(routeJsonPath);
68
+ if (!routeJson ||
69
+ !routeJson.method ||
70
+ !routeJson.path ||
71
+ (!routeJson.action && !routeJson.flow)) {
72
+ continue;
73
+ }
74
+ // Generate route ID
75
+ const routeId = `${routeJson.method}:${routeJson.path}`;
76
+ // Calculate route.json relative path
77
+ const routeJsonRelativePath = getRelativePath(routeJsonPath, projectRoot);
78
+ if (routeJson.flow) {
79
+ routes.push({
80
+ id: routeId,
81
+ method: routeJson.method,
82
+ path: routeJson.path,
83
+ file: {
84
+ entry: routeJsonRelativePath,
85
+ },
86
+ flowId: routeJson.flow,
87
+ ...(routeJson.metadata && { metadata: routeJson.metadata }),
88
+ });
89
+ continue;
90
+ }
91
+ // Resolve action path relative to route.json location
92
+ const actionFullPath = path.resolve(path.dirname(routeJsonPath), routeJson.action);
93
+ const actionRelativePath = getRelativePath(actionFullPath, projectRoot);
94
+ // Generate actionId from route ID
95
+ const actionId = `action-${routeId}`;
96
+ routes.push({
97
+ id: routeId,
98
+ method: routeJson.method,
99
+ path: routeJson.path,
100
+ file: {
101
+ entry: routeJsonRelativePath,
102
+ },
103
+ actionId,
104
+ ...(routeJson.metadata && { metadata: routeJson.metadata }),
105
+ });
106
+ }
107
+ return routes;
108
+ }
109
+ function scanActions(projectRoot) {
110
+ const routesDir = path.join(projectRoot, "routes");
111
+ const actionsMap = new Map();
112
+ if (!fs.existsSync(routesDir)) {
113
+ return undefined;
114
+ }
115
+ const routeJsonPaths = collectRouteJsonFiles(routesDir);
116
+ for (const routeJsonPath of routeJsonPaths) {
117
+ const routeJson = readRouteJson(routeJsonPath);
118
+ if (!routeJson ||
119
+ !routeJson.method ||
120
+ !routeJson.path ||
121
+ !routeJson.action) {
122
+ continue;
123
+ }
124
+ // Resolve action path relative to route.json location
125
+ const actionFullPath = path.resolve(path.dirname(routeJsonPath), routeJson.action);
126
+ if (!fs.existsSync(actionFullPath)) {
127
+ continue;
128
+ }
129
+ // Generate route ID and action ID
130
+ const routeId = `${routeJson.method}:${routeJson.path}`;
131
+ const actionId = `action-${routeId}`;
132
+ // Read action source
133
+ const actionSource = fs.readFileSync(actionFullPath, "utf-8");
134
+ // Try to read config.ts if it exists
135
+ const actionDir = path.dirname(actionFullPath);
136
+ const configPath = path.join(actionDir, "config.ts");
137
+ const configCode = fs.existsSync(configPath)
138
+ ? fs.readFileSync(configPath, "utf-8")
139
+ : undefined;
140
+ // Calculate action.ts relative path
141
+ const actionRelativePath = getRelativePath(actionFullPath, projectRoot);
142
+ // Add action to map (deduplicate by actionId)
143
+ if (!actionsMap.has(actionId)) {
144
+ actionsMap.set(actionId, {
145
+ id: actionId,
146
+ code: actionSource,
147
+ file: {
148
+ entry: actionRelativePath,
149
+ },
150
+ ...(configCode && { configCode }),
151
+ });
152
+ }
153
+ }
154
+ return actionsMap.size > 0
155
+ ? Array.from(actionsMap.values()).sort((a, b) => a.id.localeCompare(b.id))
156
+ : undefined;
157
+ }
158
+ export function generateSnapshot(projectRoot) {
159
+ const config = loadConfig(projectRoot);
160
+ // Load existing snapshot to preserve metadata fields
161
+ const existingSnapshotPath = path.join(projectRoot, ".bestudio", "snapshot.json");
162
+ let existingSnapshot = null;
163
+ if (fs.existsSync(existingSnapshotPath)) {
164
+ try {
165
+ const content = fs.readFileSync(existingSnapshotPath, "utf-8");
166
+ existingSnapshot = JSON.parse(content);
167
+ }
168
+ catch {
169
+ // Parse error - ignore and continue
170
+ }
171
+ }
172
+ const routes = scanRoutes(projectRoot);
173
+ const actions = scanActions(projectRoot);
174
+ const jobsRaw = scanJobs(projectRoot);
175
+ const services = scanServices(projectRoot);
176
+ const assets = scanAssets(projectRoot);
177
+ const modelsRaw = scanModels(projectRoot);
178
+ const flowsRaw = scanFlows(projectRoot);
179
+ // Add file.entry to flows
180
+ const flows = flowsRaw.map((f) => ({
181
+ id: f.id,
182
+ name: f.name,
183
+ flow: f.flow,
184
+ file: {
185
+ entry: f.filePath,
186
+ },
187
+ }));
188
+ // Add file.entry to jobs
189
+ const jobs = jobsRaw.map((job) => ({
190
+ id: job.id,
191
+ code: job.code,
192
+ file: {
193
+ entry: job.filePath,
194
+ },
195
+ }));
196
+ // Add file.entry to models
197
+ const models = modelsRaw.map((model) => ({
198
+ ...model,
199
+ file: {
200
+ entry: model.filePath,
201
+ },
202
+ }));
203
+ // Convert routes to hash format (with actionId instead of action.file)
204
+ // For hash calculation, we need routes with actionId references
205
+ const routesForHash = routes.map((route) => {
206
+ // For flow routes, actionId is empty
207
+ const actionId = route.flowId ? "" : (route.actionId || `action-${route.id}`);
208
+ return {
209
+ id: route.id,
210
+ method: route.method,
211
+ path: route.path,
212
+ actionId,
213
+ file: route.file,
214
+ };
215
+ });
216
+ // Calculate hashes
217
+ // Routes hash includes only route metadata (method, path, actionId)
218
+ const routesHash = calculateDomainHash("routes", routesForHash);
219
+ // Actions hash includes action code
220
+ const actionsHash = actions
221
+ ? calculateDomainHash("actions", actions)
222
+ : undefined;
223
+ // Jobs hash (include file.entry)
224
+ const jobsHash = jobs.length > 0 ? calculateDomainHash("jobs", jobs) : undefined;
225
+ // Models hash
226
+ const modelsHash = models.length > 0 ? calculateDomainHash("models", models) : undefined;
227
+ const algorithmHash = calculateAlgorithmHash();
228
+ const snapshot = {
229
+ snapshotFormatVersion: 1,
230
+ project: {
231
+ name: config.name,
232
+ },
233
+ ...(config.applicationAuth && { applicationAuth: config.applicationAuth }),
234
+ routes: canonicalizeRoutes(routes),
235
+ actions: actions ? canonicalizeActions(actions) : undefined,
236
+ jobs: jobs.length > 0 ? canonicalizeJobs(jobs) : undefined,
237
+ services: services || undefined,
238
+ assets: assets || undefined,
239
+ models: models.length > 0 ? canonicalizeModels(models) : undefined,
240
+ flows: flows.length > 0 ? flows : undefined,
241
+ hashes: {
242
+ routes: routesHash,
243
+ ...(actionsHash && { actions: actionsHash }),
244
+ ...(jobsHash && { jobs: jobsHash }),
245
+ ...(modelsHash && { models: modelsHash }),
246
+ algorithm: algorithmHash,
247
+ },
248
+ };
249
+ // Preserve metadata fields from existing snapshot
250
+ if (existingSnapshot) {
251
+ if (existingSnapshot.serverId) {
252
+ snapshot.serverId = existingSnapshot.serverId;
253
+ }
254
+ if (existingSnapshot.version !== undefined) {
255
+ snapshot.version = existingSnapshot.version;
256
+ }
257
+ if (existingSnapshot.pushedAt) {
258
+ snapshot.pushedAt = existingSnapshot.pushedAt;
259
+ }
260
+ if (existingSnapshot.createdAt) {
261
+ snapshot.createdAt = existingSnapshot.createdAt;
262
+ }
263
+ }
264
+ return snapshot;
265
+ }
266
+ function writeSnapshot(snapshot, outputPath) {
267
+ const outputDir = path.dirname(outputPath);
268
+ // Create .bestudio directory if it doesn't exist
269
+ if (!fs.existsSync(outputDir)) {
270
+ fs.mkdirSync(outputDir, { recursive: true });
271
+ }
272
+ fs.writeFileSync(outputPath, JSON.stringify(snapshot, null, 2), "utf-8");
273
+ }
274
+ function runSnapshot(options) {
275
+ const projectRoot = process.cwd();
276
+ const outputPath = options.out
277
+ ? path.resolve(projectRoot, options.out)
278
+ : path.join(projectRoot, ".bestudio", "snapshot.json");
279
+ console.log("📦 Generating snapshot...");
280
+ let snapshot;
281
+ try {
282
+ snapshot = generateSnapshot(projectRoot);
283
+ writeSnapshot(snapshot, outputPath);
284
+ }
285
+ catch (error) {
286
+ console.error(`✖ ${error.message || "Failed to generate snapshot"}`);
287
+ process.exit(1);
288
+ }
289
+ const relativeOutputPath = path
290
+ .relative(projectRoot, outputPath)
291
+ .replace(/\\/g, "/");
292
+ console.log(`✔ Routes scanned: ${snapshot.routes.length}`);
293
+ console.log(`✔ Jobs scanned: ${snapshot.jobs?.length || 0}`);
294
+ if (snapshot.services) {
295
+ const serviceNames = Object.keys(snapshot.services);
296
+ console.log(`✔ Services scanned: ${serviceNames.length} (${serviceNames.join(", ")})`);
297
+ }
298
+ if (snapshot.assets) {
299
+ console.log(`✔ Assets config scanned`);
300
+ }
301
+ console.log(`✔ Models scanned: ${snapshot.models?.length || 0}`);
302
+ console.log(`✔ Flows scanned: ${snapshot.flows?.length || 0}`);
303
+ console.log(`✔ Snapshot written: ${relativeOutputPath}`);
304
+ }
305
+ export const snapshotCommand = new Command("snapshot")
306
+ .option("--out <file>", "Output file path (default: .bestudio/snapshot.json)")
307
+ .description("Generate BE Studio project snapshot")
308
+ .addHelpText("after", `
309
+ Example:
310
+ backant snapshot --out .bestudio/snapshot.json
311
+ `)
312
+ .action(runSnapshot);