@auracheck-ai/cli 0.2.3 → 0.2.5

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/dist/bin.js CHANGED
@@ -1,152 +1,3582 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from 'node:module';
3
- import path from 'node:path';
4
- import { Command } from 'commander';
5
- import pc from 'picocolors';
6
- import { doctorCommand } from './commands/doctor.js';
7
- import { initCommand } from './commands/init.js';
8
- import { authStatusCommand, loginCommand, logoutCommand, } from './commands/login.js';
9
- import { setupCommand } from './commands/setup.js';
10
- import { statusCommand } from './commands/status.js';
11
- import { runMcpServer } from './mcp/server.js';
12
- // Single-source the version from package.json. It used to be typed here as
13
- // well, and the two drifted: the published npm package said 0.1.7 while
14
- // `sixseven --version` still claimed 0.1.4, which makes "which build is this?"
15
- // unanswerable exactly when a user is reporting an MCP bug.
16
- const { version } = createRequire(import.meta.url)('../package.json');
17
- /**
18
- * `auracheck` is the published command (the `sixseven` alias was dropped in
19
- * 0.2.3 because it collided with the old @sixseven-ai/cli global install).
20
- * Show whichever name the person actually typed in --help/usage output.
21
- */
22
- function invokedCommandName() {
23
- const argv1 = process.argv[1] ?? '';
24
- const base = path.basename(argv1).replace(/\.(c|m)?js$/, '');
25
- return base === 'sixseven' ? 'sixseven' : 'auracheck';
2
+
3
+ // src/bin.ts
4
+ import path5 from "path";
5
+ import { Command } from "commander";
6
+ import pc6 from "picocolors";
7
+
8
+ // src/commands/doctor.ts
9
+ import pc from "picocolors";
10
+ import { fetch as fetch2 } from "undici";
11
+
12
+ // ../mcp-core/dist/api.js
13
+ var ApiError = class extends Error {
14
+ status;
15
+ bodyText;
16
+ constructor(status, bodyText, message) {
17
+ super(message);
18
+ this.status = status;
19
+ this.bodyText = bodyText;
20
+ this.name = "ApiError";
21
+ }
22
+ };
23
+ var DEFAULT_SIGN_IN_HINT = "Sign in again.";
24
+ function authHint(status, serverError, signInHint = DEFAULT_SIGN_IN_HINT) {
25
+ if (status === 401) {
26
+ return `Your AuraCheck sign-in is missing, expired or revoked. ${signInHint}`;
27
+ }
28
+ if (status === 403 && /limited to another project/i.test(serverError)) {
29
+ return "This token is a project CI token and only reaches its own project. Sign in personally, or pass that projectId.";
30
+ }
31
+ return null;
26
32
  }
27
- async function main() {
28
- const program = new Command();
29
- program
30
- .name(invokedCommandName())
31
- .description('AuraCheck CLI — login, init repo, and run an MCP server so Claude Code can author whitebox testcases against your app. (`sixseven` also works, same command.)')
32
- .version(version);
33
- program
34
- .command('setup')
35
- .description('Guided wizard: login → bind project → register MCP with Claude Code in one go')
36
- .option('--base-url <url>', 'SixSeven base URL')
37
- .option('--token <token>', 'CI token starting with 67ci_')
38
- .option('--project-id <id>', 'SixSeven project id')
39
- .option('--skip-mcp', 'do not register the MCP server')
40
- .option('--non-interactive', 'fail instead of prompting')
41
- .action(async (opts) => {
42
- await setupCommand({
43
- baseUrl: opts.baseUrl,
44
- token: opts.token,
45
- projectId: opts.projectId,
46
- skipMcp: !!opts.skipMcp,
47
- nonInteractive: !!opts.nonInteractive,
48
- });
33
+ function normalizeBaseUrl(u) {
34
+ return u.replace(new RegExp("\\p{Cc}", "gu"), "").trim().replace(/\/+$/, "");
35
+ }
36
+ function normalizeStepsToYaml(steps, caseName = "") {
37
+ if (typeof steps === "string")
38
+ return steps;
39
+ if (Array.isArray(steps)) {
40
+ return JSON.stringify({
41
+ tasks: [{ name: caseName || "Main flow", flow: steps }]
49
42
  });
50
- const loginOptions = (cmd) => cmd
51
- .option('--base-url <url>', 'AuraCheck base URL (default: last login, else https://space.auracheck.ai.id)')
52
- .option('--token <token>', 'use a CI token (67ci_…) instead of the browser sign-in — for CI')
53
- .option('--paste-token', 'prompt for a CI token instead of the browser')
54
- .option('--no-browser', 'print the sign-in link instead of opening it')
55
- .option('--label <name>', 'name shown under Active devices')
56
- .option('--non-interactive', 'fail instead of prompting');
57
- const runLogin = async (opts) => {
58
- await loginCommand({
59
- baseUrl: opts.baseUrl,
60
- token: opts.token,
61
- promptToken: !!opts.pasteToken,
62
- noBrowser: opts.browser === false,
63
- label: opts.label,
64
- nonInteractive: !!opts.nonInteractive,
65
- });
43
+ }
44
+ if (steps && typeof steps === "object") {
45
+ const obj = steps;
46
+ if (Array.isArray(obj.tasks))
47
+ return JSON.stringify(obj);
48
+ if (Array.isArray(obj.flow)) {
49
+ return JSON.stringify({
50
+ tasks: [{ name: caseName || "Main flow", flow: obj.flow }]
51
+ });
52
+ }
53
+ }
54
+ throw new Error('steps must be a YAML string, an array of Midscene flow items (e.g. [{ aiTap: "Sign in" }, { aiInput: "user@example.com", locate: "Email field" }]), or an object with a tasks[] array.');
55
+ }
56
+ var AuraCheckApi = class {
57
+ baseUrl;
58
+ token;
59
+ timeoutMs;
60
+ fetchImpl;
61
+ extraHeaders;
62
+ dispatcher;
63
+ signInHint;
64
+ constructor(opts) {
65
+ this.baseUrl = normalizeBaseUrl(opts.baseUrl);
66
+ this.token = opts.token;
67
+ this.timeoutMs = opts.timeoutMs ?? 3e4;
68
+ this.fetchImpl = opts.fetchImpl ?? fetch;
69
+ this.extraHeaders = opts.extraHeaders ?? {};
70
+ this.dispatcher = opts.dispatcher;
71
+ this.signInHint = opts.signInHint ?? DEFAULT_SIGN_IN_HINT;
72
+ }
73
+ /** Spreads `{ dispatcher }` into a fetch init only when one was given. */
74
+ dispatcherInit() {
75
+ return this.dispatcher ? { dispatcher: this.dispatcher } : {};
76
+ }
77
+ async request(method, path6, body) {
78
+ const url = `${this.baseUrl}${path6}`;
79
+ const headers = {
80
+ Authorization: `Bearer ${this.token}`,
81
+ Accept: "application/json",
82
+ ...this.extraHeaders
66
83
  };
67
- loginOptions(program
68
- .command('login')
69
- .description('Sign in through your browser (or with --token for CI); the CLI and MCP server use it')).action(runLogin);
70
- program
71
- .command('logout')
72
- .description('Revoke this sign-in and forget the saved token')
73
- .option('--base-url <url>', 'AuraCheck base URL')
74
- .action(async (opts) => {
75
- await logoutCommand({ baseUrl: opts.baseUrl });
76
- });
77
- const auth = program
78
- .command('auth')
79
- .description('Sign-in commands: `auth status`, `auth login`, `auth logout`; `auth --token <t>` saves a CI token')
80
- .option('--base-url <url>', 'AuraCheck base URL')
81
- .option('--token <token>', 'save a CI token (67ci_…) for this base URL')
82
- .action(async (opts) => {
83
- if (opts.token) {
84
- await loginCommand({
85
- baseUrl: opts.baseUrl,
86
- token: opts.token,
87
- nonInteractive: true,
88
- });
89
- return;
84
+ let payload;
85
+ if (body !== void 0) {
86
+ headers["Content-Type"] = "application/json";
87
+ payload = JSON.stringify(body);
88
+ }
89
+ const controller = new AbortController();
90
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
91
+ let res;
92
+ try {
93
+ res = await this.fetchImpl(url, {
94
+ method,
95
+ headers,
96
+ body: payload,
97
+ signal: controller.signal,
98
+ ...this.dispatcherInit()
99
+ });
100
+ } catch (err) {
101
+ throw new ApiError(0, "", `Network error calling ${url}: ${err.message}`);
102
+ } finally {
103
+ clearTimeout(timer);
104
+ }
105
+ const text = await res.text();
106
+ if (!res.ok) {
107
+ let msg = `${method} ${path6} -> ${res.status}`;
108
+ let serverError = "";
109
+ try {
110
+ const parsed = JSON.parse(text);
111
+ if (parsed?.error)
112
+ serverError = String(parsed.error);
113
+ } catch {
114
+ serverError = text.slice(0, 200);
115
+ }
116
+ if (serverError)
117
+ msg += `: ${serverError}`;
118
+ const hint = authHint(res.status, serverError, this.signInHint);
119
+ if (hint)
120
+ msg += `. ${hint}`;
121
+ throw new ApiError(res.status, text, msg);
122
+ }
123
+ if (!text)
124
+ return void 0;
125
+ try {
126
+ return JSON.parse(text);
127
+ } catch {
128
+ return text;
129
+ }
130
+ }
131
+ // --- Auth ---
132
+ async me() {
133
+ return this.request("GET", "/api/auth/me");
134
+ }
135
+ // --- MCP context (role/subscription awareness; §3.4) ---
136
+ async mcpContext() {
137
+ return this.request("GET", "/api/mcp/context");
138
+ }
139
+ // --- Projects ---
140
+ async listProjects() {
141
+ return this.request("GET", "/api/projects");
142
+ }
143
+ async getProject(projectId) {
144
+ return this.request("GET", `/api/projects/${projectId}`);
145
+ }
146
+ async createProject(input) {
147
+ return this.request("POST", "/api/projects", input);
148
+ }
149
+ // --- Features ---
150
+ async listFeatures(projectId) {
151
+ return this.request("GET", `/api/projects/${projectId}/features`);
152
+ }
153
+ async createFeature(projectId, input) {
154
+ return this.request("POST", `/api/projects/${projectId}/features`, input);
155
+ }
156
+ /** There is no `GET /api/features/:id`; look it up via the project's list. */
157
+ async getFeature(id, projectId) {
158
+ const all = await this.listFeatures(projectId);
159
+ return all.find((f) => f.id === id) ?? null;
160
+ }
161
+ /**
162
+ * Delete a feature. Not a blanket cascade: its own test cases that are
163
+ * linked to a run are soft-deleted (reparented onto the feature's parent,
164
+ * run history intact) while unlinked ones are hard-deleted; descendant
165
+ * features are removed once their cases are cleared. `cascade` also
166
+ * removes any sub-features (same per-case split applies to their cases).
167
+ */
168
+ async deleteFeature(id, cascade = false) {
169
+ const qs = cascade ? "?cascade=true" : "";
170
+ await this.request("DELETE", `/api/features/${id}${qs}`);
171
+ }
172
+ // --- Test cases ---
173
+ async listTestCasesByProject(projectId, platform) {
174
+ const qs = platform ? `?platform=${encodeURIComponent(platform)}` : "";
175
+ return this.request("GET", `/api/projects/${projectId}/test-cases${qs}`);
176
+ }
177
+ async listTestCasesByFeature(featureId) {
178
+ return this.request("GET", `/api/features/${featureId}/test-cases`);
179
+ }
180
+ async createTestCase(featureId, input) {
181
+ const body = {
182
+ ...input,
183
+ steps: normalizeStepsToYaml(input.steps, input.name),
184
+ executionType: input.executionType ?? "automation"
185
+ };
186
+ return this.request("POST", `/api/features/${featureId}/test-cases`, body);
187
+ }
188
+ /**
189
+ * Fetch one test case. There is no `GET /api/test-cases/:id` on the server
190
+ * — only PUT, DELETE and sub-routes — so this reads via the project list.
191
+ */
192
+ async getTestCase(id, projectId) {
193
+ const all = await this.listTestCasesByProject(projectId);
194
+ const found = all.find((c) => c.id === id);
195
+ if (!found) {
196
+ throw new ApiError(404, "", `Test case ${id} not found in project ${projectId}`);
197
+ }
198
+ return found;
199
+ }
200
+ /**
201
+ * Patch a test case. PUT, not PATCH: the server defines no PATCH handler
202
+ * for this path, while its PUT handler is explicitly partial.
203
+ */
204
+ async updateTestCase(id, patch) {
205
+ const body = patch && typeof patch === "object" && patch.steps !== void 0 ? {
206
+ ...patch,
207
+ steps: normalizeStepsToYaml(patch.steps, typeof patch.name === "string" ? patch.name : "")
208
+ } : patch;
209
+ return this.request("PUT", `/api/test-cases/${id}`, body);
210
+ }
211
+ /**
212
+ * Delete test cases. A single id goes through `DELETE /api/test-cases/:id`;
213
+ * several go through `DELETE /api/test-cases/bulk` (max 500 ids). Either
214
+ * way the server splits per case: one already linked to a run is
215
+ * soft-deleted, an unlinked one is hard-deleted.
216
+ */
217
+ async deleteTestCases(ids) {
218
+ if (ids.length === 1) {
219
+ await this.request("DELETE", `/api/test-cases/${ids[0]}`);
220
+ return { hardDeleted: null, softDeleted: null };
221
+ }
222
+ return this.request("DELETE", "/api/test-cases/bulk", { ids });
223
+ }
224
+ // --- Prompt-to-test (test_my_flow) ---
225
+ async previewPromptTest(projectId, input) {
226
+ return this.request("POST", `/api/projects/${projectId}/prompt-tests/preview`, input);
227
+ }
228
+ async createPromptTestRun(projectId, input) {
229
+ return this.request("POST", `/api/projects/${projectId}/prompt-tests`, {
230
+ url: input.url,
231
+ prompt: input.prompt,
232
+ plan: input.plan
233
+ });
234
+ }
235
+ // --- Runs ---
236
+ async listRuns(projectId, platform) {
237
+ const qs = platform ? `?platform=${encodeURIComponent(platform)}` : "";
238
+ return this.request("GET", `/api/projects/${projectId}/runs${qs}`);
239
+ }
240
+ async createRun(projectId, input) {
241
+ return this.request("POST", `/api/projects/${projectId}/runs`, input);
242
+ }
243
+ async getRun(runId) {
244
+ return this.request("GET", `/api/runs/${runId}`);
245
+ }
246
+ /** Result buckets the Run Report shows (bugs / script issues / blocked / passed). */
247
+ async getRunReportBuckets(runId) {
248
+ return this.request("GET", `/api/runs/${runId}/report-buckets`);
249
+ }
250
+ async getRunCaseStatusCounts(runId) {
251
+ return this.request("GET", `/api/runs/${runId}/case-status-counts`);
252
+ }
253
+ async executeRun(runId) {
254
+ return this.request("POST", `/api/runs/${runId}/execute`, {});
255
+ }
256
+ async cancelRun(runId) {
257
+ return this.request("POST", `/api/runs/${runId}/cancel`, {});
258
+ }
259
+ async listRunTestCases(runId) {
260
+ return this.request("GET", `/api/runs/${runId}/test-cases`);
261
+ }
262
+ async listRunCaseAttempts(runId) {
263
+ return this.request("GET", `/api/runs/${runId}/case-attempts`);
264
+ }
265
+ async listRunStepEvents(runId, testCaseId) {
266
+ const qs = testCaseId ? `?testCaseId=${encodeURIComponent(testCaseId)}` : "";
267
+ return this.request("GET", `/api/runs/${runId}/events${qs}`);
268
+ }
269
+ // --- Schedules (recurring runs) ---
270
+ async listSchedules(projectId) {
271
+ return this.request("GET", `/api/projects/${projectId}/schedules`);
272
+ }
273
+ async createSchedule(projectId, input) {
274
+ return this.request("POST", `/api/projects/${projectId}/schedules`, input);
275
+ }
276
+ async getSchedule(id) {
277
+ return this.request("GET", `/api/schedules/${id}`);
278
+ }
279
+ async updateSchedule(id, patch) {
280
+ return this.request("PATCH", `/api/schedules/${id}`, patch);
281
+ }
282
+ /** Server replies 204 with no body; resolves to void on success. */
283
+ async deleteSchedule(id) {
284
+ await this.request("DELETE", `/api/schedules/${id}`);
285
+ }
286
+ async listScheduleFires(id, page) {
287
+ const qs = page && page > 1 ? `?page=${page}` : "";
288
+ return this.request("GET", `/api/schedules/${id}/fires${qs}`);
289
+ }
290
+ async listScheduleRecipients(projectId) {
291
+ return this.request("GET", `/api/projects/${projectId}/schedules/assignable-users`);
292
+ }
293
+ /**
294
+ * Fire a schedule immediately. The route answers 202 for `run_created` and
295
+ * 409 for every skip (`skipped_overlap` above all). A skip is a real,
296
+ * informative answer, not a transport failure, so it is unwrapped back
297
+ * into a normal result; only a genuine error (404, 500, network) still
298
+ * throws.
299
+ */
300
+ async runScheduleNow(id) {
301
+ try {
302
+ const res = await this.request("POST", `/api/schedules/${id}/run-now`, {});
303
+ return { outcome: res.outcome, skipped: false };
304
+ } catch (err) {
305
+ if (err instanceof ApiError && err.status === 409) {
306
+ try {
307
+ const parsed = JSON.parse(err.bodyText);
308
+ if (parsed?.outcome)
309
+ return { outcome: parsed.outcome, skipped: true };
310
+ } catch {
90
311
  }
91
- await authStatusCommand({ baseUrl: opts.baseUrl });
92
- });
93
- auth
94
- .command('status')
95
- .description('Show who the CLI/MCP is signed in as (never prints the token)')
96
- .option('--base-url <url>', 'AuraCheck base URL')
97
- .action(async (opts, cmd) => {
98
- await authStatusCommand({
99
- baseUrl: opts.baseUrl ?? cmd.parent?.opts().baseUrl,
312
+ }
313
+ throw err;
314
+ }
315
+ }
316
+ // --- Issue reports (bugs) ---
317
+ async createIssueReport(input) {
318
+ return this.request("POST", "/api/issue-reports", input);
319
+ }
320
+ async listIssueReports(projectId) {
321
+ const qs = projectId ? `?projectId=${encodeURIComponent(projectId)}` : "";
322
+ const resp = await this.request("GET", `/api/issue-reports${qs}`);
323
+ if (Array.isArray(resp))
324
+ return resp;
325
+ return resp.reports ?? [];
326
+ }
327
+ async getIssueReport(id) {
328
+ return this.request("GET", `/api/issue-reports/${id}`);
329
+ }
330
+ // --- Exploration ---
331
+ async startExploration(projectId, input) {
332
+ return this.request("POST", `/api/projects/${projectId}/explore`, input);
333
+ }
334
+ async getExploration(projectId) {
335
+ return this.request("GET", `/api/projects/${projectId}/explore`);
336
+ }
337
+ /**
338
+ * Fetch an authenticated blob (screenshot, report) and return its raw
339
+ * bytes. No filesystem here — a Worker has none. Callers that want a file
340
+ * on disk (the local stdio adapter) write the bytes themselves.
341
+ *
342
+ * `urlOrPath` accepts a bare path (as returned by get_evidence) or an
343
+ * absolute URL — but only on the bound host. A URL elsewhere is refused
344
+ * rather than followed, because following it would hand the bearer token
345
+ * to whatever host the caller named.
346
+ */
347
+ async downloadBlob(urlOrPath) {
348
+ let pathPart;
349
+ if (/^https?:\/\//i.test(urlOrPath)) {
350
+ const given = new URL(urlOrPath);
351
+ const bound = new URL(this.baseUrl);
352
+ if (given.host !== bound.host) {
353
+ throw new ApiError(0, "", `Refusing to download from host ${given.host}: only ${bound.host} is bound`);
354
+ }
355
+ pathPart = `${given.pathname}${given.search}`;
356
+ } else {
357
+ pathPart = urlOrPath.startsWith("/") ? urlOrPath : `/${urlOrPath}`;
358
+ }
359
+ const url = `${this.baseUrl}${pathPart}`;
360
+ let res;
361
+ try {
362
+ res = await this.fetchImpl(url, {
363
+ method: "GET",
364
+ headers: {
365
+ Authorization: `Bearer ${this.token}`,
366
+ ...this.extraHeaders
367
+ },
368
+ ...this.dispatcherInit()
369
+ });
370
+ } catch (err) {
371
+ throw new ApiError(0, "", `Network error calling ${url}: ${err.message}`);
372
+ }
373
+ if (!res.ok) {
374
+ const text = await res.text().catch(() => "");
375
+ throw new ApiError(res.status, text, `GET ${pathPart} -> ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
376
+ }
377
+ const buf = new Uint8Array(await res.arrayBuffer());
378
+ if (buf.length === 0) {
379
+ throw new ApiError(res.status, "", `GET ${pathPart} returned an empty body`);
380
+ }
381
+ return {
382
+ bytes: buf,
383
+ contentType: res.headers.get("content-type") ?? "application/octet-stream"
384
+ };
385
+ }
386
+ };
387
+ var TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
388
+ "passed",
389
+ "failed",
390
+ "cancelled",
391
+ "error"
392
+ ]);
393
+
394
+ // ../mcp-core/dist/context.js
395
+ function requireProjectId(ctx, explicit) {
396
+ const id = explicit?.trim() || ctx.projectId;
397
+ if (!id) {
398
+ throw new Error("No AuraCheck project for this call: pass `projectId` (find it with list_projects), or call set_project first.");
399
+ }
400
+ return id;
401
+ }
402
+
403
+ // ../mcp-core/dist/errors.js
404
+ function parseBody(bodyText) {
405
+ try {
406
+ return JSON.parse(bodyText);
407
+ } catch {
408
+ return {};
409
+ }
410
+ }
411
+ function contactName(contact) {
412
+ return contact.name ?? contact.email;
413
+ }
414
+ var CAPABILITY_LABELS = {
415
+ viewProject: "View project",
416
+ viewReports: "View reports",
417
+ manageTestCases: "Manage test cases",
418
+ manageRuns: "Manage runs",
419
+ runTests: "Run tests",
420
+ manageProjectSetup: "Manage project setup",
421
+ manageBugs: "Manage bugs"
422
+ };
423
+ function capabilityLabel(cap) {
424
+ if (!cap)
425
+ return "this action";
426
+ return CAPABILITY_LABELS[cap] ?? cap;
427
+ }
428
+ function mapApiError(err, ctx, requiresCapability) {
429
+ const body = parseBody(err.bodyText);
430
+ const account = ctx.account;
431
+ switch (err.status) {
432
+ case 402: {
433
+ if (body.isCompanyAdmin ?? isCompanyAdminRole(account)) {
434
+ return {
435
+ blocked: true,
436
+ message: `Your AuraCheck plan has ended, so new runs are paused. Your existing runs and reports are still available. Renew here: ${ctx.renewalUrl}`
437
+ };
438
+ }
439
+ const contact = body.adminContact ?? account?.adminContact ?? null;
440
+ return {
441
+ blocked: true,
442
+ message: contact ? `Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin ${contactName(contact)} (${contact.email}) to renew. Existing results are still available.` : "Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin to renew. Existing results are still available."
443
+ };
444
+ }
445
+ case 429: {
446
+ const text = body.error ?? "";
447
+ const isConcurrent = /concurrent|already in progress|1 at a time/i.test(text);
448
+ if (isConcurrent) {
449
+ return {
450
+ blocked: true,
451
+ message: "A run is already in progress (trials run 1 at a time). I'll wait for it to finish, then start yours."
452
+ };
453
+ }
454
+ const isAdmin = body.isCompanyAdmin ?? isCompanyAdminRole(account);
455
+ const limit = account?.subscription.runUsage?.dailyLimit;
456
+ const limitClause = limit ? `Your trial allows ${limit} runs per day and today's are used up.` : "Your trial's daily run cap is used up.";
457
+ const contact = body.adminContact ?? account?.adminContact ?? null;
458
+ const actionClause = isAdmin ? `Upgrade to remove the daily cap: ${ctx.renewalUrl}` : contact ? `Ask ${contactName(contact)} to upgrade.` : "Ask your admin to upgrade.";
459
+ return {
460
+ blocked: true,
461
+ message: `${limitClause} It resets at 07:00 WIB. ${actionClause}`
462
+ };
463
+ }
464
+ case 403: {
465
+ if (/project CI token/i.test(body.error ?? "")) {
466
+ return {
467
+ blocked: true,
468
+ message: "This token can only reach its own project. Sign in personally, or pass that projectId."
469
+ };
470
+ }
471
+ const roleLabel = account?.user.roleLabel ?? "your role";
472
+ return {
473
+ blocked: true,
474
+ message: `Your AuraCheck role (${roleLabel}) can't do that. Ask your admin to give you the '${capabilityLabel(requiresCapability)}' permission.`
475
+ };
476
+ }
477
+ case 401: {
478
+ if (ctx.surface === "local")
479
+ return null;
480
+ return {
481
+ blocked: true,
482
+ message: "This AI app was disconnected from AuraCheck. Reconnect it from the app\u2019s connector settings."
483
+ };
484
+ }
485
+ default:
486
+ return null;
487
+ }
488
+ }
489
+ function isCompanyAdminRole(account) {
490
+ const caps = account?.user.capabilities ?? [];
491
+ const label = account?.user.roleLabel?.toLowerCase() ?? "";
492
+ return label.includes("admin") || caps.includes("manageProjectSetup");
493
+ }
494
+ var MOBILE_RUN_NEXT_STEP = 'Ask the person to open this run in the AuraCheck desktop app with the Android device or emulator connected and click "Run on local" (iOS: macOS desktop app, "Run on iOS"). Then call wait_for_run: it waits while the run is pending.';
495
+ function runFromDesktopAnswer(err, runId) {
496
+ if (err.status !== 422)
497
+ return null;
498
+ let body = {};
499
+ try {
500
+ body = JSON.parse(err.bodyText);
501
+ } catch {
502
+ return null;
503
+ }
504
+ if (body.code !== "run_from_desktop")
505
+ return null;
506
+ return {
507
+ started: false,
508
+ status: "run_from_desktop",
509
+ runId,
510
+ platform: body.platform ?? null,
511
+ runUrl: body.runUrl ?? null,
512
+ message: body.error ?? null,
513
+ next: MOBILE_RUN_NEXT_STEP
514
+ };
515
+ }
516
+ function graceNotice(graceEnd, renewalUrl) {
517
+ return `Heads-up: payment is overdue; runs keep working until ${graceEnd ?? "the grace period ends"}. Renew here: ${renewalUrl}`;
518
+ }
519
+
520
+ // ../mcp-core/dist/knowledge.js
521
+ var SERVER_INSTRUCTIONS = `You are connected to AuraCheck, an AI testing service that runs real browser tests on the user's website.
522
+ Start every conversation with account_status. It tells you the user's role, plan, days/runs left and their projects.
523
+ Talk in outcomes, not YAML. Many users are not engineers. Say "I'll check that new users can sign up" \u2014 not
524
+ "I'll create a Midscene flow". After a run, report: what passed, what failed in one sentence each, the likely cause,
525
+ the run link, and a screenshot for the first failure. Only show steps/YAML if the user asks.
526
+ Before writing or running any test: (1) find the project (list_projects; ask if more than one fits);
527
+ (2) PRELATION \u2014 decide whether the test needs a starting state (logged in, a specific page, seeded data). If yes,
528
+ list_testcases and reuse an existing setup case (e.g. "Login") via prelationTestCaseId. Never copy login steps into a
529
+ test. If none exists, ask the user for the test account to use, create the setup case first, then reference it.
530
+ AuraCheck runs the setup case automatically \u2014 never add it to a run yourself. (3) check list_testcases for a duplicate.
531
+ For "test this on my site" requests use test_my_flow; it shows a plan first \u2014 confirm it with the user before running.
532
+ Runs take minutes: start the run, give the link, then call wait_for_run; if it returns pollAgain, tell the user it's
533
+ still running and call it again (or come back later \u2014 they also get an email).
534
+ Never ask for or repeat passwords, PINs or OTP codes in chat. Test accounts and secrets are stored in AuraCheck
535
+ (Project \u2192 Test accounts); tell the user to add them there. Tool results never contain secret values.
536
+ Delete tools are dry-run first: show what will be deleted and get an explicit "yes" before confirm:true.
537
+ If a tool says the plan is read-only or the trial limit is reached, relay its message and next step exactly; don't retry.
538
+ Apps on localhost, an office VPN or an intranet can't be reached by AuraCheck's cloud runner: suggest the AuraCheck
539
+ desktop app or the local MCP (npx @auracheck-ai/mcp). Android/iOS runs only start from the desktop app on the user's device.`;
540
+ var LOCAL_CODE_TOOLS_PARAGRAPH = `This server also runs on your machine, so it additionally offers read_code, list_dir and search_code over the developer's repo (within configured codeRoots) \u2014 use them to understand routes, components, validators and fixtures before generating a testcase. It also offers login, logout and bind_project for local sign-in and project binding; account_status/whoami work here too.`;
541
+ function serverInstructions(surface) {
542
+ return surface === "local" ? `${SERVER_INSTRUCTIONS}
543
+
544
+ ${LOCAL_CODE_TOOLS_PARAGRAPH}` : SERVER_INSTRUCTIONS;
545
+ }
546
+ var WRITE_TESTCASE_PROMPT = [
547
+ "Before calling create_testcase, check:",
548
+ "- Prelation: does this case need a starting state (logged in, specific page, seeded data)? If so, find or create a setup case and set prelationTestCaseId instead of copying its steps in.",
549
+ "- Reuse the setup case; never duplicate a login flow across cases.",
550
+ "- Ask the user for the test account NAME to use, never the password \u2014 passwords live in AuraCheck (Project \u2192 Test accounts).",
551
+ "- Platform: web, android, or ios? Matches the project/feature this case belongs to?",
552
+ "- Steps: a non-empty Midscene flow (array or tasks[] YAML/JSON) \u2014 never an empty flow.",
553
+ '- Expected result: is it stated, so a run that technically "passes" but does the wrong thing still gets caught?',
554
+ "- executionType: automation (runs in CI/scheduled runs) or manual (a human does it, excluded from automation runs)?",
555
+ "- Is there already a similar case (list_testcases) this would duplicate?"
556
+ ].join("\n");
557
+ var RUN_AND_EXPLAIN_PROMPT = "Pick or create the cases \u2192 start_run \u2192 share link \u2192 wait_for_run until terminal \u2192 run_summary \u2192 for each failure get_evidence + one screenshot \u2192 explain in \u22645 bullets: what broke, where, likely bug vs. test issue, suggested fix/next step.";
558
+ var ONBOARDING_PROMPT = "account_status \u2192 if no project: ask for the website URL \u2192 create_project_from_url (or tell non-admins to ask their admin) \u2192 suggest 3 starter flows (sign-up, login, main purchase/contact form) \u2192 test_my_flow for the first one.";
559
+ var PROMPTS = [
560
+ {
561
+ name: "write_testcase",
562
+ description: "Checklist to run through before authoring a new AuraCheck testcase.",
563
+ text: WRITE_TESTCASE_PROMPT
564
+ },
565
+ {
566
+ name: "run_and_explain",
567
+ description: "Run one or more testcases and explain the result in plain language.",
568
+ text: RUN_AND_EXPLAIN_PROMPT
569
+ },
570
+ {
571
+ name: "onboarding",
572
+ description: "First-run flow for a brand-new AuraCheck connection.",
573
+ text: ONBOARDING_PROMPT
574
+ }
575
+ ];
576
+
577
+ // ../mcp-core/dist/register.js
578
+ import { zodToJsonSchema } from "zod-to-json-schema";
579
+
580
+ // ../mcp-core/dist/secrets.js
581
+ var DENY_KEY_PATTERNS = [
582
+ /password/i,
583
+ /pin$/i,
584
+ /^pin/i,
585
+ /otp/i,
586
+ /secret/i,
587
+ /token/i,
588
+ /api[_-]?key/i,
589
+ /authorization/i,
590
+ /cookie/i,
591
+ /credential/i,
592
+ // Config-var payloads the server itself treats as secret.
593
+ /^variables$/i
594
+ ];
595
+ var REDACTED = "[redacted]";
596
+ var MAX_DEPTH = 12;
597
+ function isSecretKey(key) {
598
+ return DENY_KEY_PATTERNS.some((re) => re.test(key));
599
+ }
600
+ function stripSecrets(value, depth = 0) {
601
+ if (depth > MAX_DEPTH || value === null || value === void 0) {
602
+ return value;
603
+ }
604
+ if (Array.isArray(value)) {
605
+ return value.map((v) => stripSecrets(v, depth + 1));
606
+ }
607
+ if (typeof value === "object") {
608
+ const out = {};
609
+ for (const [k, v] of Object.entries(value)) {
610
+ if (isSecretKey(k)) {
611
+ out[k] = REDACTED;
612
+ } else {
613
+ out[k] = stripSecrets(v, depth + 1);
614
+ }
615
+ }
616
+ return out;
617
+ }
618
+ return value;
619
+ }
620
+
621
+ // ../mcp-core/dist/tools/account.js
622
+ import { z } from "zod";
623
+
624
+ // ../mcp-core/dist/types.js
625
+ function defineTool(def) {
626
+ return def;
627
+ }
628
+
629
+ // ../mcp-core/dist/tools/account.js
630
+ var accountStatus = defineTool({
631
+ name: "account_status",
632
+ title: "Account status",
633
+ description: "Who the signed-in user is, their role, their company's plan/trial state, days and runs left, and the projects they can reach. Call this first in every conversation.",
634
+ input: z.object({}),
635
+ requires: null,
636
+ billing: "read",
637
+ surfaces: ["remote", "local"],
638
+ annotations: { readOnlyHint: true },
639
+ handler: async (_args, ctx) => {
640
+ const { account } = ctx;
641
+ const sub = account.subscription;
642
+ const lines = [];
643
+ if (sub.inGrace) {
644
+ lines.push(graceNotice(sub.graceEnd ?? null, ctx.renewalUrl));
645
+ } else if (!sub.readOnly && sub.runUsage) {
646
+ lines.push(`Trial: ${sub.daysLeft ?? "?"} days left, ${Math.max(sub.runUsage.dailyLimit - sub.runUsage.dailyCount, 0)} runs left today (${Math.max(sub.runUsage.monthlyLimit - sub.runUsage.monthlyCount, 0)} this month).`);
647
+ } else if (sub.readOnly) {
648
+ lines.push(account.adminContact ? `Your company's AuraCheck plan has ended, so new runs are paused. Please ask your admin ${account.adminContact.name ?? account.adminContact.email} (${account.adminContact.email}) to renew. Existing results are still available.` : `Your AuraCheck plan has ended, so new runs are paused. Existing results are still available. Renew here: ${ctx.renewalUrl}`);
649
+ }
650
+ return {
651
+ user: account.user,
652
+ company: account.company,
653
+ subscription: sub,
654
+ projects: account.projects,
655
+ renewalUrl: ctx.renewalUrl,
656
+ minLocalMcp: account.minLocalMcp,
657
+ note: lines.join(" ") || null
658
+ };
659
+ }
660
+ });
661
+ var listProjects = defineTool({
662
+ name: "list_projects",
663
+ title: "List projects",
664
+ description: "List the AuraCheck projects this sign-in can reach (id, name, platforms, defaultConfigurationId). Pass a project id as `projectId` to any project tool to work outside the currently set project.",
665
+ input: z.object({}),
666
+ requires: "viewProject",
667
+ billing: "read",
668
+ surfaces: ["remote", "local"],
669
+ annotations: { readOnlyHint: true },
670
+ handler: async (_args, ctx) => {
671
+ const projects = await ctx.api.listProjects();
672
+ return projects.map((p) => ({
673
+ id: p.id,
674
+ name: p.name,
675
+ companyId: p.companyId,
676
+ platforms: p.platforms,
677
+ defaultConfigurationId: p.defaultConfigurationId ?? null
678
+ }));
679
+ }
680
+ });
681
+ var setProject = defineTool({
682
+ name: "set_project",
683
+ title: "Set project",
684
+ description: "Confirm an AuraCheck project id is reachable and set it as the project for this session. Advisory: still pass `projectId` explicitly to tools when working across more than one project in the same conversation.",
685
+ input: z.object({ projectId: z.string().min(1) }),
686
+ requires: "viewProject",
687
+ billing: "read",
688
+ surfaces: ["remote", "local"],
689
+ handler: async ({ projectId }, ctx) => {
690
+ const projects = await ctx.api.listProjects();
691
+ const project = projects.find((p) => p.id === projectId);
692
+ if (!project) {
693
+ throw new Error(`${projectId} is not in the list of projects this sign-in can reach. Call list_projects.`);
694
+ }
695
+ await ctx.onSetProject?.(projectId);
696
+ return {
697
+ ok: true,
698
+ projectId,
699
+ project: { id: project.id, name: project.name }
700
+ };
701
+ }
702
+ });
703
+ var createProjectFromUrl = defineTool({
704
+ name: "create_project_from_url",
705
+ title: "Create project from URL",
706
+ description: '"Start testing my website": create a new AuraCheck project with the given URL as its web environment. Needs the manageProjectSetup permission.',
707
+ input: z.object({
708
+ name: z.string().min(1),
709
+ targetUrl: z.string().url(),
710
+ description: z.string().optional()
711
+ }),
712
+ requires: "manageProjectSetup",
713
+ billing: "write",
714
+ surfaces: ["remote", "local"],
715
+ handler: async (args, ctx) => {
716
+ try {
717
+ const project = await ctx.api.createProject({
718
+ name: args.name,
719
+ targetUrl: args.targetUrl,
720
+ platforms: ["web"],
721
+ description: args.description
722
+ });
723
+ await ctx.onSetProject?.(project.id);
724
+ return {
725
+ ok: true,
726
+ project: { id: project.id, name: project.name },
727
+ nextStep: "Suggest 3 starter flows (sign-up, login, main purchase/contact form), then use test_my_flow for the first one."
728
+ };
729
+ } catch (err) {
730
+ if (err instanceof ApiError && /unreachable|ENOTFOUND|ECONNREFUSED/i.test(err.message)) {
731
+ return {
732
+ blocked: true,
733
+ message: `AuraCheck's cloud can't reach ${args.targetUrl} (private network or localhost). Use the AuraCheck desktop app or the local MCP.`
734
+ };
735
+ }
736
+ throw err;
737
+ }
738
+ }
739
+ });
740
+ var ACCOUNT_TOOLS = [
741
+ accountStatus,
742
+ listProjects,
743
+ setProject,
744
+ createProjectFromUrl
745
+ ];
746
+
747
+ // ../mcp-core/dist/tools/bugs.js
748
+ import { z as z2 } from "zod";
749
+ var PROJECT_ID = z2.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
750
+ var fileBug = defineTool({
751
+ name: "file_bug",
752
+ title: "File bug",
753
+ description: "Open an issue report (bug) against a project. Use this only after the auto-fix loop has identified a real application defect (not a flaky testcase). Severity must be 'critical', 'high', 'medium', or 'low'. Pass evidence URLs (screenshotUrl from get_evidence) in evidences[].",
754
+ input: z2.object({
755
+ projectId: PROJECT_ID,
756
+ title: z2.string().min(1).max(200),
757
+ severity: z2.enum(["critical", "high", "medium", "low"]),
758
+ description: z2.string().optional(),
759
+ pageUrl: z2.string().optional(),
760
+ evidences: z2.array(z2.string()).optional()
761
+ }),
762
+ // manageBugs is proposed (§4): the route itself only checks requireAuth
763
+ // today, so this is a client-side-only gate until the server catches up.
764
+ requires: "manageBugs",
765
+ billing: "write",
766
+ surfaces: ["remote", "local"],
767
+ handler: async ({ projectId, ...args }, ctx) => ctx.api.createIssueReport({
768
+ ...args,
769
+ projectId: requireProjectId(ctx, projectId)
770
+ })
771
+ });
772
+ var listBugs = defineTool({
773
+ name: "list_bugs",
774
+ title: "List bugs",
775
+ description: "List issue reports (bugs) for a project. Use to check whether a defect has already been reported before filing a new one.",
776
+ input: z2.object({ projectId: PROJECT_ID }),
777
+ requires: "viewReports",
778
+ billing: "read",
779
+ surfaces: ["remote", "local"],
780
+ annotations: { readOnlyHint: true },
781
+ handler: async ({ projectId }, ctx) => ctx.api.listIssueReports(requireProjectId(ctx, projectId))
782
+ });
783
+ var getBug = defineTool({
784
+ name: "get_bug",
785
+ title: "Get bug",
786
+ description: "Fetch a single issue report by id.",
787
+ input: z2.object({ id: z2.string().min(1) }),
788
+ requires: "viewReports",
789
+ billing: "read",
790
+ surfaces: ["remote", "local"],
791
+ annotations: { readOnlyHint: true },
792
+ handler: async ({ id }, ctx) => ctx.api.getIssueReport(id)
793
+ });
794
+ var BUG_TOOLS = [fileBug, listBugs, getBug];
795
+
796
+ // ../mcp-core/dist/tools/exploration.js
797
+ import { z as z3 } from "zod";
798
+ var PROJECT_ID2 = z3.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
799
+ var startExploration = defineTool({
800
+ name: "start_exploration",
801
+ title: "Start exploration",
802
+ description: "Trigger AuraCheck's crawler on a set of seed URLs for a project. Returns a snapshot immediately (job runs in background); poll with get_exploration. One job per project at a time \u2014 calling this while a job is already running returns the live snapshot.",
803
+ input: z3.object({
804
+ projectId: PROJECT_ID2,
805
+ seedUrls: z3.array(z3.string().url()).min(1),
806
+ configurationId: z3.string().optional(),
807
+ maxDepth: z3.number().int().positive().max(20).optional(),
808
+ maxPages: z3.number().int().positive().max(500).optional()
809
+ }),
810
+ requires: "runTests",
811
+ billing: "run",
812
+ surfaces: ["remote", "local"],
813
+ handler: async ({ projectId, ...args }, ctx) => ctx.api.startExploration(requireProjectId(ctx, projectId), args)
814
+ });
815
+ var getExploration = defineTool({
816
+ name: "get_exploration",
817
+ title: "Get exploration",
818
+ description: "Return the latest exploration snapshot for a project (or null if none has ever run). Shape: { jobId, status, visited, anchorsUpserted, loggedIn, errors[] }. Use to await completion before generating testcases that depend on discovered routes/anchors.",
819
+ input: z3.object({ projectId: PROJECT_ID2 }),
820
+ requires: "viewProject",
821
+ billing: "read",
822
+ surfaces: ["remote", "local"],
823
+ annotations: { readOnlyHint: true },
824
+ handler: async ({ projectId }, ctx) => ctx.api.getExploration(requireProjectId(ctx, projectId))
825
+ });
826
+ var EXPLORATION_TOOLS = [startExploration, getExploration];
827
+
828
+ // ../mcp-core/dist/tools/features.js
829
+ import { z as z4 } from "zod";
830
+ var PROJECT_ID3 = z4.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
831
+ var listFeatures = defineTool({
832
+ name: "list_features",
833
+ title: "List features",
834
+ description: "List features (groups of testcases) for a project. Each feature has an id and a name. Pick the most relevant feature id before creating a testcase.",
835
+ input: z4.object({ projectId: PROJECT_ID3 }),
836
+ requires: "viewProject",
837
+ billing: "read",
838
+ surfaces: ["remote", "local"],
839
+ annotations: { readOnlyHint: true },
840
+ handler: async (args, ctx) => ctx.api.listFeatures(requireProjectId(ctx, args.projectId))
841
+ });
842
+ var createFeature = defineTool({
843
+ name: "create_feature",
844
+ title: "Create feature",
845
+ description: "Create a new feature in a project. Use when no existing feature fits the testcase you are about to create.",
846
+ input: z4.object({
847
+ projectId: PROJECT_ID3,
848
+ name: z4.string().min(1),
849
+ path: z4.string().optional(),
850
+ description: z4.string().optional(),
851
+ prdContent: z4.string().optional()
852
+ }),
853
+ requires: "manageTestCases",
854
+ billing: "write",
855
+ surfaces: ["remote", "local"],
856
+ handler: async ({ projectId, ...rest }, ctx) => ctx.api.createFeature(requireProjectId(ctx, projectId), rest)
857
+ });
858
+ var deleteFeature = defineTool({
859
+ name: "delete_feature",
860
+ title: "Delete feature",
861
+ description: "Delete a feature. Requires manageTestCases. Without `confirm: true` this is a DRY RUN \u2014 it only shows the feature's name and how many testcases it holds; nothing is deleted on the first call. Testcases linked to a run are soft-deleted (reparented, run history kept); unlinked ones are removed permanently. Pass `cascade: true` to also remove sub-features.",
862
+ input: z4.object({
863
+ projectId: PROJECT_ID3,
864
+ featureId: z4.string().min(1),
865
+ cascade: z4.boolean().optional(),
866
+ confirm: z4.boolean().optional()
867
+ }),
868
+ requires: "manageTestCases",
869
+ billing: "write",
870
+ surfaces: ["remote", "local"],
871
+ annotations: { destructiveHint: true },
872
+ handler: async ({ projectId, featureId, cascade, confirm }, ctx) => {
873
+ const pid = requireProjectId(ctx, projectId);
874
+ try {
875
+ const feature = await ctx.api.getFeature(featureId, pid);
876
+ if (!feature) {
877
+ throw new Error(`Delete failed (404): feature ${featureId} not found.`);
878
+ }
879
+ if (!confirm) {
880
+ const cases = await ctx.api.listTestCasesByFeature(featureId).catch(() => []);
881
+ return {
882
+ dryRun: true,
883
+ feature: { id: feature.id, name: feature.name },
884
+ testCaseCount: cases.length,
885
+ cascade: !!cascade,
886
+ note: "Testcases linked to a run are soft-deleted (run history kept); others are removed permanently. Re-call with confirm:true to actually delete."
887
+ };
888
+ }
889
+ await ctx.api.deleteFeature(featureId, cascade);
890
+ return { dryRun: false, deletedFeatureId: featureId, cascade: !!cascade };
891
+ } catch (err) {
892
+ if (err instanceof ApiError && err.status === 403) {
893
+ throw new Error("Delete failed (403): this sign-in lacks manageTestCases, or this feature belongs to a project it can't reach.");
894
+ }
895
+ if (err instanceof ApiError && err.status === 404) {
896
+ throw new Error(`Delete failed (404): feature ${featureId} not found.`);
897
+ }
898
+ throw err;
899
+ }
900
+ }
901
+ });
902
+ var FEATURE_TOOLS = [listFeatures, createFeature, deleteFeature];
903
+
904
+ // ../mcp-core/dist/tools/runs.js
905
+ import { z as z5 } from "zod";
906
+ var PROJECT_ID4 = z5.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
907
+ function runViewUrl(appUrl, runId, projectId) {
908
+ return projectId ? `${appUrl}/projects/${projectId}/runs/${runId}` : `${appUrl}/runs/${runId}`;
909
+ }
910
+ var listRuns = defineTool({
911
+ name: "list_runs",
912
+ title: "List runs",
913
+ description: "List recent runs for a project, optionally filtered by platform.",
914
+ input: z5.object({
915
+ projectId: PROJECT_ID4,
916
+ platform: z5.enum(["web", "android", "ios"]).optional()
917
+ }),
918
+ requires: "viewProject",
919
+ billing: "read",
920
+ surfaces: ["remote", "local"],
921
+ annotations: { readOnlyHint: true },
922
+ handler: async ({ projectId, platform }, ctx) => ctx.api.listRuns(requireProjectId(ctx, projectId), platform)
923
+ });
924
+ var createRun = defineTool({
925
+ name: "create_run",
926
+ title: "Create run",
927
+ description: 'Create a new run for one or more testcases. Defaults: caseSelectionMode="select". Returns the created run object including its id. An android/ios run is created here as usual, but only a person can start it: in the AuraCheck desktop app on their device.',
928
+ input: z5.object({
929
+ projectId: PROJECT_ID4,
930
+ name: z5.string().min(1),
931
+ testCaseIds: z5.array(z5.string()).optional(),
932
+ featureIds: z5.array(z5.string()).optional(),
933
+ platform: z5.enum(["web", "android", "ios"]).optional(),
934
+ caseSelectionMode: z5.enum(["all", "select"]).optional(),
935
+ configurationId: z5.string().optional(),
936
+ milestoneId: z5.string().optional(),
937
+ tags: z5.array(z5.string()).optional(),
938
+ notes: z5.string().optional(),
939
+ browserEngine: z5.enum(["chrome", "edge"]).optional()
940
+ }),
941
+ requires: "runTests",
942
+ billing: "run",
943
+ surfaces: ["remote", "local"],
944
+ handler: async ({ projectId, ...args }, ctx) => {
945
+ const pid = requireProjectId(ctx, projectId);
946
+ const body = {
947
+ ...args,
948
+ platform: args.platform ?? ctx.defaultPlatform ?? "web",
949
+ caseSelectionMode: args.caseSelectionMode ?? (args.testCaseIds?.length ? "select" : "all")
950
+ };
951
+ try {
952
+ return await ctx.api.createRun(pid, body);
953
+ } catch (err) {
954
+ if (err instanceof ApiError) {
955
+ const mapped = mapApiError(err, ctx, "runTests");
956
+ if (mapped)
957
+ return mapped;
958
+ }
959
+ throw err;
960
+ }
961
+ }
962
+ });
963
+ var startRun = defineTool({
964
+ name: "start_run",
965
+ // Existing local CLI name, kept so `auracheck.execute_run` doesn't break.
966
+ localAlias: "execute_run",
967
+ title: "Start run",
968
+ description: "Trigger execution of an existing WEB run. Fire-and-forget: the runner state lives in AuraCheck. Use wait_for_run to await terminal status. Android/iOS runs never execute on AuraCheck's servers: for those this returns a blocked result telling the person to open the run in the desktop app and click Run on local / Run on iOS.",
969
+ input: z5.object({ runId: z5.string().min(1) }),
970
+ requires: "runTests",
971
+ billing: "run",
972
+ surfaces: ["remote", "local"],
973
+ handler: async ({ runId }, ctx) => {
974
+ try {
975
+ return await ctx.api.executeRun(runId);
976
+ } catch (err) {
977
+ if (err instanceof ApiError) {
978
+ const answer = runFromDesktopAnswer(err, runId) ?? mapApiError(err, ctx, "runTests");
979
+ if (answer)
980
+ return answer;
981
+ }
982
+ throw err;
983
+ }
984
+ }
985
+ });
986
+ var cancelRun = defineTool({
987
+ name: "cancel_run",
988
+ title: "Cancel run",
989
+ description: "Cancel an in-flight run. Idempotent for queued runs; for inline runs the cancel may take effect at the next case boundary.",
990
+ input: z5.object({ runId: z5.string().min(1) }),
991
+ requires: "manageRuns",
992
+ billing: "write",
993
+ surfaces: ["remote", "local"],
994
+ handler: async ({ runId }, ctx) => ctx.api.cancelRun(runId)
995
+ });
996
+ var waitForRun = defineTool({
997
+ name: "wait_for_run",
998
+ title: "Wait for run",
999
+ description: "Poll a run until it reaches a terminal status (passed/failed/cancelled/error) or the timeout elapses. Returns the final run object plus a summary of per-case statuses. Remote caps the wait at 45s and returns `pollAgain:true` if still running \u2014 call it again (the user also gets an email when the run finishes). Local can wait up to 300s. An android/ios run stays pending until a person starts it in the AuraCheck desktop app.",
1000
+ input: z5.object({
1001
+ runId: z5.string().min(1),
1002
+ timeoutSec: z5.number().int().positive().max(3600).optional(),
1003
+ pollMs: z5.number().int().positive().max(3e4).optional()
1004
+ }),
1005
+ requires: "viewProject",
1006
+ billing: "read",
1007
+ surfaces: ["remote", "local"],
1008
+ annotations: { readOnlyHint: true },
1009
+ handler: async (args, ctx) => {
1010
+ const requested = args.timeoutSec ?? ctx.waitForRunMaxSec;
1011
+ const timeoutMs = Math.min(requested, ctx.waitForRunMaxSec) * 1e3;
1012
+ const pollMs = args.pollMs ?? 3e3;
1013
+ const start = Date.now();
1014
+ let last = await ctx.api.getRun(args.runId);
1015
+ while (!TERMINAL_RUN_STATUSES.has(last.status) && Date.now() - start < timeoutMs) {
1016
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1017
+ last = await ctx.api.getRun(args.runId);
1018
+ }
1019
+ const terminal = TERMINAL_RUN_STATUSES.has(last.status);
1020
+ const attempts = await ctx.api.listRunCaseAttempts(args.runId).catch(() => ({ attempts: [] }));
1021
+ const summary = attempts.attempts.reduce((acc, a) => {
1022
+ acc[a.status] = (acc[a.status] ?? 0) + 1;
1023
+ return acc;
1024
+ }, {});
1025
+ const pendingMobile = !terminal && last.status === "pending" && (last.platform === "android" || last.platform === "ios");
1026
+ return {
1027
+ terminal,
1028
+ pollAgain: !terminal,
1029
+ elapsedMs: Date.now() - start,
1030
+ runId: args.runId,
1031
+ status: last.status,
1032
+ reportUrl: last.reportUrl ?? null,
1033
+ viewUrl: runViewUrl(ctx.appUrl, args.runId, last.projectId),
1034
+ completedAt: last.completedAt ?? null,
1035
+ caseStatusSummary: summary,
1036
+ ...pendingMobile ? {
1037
+ message: "Not started yet: Android/iOS runs are started by a person in the AuraCheck desktop app on their own device."
1038
+ } : {},
1039
+ run: last
1040
+ };
1041
+ }
1042
+ });
1043
+ var getRun = defineTool({
1044
+ name: "get_run",
1045
+ title: "Get run",
1046
+ description: "Fetch a single run by id including current status, started/completed timestamps, and reportUrl when available.",
1047
+ input: z5.object({ runId: z5.string().min(1) }),
1048
+ requires: "viewProject",
1049
+ billing: "read",
1050
+ surfaces: ["remote", "local"],
1051
+ annotations: { readOnlyHint: true },
1052
+ handler: async ({ runId }, ctx) => ctx.api.getRun(runId)
1053
+ });
1054
+ var runSummary = defineTool({
1055
+ name: "run_summary",
1056
+ // Existing local CLI name, kept so `auracheck.get_run_report` doesn't break.
1057
+ localAlias: "get_run_report",
1058
+ title: "Run summary",
1059
+ description: "Results of a run as the Run Report groups them: case counts (passed/failed/skipped/pending) plus buckets \u2014 potential bugs (with bug report, severity), script issues, blocked cases and passed cases. Read-only.",
1060
+ input: z5.object({ runId: z5.string().min(1) }),
1061
+ requires: "viewReports",
1062
+ billing: "read",
1063
+ surfaces: ["remote", "local"],
1064
+ annotations: { readOnlyHint: true },
1065
+ handler: async ({ runId }, ctx) => {
1066
+ const [run, counts, buckets] = await Promise.all([
1067
+ ctx.api.getRun(runId),
1068
+ ctx.api.getRunCaseStatusCounts(runId),
1069
+ ctx.api.getRunReportBuckets(runId)
1070
+ ]);
1071
+ return {
1072
+ run: {
1073
+ id: run.id,
1074
+ name: run.name,
1075
+ status: run.status,
1076
+ reportUrl: run.reportUrl ?? null
1077
+ },
1078
+ counts,
1079
+ ...buckets
1080
+ };
1081
+ }
1082
+ });
1083
+ var listRunTestcases = defineTool({
1084
+ name: "list_run_testcases",
1085
+ title: "List run testcases",
1086
+ description: "List the testcases attached to a specific run.",
1087
+ input: z5.object({ runId: z5.string().min(1) }),
1088
+ requires: "viewProject",
1089
+ billing: "read",
1090
+ surfaces: ["remote", "local"],
1091
+ annotations: { readOnlyHint: true },
1092
+ handler: async ({ runId }, ctx) => ctx.api.listRunTestCases(runId)
1093
+ });
1094
+ var getEvidence = defineTool({
1095
+ name: "get_evidence",
1096
+ title: "Get evidence",
1097
+ description: "Aggregate evidence for a finished (or in-progress) run: per-case attempts, latest step events, failed-step screenshots and error messages, and the AuraCheck report URL. A failed step that hung also carries stallDiagnostics. Filter by caseId to narrow scope. Use after wait_for_run to diagnose failures.",
1098
+ input: z5.object({
1099
+ runId: z5.string().min(1),
1100
+ caseId: z5.string().optional(),
1101
+ maxEventsPerCase: z5.number().int().positive().max(200).optional()
1102
+ }),
1103
+ requires: "viewReports",
1104
+ billing: "read",
1105
+ surfaces: ["remote", "local"],
1106
+ annotations: { readOnlyHint: true },
1107
+ handler: async (args, ctx) => {
1108
+ const max = args.maxEventsPerCase ?? 20;
1109
+ const [run, attemptsResp, eventsResp, runCases] = await Promise.all([
1110
+ ctx.api.getRun(args.runId),
1111
+ ctx.api.listRunCaseAttempts(args.runId),
1112
+ ctx.api.listRunStepEvents(args.runId, args.caseId),
1113
+ ctx.api.listRunTestCases(args.runId).catch(() => [])
1114
+ ]);
1115
+ const caseNameById = new Map(runCases.map((c) => [c.id, c.name]));
1116
+ const allEvents = eventsResp.events ?? [];
1117
+ const eventsByCase = /* @__PURE__ */ new Map();
1118
+ for (const e of allEvents) {
1119
+ const key = e.testCaseId ?? "__unbound__";
1120
+ if (args.caseId && key !== args.caseId)
1121
+ continue;
1122
+ const arr = eventsByCase.get(key) ?? [];
1123
+ arr.push(e);
1124
+ eventsByCase.set(key, arr);
1125
+ }
1126
+ const attempts = (attemptsResp.attempts ?? []).filter((a) => !args.caseId || a.testCaseId === args.caseId);
1127
+ const cases = attempts.map((attempt) => {
1128
+ const events = (eventsByCase.get(attempt.testCaseId) ?? []).slice().sort((a, b) => (a.stepIndex ?? 0) - (b.stepIndex ?? 0)).slice(0, max);
1129
+ const failedSteps = events.filter((e) => e.status === "failed" || e.error);
1130
+ return {
1131
+ testCaseId: attempt.testCaseId,
1132
+ testCaseName: caseNameById.get(attempt.testCaseId) ?? null,
1133
+ attemptId: attempt.id,
1134
+ attemptStatus: attempt.status,
1135
+ attemptReportUrl: attempt.reportUrl ?? null,
1136
+ startedAt: attempt.startedAt,
1137
+ completedAt: attempt.completedAt,
1138
+ stepEvents: events.map((e) => ({
1139
+ stepIndex: e.stepIndex,
1140
+ stepType: e.stepType,
1141
+ stepPrompt: e.stepPrompt,
1142
+ status: e.status,
1143
+ durationMs: e.durationMs,
1144
+ error: e.error,
1145
+ screenshotUrl: e.screenshotUrl,
1146
+ notes: e.notes
1147
+ })),
1148
+ failedSteps: failedSteps.map((e) => ({
1149
+ stepIndex: e.stepIndex,
1150
+ stepType: e.stepType,
1151
+ error: e.error,
1152
+ screenshotUrl: e.screenshotUrl,
1153
+ stallDiagnostics: e.stallDiagnostics ?? null
1154
+ }))
1155
+ };
1156
+ });
1157
+ return {
1158
+ runId: args.runId,
1159
+ status: run.status,
1160
+ platform: run.platform,
1161
+ reportUrl: run.reportUrl ?? null,
1162
+ viewUrl: runViewUrl(ctx.appUrl, args.runId),
1163
+ cases,
1164
+ totals: {
1165
+ caseCount: cases.length,
1166
+ failedCaseCount: cases.filter((c) => c.attemptStatus === "failed").length,
1167
+ failedStepCount: cases.reduce((n, c) => n + c.failedSteps.length, 0)
1168
+ }
1169
+ };
1170
+ }
1171
+ });
1172
+ var getScreenshot = defineTool({
1173
+ name: "get_screenshot",
1174
+ title: "Get screenshot",
1175
+ description: "Fetch a run screenshot (or any authenticated blob) so it can actually be SEEN. Pass a `screenshotUrl` straight from get_evidence. Remote returns it as inline MCP image content; local writes it to a file and returns the path. Reach for it whenever a failure's cause is visual.",
1176
+ input: z5.object({
1177
+ url: z5.string().min(1).describe("screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host.")
1178
+ }),
1179
+ requires: "viewReports",
1180
+ billing: "read",
1181
+ // Local keeps its pre-existing, richer implementation (optional outPath,
1182
+ // writes the file itself — mcp-core has no fs) in packages/cli directly;
1183
+ // this one only ever runs on the Worker.
1184
+ surfaces: ["remote"],
1185
+ annotations: { readOnlyHint: true },
1186
+ handler: async ({ url }, ctx) => {
1187
+ const { bytes, contentType } = await ctx.api.downloadBlob(url);
1188
+ return { __binary: true, bytes, contentType, sourceUrl: url };
1189
+ }
1190
+ });
1191
+ var RUN_TOOLS = [
1192
+ listRuns,
1193
+ createRun,
1194
+ startRun,
1195
+ cancelRun,
1196
+ waitForRun,
1197
+ getRun,
1198
+ runSummary,
1199
+ listRunTestcases,
1200
+ getEvidence,
1201
+ getScreenshot
1202
+ ];
1203
+
1204
+ // ../mcp-core/dist/tools/schedules.js
1205
+ import { z as z6 } from "zod";
1206
+ var PROJECT_ID5 = z6.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
1207
+ var listSchedules = defineTool({
1208
+ name: "list_schedules",
1209
+ title: "List schedules",
1210
+ description: "List the recurring run schedules of a project. Each schedule carries its cron expressions, IANA timezone, computed nextFireAt (UTC), platform, case filter and notify recipients.",
1211
+ input: z6.object({ projectId: PROJECT_ID5 }),
1212
+ requires: "viewProject",
1213
+ billing: "read",
1214
+ surfaces: ["remote", "local"],
1215
+ annotations: { readOnlyHint: true },
1216
+ handler: async ({ projectId }, ctx) => ctx.api.listSchedules(requireProjectId(ctx, projectId))
1217
+ });
1218
+ var getSchedule = defineTool({
1219
+ name: "get_schedule",
1220
+ title: "Get schedule",
1221
+ description: "Fetch a single schedule by id. lastFiredAt reflects CLOCK-driven fires only \u2014 run_schedule_now deliberately leaves it untouched; use list_schedule_fires for the full history.",
1222
+ input: z6.object({ scheduleId: z6.string().min(1) }),
1223
+ requires: "viewProject",
1224
+ billing: "read",
1225
+ surfaces: ["remote", "local"],
1226
+ annotations: { readOnlyHint: true },
1227
+ handler: async ({ scheduleId }, ctx) => ctx.api.getSchedule(scheduleId)
1228
+ });
1229
+ var createSchedule = defineTool({
1230
+ name: "create_schedule",
1231
+ title: "Create schedule",
1232
+ description: "Create a recurring run schedule. cronExpressions is 5-field cron evaluated in `timezone` (IANA, e.g. 'Asia/Jakarta'); several expressions are allowed. caseFilter picks what runs: { mode: 'all' } for every case on the platform, or { mode: 'feature', featureIds } to narrow (get ids from list_features). notifyUserIds must come from list_schedule_recipients. Prefer enabled:false while testing, then enable once the cadence reads right.",
1233
+ input: z6.object({
1234
+ projectId: PROJECT_ID5,
1235
+ name: z6.string().min(1),
1236
+ cronExpressions: z6.array(z6.string().min(1)).min(1),
1237
+ timezone: z6.string().min(1),
1238
+ platform: z6.enum(["web", "android", "ios"]).optional(),
1239
+ enabled: z6.boolean().optional(),
1240
+ configurationId: z6.string().optional(),
1241
+ caseFilter: z6.object({
1242
+ mode: z6.enum(["all", "feature"]),
1243
+ featureIds: z6.array(z6.string()).default([])
1244
+ }).optional(),
1245
+ notifyUserIds: z6.array(z6.string()).optional(),
1246
+ misfireGraceMinutes: z6.number().int().positive().optional()
1247
+ }),
1248
+ requires: "runTests",
1249
+ billing: "write",
1250
+ surfaces: ["remote", "local"],
1251
+ handler: async ({ projectId, ...args }, ctx) => {
1252
+ const pid = requireProjectId(ctx, projectId);
1253
+ if (args.caseFilter?.mode === "feature" && !args.caseFilter.featureIds?.length) {
1254
+ throw new Error("caseFilter.mode 'feature' needs at least one featureId \u2014 otherwise every fire resolves to zero cases. Call list_features, or use { mode: 'all' }.");
1255
+ }
1256
+ const schedule = await ctx.api.createSchedule(pid, {
1257
+ ...args,
1258
+ platform: args.platform ?? ctx.defaultPlatform ?? "web"
1259
+ });
1260
+ let warning = null;
1261
+ if (!schedule.configurationId) {
1262
+ const project = await ctx.api.getProject(pid).catch(() => null);
1263
+ if (project && !project.defaultConfigurationId) {
1264
+ warning = "This schedule has no configurationId and the project has no default configuration, so its runs will start without a base URL and fail at the first navigation. Set configurationId via update_schedule.";
1265
+ }
1266
+ }
1267
+ return { ...schedule, warning };
1268
+ }
1269
+ });
1270
+ var updateSchedule = defineTool({
1271
+ name: "update_schedule",
1272
+ title: "Update schedule",
1273
+ description: "Patch an existing schedule \u2014 pause it (enabled:false), change cadence, retarget its configuration, or edit notify recipients. Only the fields you pass are touched.",
1274
+ input: z6.object({ scheduleId: z6.string().min(1), patch: z6.record(z6.any()) }),
1275
+ requires: "runTests",
1276
+ billing: "write",
1277
+ surfaces: ["remote", "local"],
1278
+ handler: async ({ scheduleId, patch }, ctx) => ctx.api.updateSchedule(scheduleId, patch)
1279
+ });
1280
+ var deleteSchedule = defineTool({
1281
+ name: "delete_schedule",
1282
+ title: "Delete schedule",
1283
+ description: "Delete a schedule permanently. Runs it already created are kept; only the cadence goes away. Prefer update_schedule with enabled:false to pause it instead.",
1284
+ input: z6.object({ scheduleId: z6.string().min(1) }),
1285
+ requires: "runTests",
1286
+ billing: "write",
1287
+ surfaces: ["remote", "local"],
1288
+ annotations: { destructiveHint: true },
1289
+ handler: async ({ scheduleId }, ctx) => {
1290
+ await ctx.api.deleteSchedule(scheduleId);
1291
+ return { ok: true, deletedScheduleId: scheduleId };
1292
+ }
1293
+ });
1294
+ var runScheduleNow = defineTool({
1295
+ name: "run_schedule_now",
1296
+ title: "Run schedule now",
1297
+ description: "Fire a schedule immediately on the identical code path the clock uses \u2014 works on a paused schedule too. Returns { outcome, runId }: 'run_created' means a run was started (feed runId to wait_for_run), while 'skipped_overlap' means a previous run of this schedule is still live and 'no_cases' means the case filter matched nothing. Skips are reported, not thrown.",
1298
+ input: z6.object({ scheduleId: z6.string().min(1) }),
1299
+ requires: "runTests",
1300
+ billing: "run",
1301
+ surfaces: ["remote", "local"],
1302
+ handler: async ({ scheduleId }, ctx) => {
1303
+ const { outcome, skipped } = await ctx.api.runScheduleNow(scheduleId);
1304
+ let runId = null;
1305
+ if (outcome === "run_created") {
1306
+ const fires = await ctx.api.listScheduleFires(scheduleId).catch(() => ({ items: [], hasMore: false }));
1307
+ runId = fires.items[0]?.runId ?? null;
1308
+ }
1309
+ return {
1310
+ scheduleId,
1311
+ outcome,
1312
+ skipped,
1313
+ runId,
1314
+ viewUrl: runId ? `${ctx.appUrl}/runs/${runId}` : null
1315
+ };
1316
+ }
1317
+ });
1318
+ var listScheduleFires = defineTool({
1319
+ name: "list_schedule_fires",
1320
+ title: "List schedule fires",
1321
+ description: "History of a schedule's occurrences, newest first: when it fired, the outcome, and the run it created (if any).",
1322
+ input: z6.object({
1323
+ scheduleId: z6.string().min(1),
1324
+ page: z6.number().int().positive().optional()
1325
+ }),
1326
+ requires: "viewProject",
1327
+ billing: "read",
1328
+ surfaces: ["remote", "local"],
1329
+ annotations: { readOnlyHint: true },
1330
+ handler: async ({ scheduleId, page }, ctx) => ctx.api.listScheduleFires(scheduleId, page)
1331
+ });
1332
+ var listScheduleRecipients = defineTool({
1333
+ name: "list_schedule_recipients",
1334
+ title: "List schedule recipients",
1335
+ description: "The users that may be put in a schedule's notifyUserIds. Resolved exactly the way the server resolves recipients at send time.",
1336
+ input: z6.object({ projectId: PROJECT_ID5 }),
1337
+ requires: "viewProject",
1338
+ billing: "read",
1339
+ surfaces: ["remote", "local"],
1340
+ annotations: { readOnlyHint: true },
1341
+ handler: async ({ projectId }, ctx) => ctx.api.listScheduleRecipients(requireProjectId(ctx, projectId))
1342
+ });
1343
+ var SCHEDULE_TOOLS = [
1344
+ listSchedules,
1345
+ getSchedule,
1346
+ createSchedule,
1347
+ updateSchedule,
1348
+ deleteSchedule,
1349
+ runScheduleNow,
1350
+ listScheduleFires,
1351
+ listScheduleRecipients
1352
+ ];
1353
+
1354
+ // ../mcp-core/dist/tools/test-my-flow.js
1355
+ import { z as z7 } from "zod";
1356
+ var PROJECT_ID6 = z7.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
1357
+ var testMyFlow = defineTool({
1358
+ name: "test_my_flow",
1359
+ title: "Test my flow",
1360
+ description: 'One-shot: turn a plain-English request ("check that sign-up works") into a test plan, show it, then run it on confirmation and summarize the result with a link. Call once without `confirm` to see the plan; call again with `confirm:true` once the person agrees to run it.',
1361
+ input: z7.object({
1362
+ projectId: PROJECT_ID6,
1363
+ url: z7.string().url(),
1364
+ prompt: z7.string().min(8).max(4e3),
1365
+ confirm: z7.boolean().optional()
1366
+ }),
1367
+ requires: "manageTestCases",
1368
+ billing: "run",
1369
+ surfaces: ["remote", "local"],
1370
+ handler: async ({ projectId, url, prompt, confirm }, ctx) => {
1371
+ const pid = requireProjectId(ctx, projectId);
1372
+ let plan = null;
1373
+ let promptToTestEnabled = true;
1374
+ try {
1375
+ const preview = await ctx.api.previewPromptTest(pid, { url, prompt });
1376
+ plan = preview.plan;
1377
+ } catch (err) {
1378
+ if (err instanceof ApiError && err.status === 404) {
1379
+ promptToTestEnabled = false;
1380
+ } else if (err instanceof ApiError) {
1381
+ const mapped = mapApiError(err, ctx, "manageTestCases");
1382
+ if (mapped)
1383
+ return mapped;
1384
+ throw err;
1385
+ } else {
1386
+ throw err;
1387
+ }
1388
+ }
1389
+ if (!confirm) {
1390
+ if (plan) {
1391
+ return {
1392
+ dryRun: true,
1393
+ plan,
1394
+ note: "Confirm this plan with the person, then call test_my_flow again with confirm:true to create and run it."
1395
+ };
1396
+ }
1397
+ return {
1398
+ dryRun: true,
1399
+ plan: {
1400
+ title: prompt.slice(0, 120),
1401
+ category: "positive",
1402
+ steps: [{ kind: "action", description: prompt }]
1403
+ },
1404
+ note: "This company doesn't have AI plan generation enabled for prompt-to-test, so this will run as a single step using your instruction verbatim. Confirm with the person, then call test_my_flow again with confirm:true."
1405
+ };
1406
+ }
1407
+ try {
1408
+ let runId;
1409
+ let viewUrl;
1410
+ if (promptToTestEnabled && plan) {
1411
+ const { run } = await ctx.api.createPromptTestRun(pid, {
1412
+ url,
1413
+ prompt,
1414
+ plan
1415
+ });
1416
+ runId = run.id;
1417
+ viewUrl = `${ctx.appUrl}/projects/${pid}/runs/${runId}`;
1418
+ } else {
1419
+ const features = await ctx.api.listFeatures(pid);
1420
+ let feature = features.find((f) => f.name === "Prompt tests");
1421
+ if (!feature) {
1422
+ feature = await ctx.api.createFeature(pid, {
1423
+ name: "Prompt tests",
1424
+ description: "Cases created by test_my_flow (AI plan generation not enabled for this company)."
1425
+ });
1426
+ }
1427
+ const testCase = await ctx.api.createTestCase(feature.id, {
1428
+ name: prompt.slice(0, 120),
1429
+ steps: [{ aiAction: prompt }],
1430
+ executionType: "automation",
1431
+ category: "positive",
1432
+ description: prompt
1433
+ });
1434
+ const run = await ctx.api.createRun(pid, {
1435
+ name: prompt.slice(0, 120),
1436
+ testCaseIds: [testCase.id],
1437
+ platform: "web",
1438
+ caseSelectionMode: "select"
1439
+ });
1440
+ runId = run.id;
1441
+ viewUrl = `${ctx.appUrl}/projects/${pid}/runs/${runId}`;
1442
+ }
1443
+ try {
1444
+ await ctx.api.executeRun(runId);
1445
+ } catch (err) {
1446
+ if (err instanceof ApiError) {
1447
+ const answer = runFromDesktopAnswer(err, runId) ?? mapApiError(err, ctx, "runTests");
1448
+ if (answer)
1449
+ return answer;
1450
+ }
1451
+ throw err;
1452
+ }
1453
+ return {
1454
+ started: true,
1455
+ runId,
1456
+ viewUrl,
1457
+ usedAiPlan: promptToTestEnabled,
1458
+ nextStep: "Call wait_for_run with this runId, then run_summary."
1459
+ };
1460
+ } catch (err) {
1461
+ if (err instanceof ApiError) {
1462
+ const mapped = mapApiError(err, ctx, "runTests");
1463
+ if (mapped)
1464
+ return mapped;
1465
+ }
1466
+ throw err;
1467
+ }
1468
+ }
1469
+ });
1470
+ var TEST_MY_FLOW_TOOLS = [testMyFlow];
1471
+
1472
+ // ../mcp-core/dist/tools/testcases.js
1473
+ import { z as z8 } from "zod";
1474
+ var PROJECT_ID7 = z8.string().optional().describe("AuraCheck project id (see list_projects). Defaults to the project set for this session.");
1475
+ var STEPS_SCHEMA = z8.union([
1476
+ z8.array(z8.record(z8.any())).min(1),
1477
+ z8.string().min(1),
1478
+ z8.record(z8.any())
1479
+ ]);
1480
+ var STEPS_DESCRIPTION = "Array of Midscene flow items (auto-wrapped into tasks[]), or a YAML/JSON string shaped as `tasks: [{ name, flow }]`. Recognized action keys: aiTap, aiInput, aiAssert, aiQuery, aiHover, aiWaitFor, aiKeyboardPress, aiScroll, aiAction, sleep, javascript, aiUploadFile, aiHumanInput, aiExpectDownload, mailTmInbox, mailTmWaitOtp, mailTmWaitLink, otpInbox, otpWaitOtp.";
1481
+ var listTestcases = defineTool({
1482
+ name: "list_testcases",
1483
+ title: "List testcases",
1484
+ description: "List testcases for a project, optionally filtered by platform (web/android/ios). Each case carries `prelationTestCaseId` and, when set, a joined `prelationTestCase` \u2014 the setup case AuraCheck runs automatically right before it. Use this to find an existing login/setup case before creating a new one.",
1485
+ input: z8.object({
1486
+ projectId: PROJECT_ID7,
1487
+ platform: z8.enum(["web", "android", "ios"]).optional()
1488
+ }),
1489
+ requires: "viewProject",
1490
+ billing: "read",
1491
+ surfaces: ["remote", "local"],
1492
+ annotations: { readOnlyHint: true },
1493
+ handler: async ({ projectId, platform }, ctx) => ctx.api.listTestCasesByProject(requireProjectId(ctx, projectId), platform)
1494
+ });
1495
+ var getTestcase = defineTool({
1496
+ name: "get_testcase",
1497
+ title: "Get testcase",
1498
+ description: "Fetch a single testcase by id. `steps` comes back as the Midscene YAML/JSON string the server stores, not an array \u2014 parse it before editing, and pass it back through update_testcase in either form. Also carries `prelationTestCaseId` and, when set, a joined `prelationTestCase`.",
1499
+ input: z8.object({ projectId: PROJECT_ID7, id: z8.string().min(1) }),
1500
+ requires: "viewProject",
1501
+ billing: "read",
1502
+ surfaces: ["remote", "local"],
1503
+ annotations: { readOnlyHint: true },
1504
+ handler: async ({ projectId, id }, ctx) => ctx.api.getTestCase(id, requireProjectId(ctx, projectId))
1505
+ });
1506
+ var createTestcase = defineTool({
1507
+ name: "create_testcase",
1508
+ title: "Create testcase",
1509
+ description: `Create a new testcase under an AuraCheck feature. \`steps\` is the Midscene flow: pass EITHER an array of flow items (each item one action, e.g. { aiTap: "Sign in" }, { aiInput: "user@example.com", locate: "Email field" }, { aiAssert: "Dashboard is visible" }) OR a YAML/JSON string shaped as tasks[]. ${STEPS_DESCRIPTION} A bare array is auto-wrapped. Android/iOS cases are authored here exactly like web ones; they are RUN by a person in the AuraCheck desktop app on their own device (see start_run).
1510
+
1511
+ PRELATION \u2014 before writing \`steps\`, decide whether this case needs a starting state (logged in, on a specific page, seeded data). If it does, set \`prelationTestCaseId\` to an existing setup case (find one with list_testcases) instead of copying its steps into every case; create the setup case first if none exists. AuraCheck runs the prelation case automatically immediately before this one every time it runs \u2014 never add the prelation case to a run yourself. A prelation must be in the same project and never points at itself or forms a cycle.`,
1512
+ input: z8.object({
1513
+ projectId: PROJECT_ID7,
1514
+ featureId: z8.string().optional(),
1515
+ name: z8.string().min(1),
1516
+ steps: STEPS_SCHEMA,
1517
+ executionType: z8.enum(["automation", "manual"]).default("automation"),
1518
+ priority: z8.enum(["low", "medium", "high", "critical"]).optional(),
1519
+ category: z8.string().optional(),
1520
+ reason: z8.string().optional(),
1521
+ description: z8.string().optional(),
1522
+ expectedResult: z8.string().optional(),
1523
+ platforms: z8.array(z8.string()).optional(),
1524
+ coveredScenarios: z8.array(z8.string()).optional(),
1525
+ tags: z8.array(z8.string()).optional(),
1526
+ prelationTestCaseId: z8.string().optional()
1527
+ }),
1528
+ requires: "manageTestCases",
1529
+ billing: "write",
1530
+ surfaces: ["remote", "local"],
1531
+ handler: async (args, ctx) => {
1532
+ requireProjectId(ctx, args.projectId);
1533
+ const { projectId: _ignore, featureId, ...rest } = args;
1534
+ if (!featureId) {
1535
+ throw new Error("No featureId provided. Call list_features or create_feature first.");
1536
+ }
1537
+ return ctx.api.createTestCase(featureId, rest);
1538
+ }
1539
+ });
1540
+ var updateTestcase = defineTool({
1541
+ name: "update_testcase",
1542
+ title: "Update testcase",
1543
+ description: "Patch an existing testcase \u2014 only the fields you pass are touched. Useful in the auto-fix loop after reading evidence from a failed run. A `steps` patch accepts the same shapes as create_testcase. `patch.prelationTestCaseId` sets/replaces the setup case AuraCheck runs automatically before this one; pass `null` to clear it. It cannot be set to the case's own id, a case from another project, or create a cycle \u2014 the server rejects those.",
1544
+ input: z8.object({ id: z8.string().min(1), patch: z8.record(z8.any()) }),
1545
+ requires: "manageTestCases",
1546
+ billing: "write",
1547
+ surfaces: ["remote", "local"],
1548
+ handler: async ({ id, patch }, ctx) => ctx.api.updateTestCase(id, patch)
1549
+ });
1550
+ var deleteTestcase = defineTool({
1551
+ name: "delete_testcase",
1552
+ title: "Delete testcase",
1553
+ description: "Delete 1\u2013500 testcases. Requires manageTestCases. Without `confirm: true` this is a DRY RUN \u2014 it only lists what would be deleted and asks you to re-call with confirm:true; nothing is deleted on the first call. A case already linked to a run is soft-deleted (run history kept); a case never attached to a run is removed permanently.",
1554
+ input: z8.object({
1555
+ projectId: PROJECT_ID7,
1556
+ testCaseIds: z8.array(z8.string().min(1)).min(1).max(500),
1557
+ confirm: z8.boolean().optional()
1558
+ }),
1559
+ requires: "manageTestCases",
1560
+ billing: "write",
1561
+ surfaces: ["remote", "local"],
1562
+ annotations: { destructiveHint: true },
1563
+ handler: async ({ projectId, testCaseIds, confirm }, ctx) => {
1564
+ const pid = requireProjectId(ctx, projectId);
1565
+ try {
1566
+ if (!confirm) {
1567
+ const all = await ctx.api.listTestCasesByProject(pid);
1568
+ const byId = new Map(all.map((c) => [c.id, c]));
1569
+ const found = testCaseIds.map((id) => {
1570
+ const c = byId.get(id);
1571
+ return c ? { id, name: c.name, featureId: c.featureId } : { id, name: null, featureId: null, notFound: true };
100
1572
  });
1573
+ return {
1574
+ dryRun: true,
1575
+ wouldDelete: found,
1576
+ note: "Cases linked to a run are soft-deleted (run history kept); others are removed permanently. Re-call with confirm:true to actually delete."
1577
+ };
1578
+ }
1579
+ const result = await ctx.api.deleteTestCases(testCaseIds);
1580
+ return { dryRun: false, deletedIds: testCaseIds, ...result };
1581
+ } catch (err) {
1582
+ if (err instanceof ApiError && err.status === 403) {
1583
+ throw new Error("Delete failed (403): this sign-in lacks manageTestCases, or one of these cases belongs to a project it can't reach.");
1584
+ }
1585
+ if (err instanceof ApiError && err.status === 404) {
1586
+ throw new Error("Delete failed (404): one of these test case ids does not exist.");
1587
+ }
1588
+ throw err;
1589
+ }
1590
+ }
1591
+ });
1592
+ var TESTCASE_TOOLS = [
1593
+ listTestcases,
1594
+ getTestcase,
1595
+ createTestcase,
1596
+ updateTestcase,
1597
+ deleteTestcase
1598
+ ];
1599
+
1600
+ // ../mcp-core/dist/register.js
1601
+ var ALL_TOOLS = [
1602
+ ...ACCOUNT_TOOLS,
1603
+ ...FEATURE_TOOLS,
1604
+ ...TESTCASE_TOOLS,
1605
+ ...RUN_TOOLS,
1606
+ ...SCHEDULE_TOOLS,
1607
+ ...EXPLORATION_TOOLS,
1608
+ ...BUG_TOOLS,
1609
+ ...TEST_MY_FLOW_TOOLS
1610
+ ];
1611
+ var TOOLS_BY_NAME = new Map(ALL_TOOLS.map((t) => [t.name, t]));
1612
+ function getTool(name) {
1613
+ return TOOLS_BY_NAME.get(name);
1614
+ }
1615
+ function localName(t) {
1616
+ return t.localAlias ?? t.name;
1617
+ }
1618
+ var TOOLS_BY_LOCAL_NAME = new Map(ALL_TOOLS.map((t) => [localName(t), t]));
1619
+ async function callTool(name, rawArgs, ctx) {
1620
+ const tool = getTool(name);
1621
+ if (!tool) {
1622
+ return { ok: false, error: `Unknown tool: ${name}` };
1623
+ }
1624
+ if (!tool.surfaces.includes(ctx.surface)) {
1625
+ return {
1626
+ ok: false,
1627
+ error: `Tool ${name} is not available on this surface.`
1628
+ };
1629
+ }
1630
+ if (tool.requires && !ctx.account.user.capabilities.includes(tool.requires)) {
1631
+ const roleLabel = ctx.account.user.roleLabel;
1632
+ return {
1633
+ ok: false,
1634
+ error: `Your AuraCheck role (${roleLabel}) can't use ${name}. Ask your admin for the '${tool.requires}' permission.`
1635
+ };
1636
+ }
1637
+ let args;
1638
+ try {
1639
+ args = tool.input.parse(rawArgs ?? {});
1640
+ } catch (err) {
1641
+ return {
1642
+ ok: false,
1643
+ error: `Invalid arguments for ${name}: ${err?.message ?? String(err)}`
1644
+ };
1645
+ }
1646
+ try {
1647
+ const result = await tool.handler(args, ctx);
1648
+ return { ok: true, result: stripSecrets(result) };
1649
+ } catch (err) {
1650
+ if (err instanceof ApiError) {
1651
+ const mapped = mapApiError(err, ctx, tool.requires);
1652
+ if (mapped)
1653
+ return { ok: true, result: mapped };
1654
+ }
1655
+ return {
1656
+ ok: false,
1657
+ error: err instanceof Error ? err.message : String(err)
1658
+ };
1659
+ }
1660
+ }
1661
+
1662
+ // ../mcp-core/dist/standard-schema.js
1663
+ import { zodToJsonSchema as zodToJsonSchema2 } from "zod-to-json-schema";
1664
+ function toStandardSchemaWithJSON(schema) {
1665
+ const jsonSchema = zodToJsonSchema2(schema, {
1666
+ target: "jsonSchema7"
1667
+ });
1668
+ return {
1669
+ "~standard": {
1670
+ version: 1,
1671
+ vendor: "auracheck-mcp-core",
1672
+ validate(value) {
1673
+ const result = schema.safeParse(value);
1674
+ if (result.success)
1675
+ return { value: result.data };
1676
+ return {
1677
+ issues: result.error.issues.map((issue) => ({
1678
+ message: issue.message,
1679
+ path: issue.path
1680
+ }))
1681
+ };
1682
+ },
1683
+ jsonSchema: {
1684
+ input: () => jsonSchema,
1685
+ output: () => jsonSchema
1686
+ }
1687
+ }
1688
+ };
1689
+ }
1690
+
1691
+ // src/api.ts
1692
+ async function listCliTokens(opts) {
1693
+ const res = await fetch(
1694
+ `${normalizeBaseUrl(opts.baseUrl)}/api/auth/cli-tokens`,
1695
+ {
1696
+ headers: {
1697
+ Authorization: `Bearer ${opts.token}`,
1698
+ Accept: "application/json"
1699
+ }
1700
+ }
1701
+ );
1702
+ const text = await res.text();
1703
+ if (!res.ok)
1704
+ throw new ApiError(
1705
+ res.status,
1706
+ text,
1707
+ `GET /api/auth/cli-tokens -> ${res.status}`
1708
+ );
1709
+ return JSON.parse(text);
1710
+ }
1711
+ async function revokeCliToken(opts, id) {
1712
+ const res = await fetch(
1713
+ `${normalizeBaseUrl(opts.baseUrl)}/api/auth/cli-tokens/${encodeURIComponent(id)}`,
1714
+ {
1715
+ method: "DELETE",
1716
+ headers: {
1717
+ Authorization: `Bearer ${opts.token}`,
1718
+ Accept: "application/json"
1719
+ }
1720
+ }
1721
+ );
1722
+ const text = await res.text();
1723
+ if (!res.ok) {
1724
+ throw new ApiError(
1725
+ res.status,
1726
+ text,
1727
+ `DELETE /api/auth/cli-tokens/${id} -> ${res.status}`
1728
+ );
1729
+ }
1730
+ return text ? JSON.parse(text) : { ok: true };
1731
+ }
1732
+ async function exchangeCliCode(baseUrl, input) {
1733
+ const url = `${normalizeBaseUrl(baseUrl)}/api/auth/cli/exchange`;
1734
+ let res;
1735
+ try {
1736
+ res = await fetch(url, {
1737
+ method: "POST",
1738
+ headers: {
1739
+ "Content-Type": "application/json",
1740
+ Accept: "application/json"
1741
+ },
1742
+ body: JSON.stringify(input)
1743
+ });
1744
+ } catch (err) {
1745
+ throw new ApiError(0, "", `Network error calling ${url}: ${err.message}`);
1746
+ }
1747
+ const text = await res.text();
1748
+ let parsed = null;
1749
+ try {
1750
+ parsed = JSON.parse(text);
1751
+ } catch {
1752
+ }
1753
+ if (res.status === 404 || res.ok && !parsed?.token) {
1754
+ throw new ApiError(
1755
+ res.status,
1756
+ text,
1757
+ `${normalizeBaseUrl(baseUrl)} does not support browser sign-in for the CLI yet. Use \`auracheck login --token <67ci_\u2026>\` with a CI token from the project's Integrations page.`
1758
+ );
1759
+ }
1760
+ if (!res.ok) {
1761
+ throw new ApiError(
1762
+ res.status,
1763
+ text,
1764
+ `Sign-in failed (${res.status}): ${parsed?.error ?? text.slice(0, 200)}`
1765
+ );
1766
+ }
1767
+ return parsed;
1768
+ }
1769
+
1770
+ // src/config.ts
1771
+ import { promises as fs } from "fs";
1772
+ import { homedir } from "os";
1773
+ import path from "path";
1774
+ import { z as z9 } from "zod";
1775
+ var DEFAULT_EXCLUDE = [
1776
+ "node_modules",
1777
+ "dist",
1778
+ "build",
1779
+ ".git",
1780
+ ".next",
1781
+ ".turbo",
1782
+ "coverage",
1783
+ ".cache"
1784
+ ];
1785
+ var PROJECT_CONFIG_FILENAME = ".sixseven/config.json";
1786
+ var DEFAULT_BASE_URL = "https://space.auracheck.ai.id";
1787
+ var LEGACY_BASE_URLS = [
1788
+ "https://sixseven-space.sprout.co.id",
1789
+ "https://sixseven.sprout.co.id",
1790
+ "https://sixseven-api.sprout.co.id"
1791
+ ];
1792
+ function migrateLegacyBaseUrl(url) {
1793
+ const normalized = normalizeBaseUrl2(url);
1794
+ return LEGACY_BASE_URLS.includes(normalized) ? DEFAULT_BASE_URL : normalized;
1795
+ }
1796
+ function credentialsDir() {
1797
+ return process.env.AURACHECK_HOME ?? process.env.SIXSEVEN_HOME ?? path.join(homedir(), ".auracheck");
1798
+ }
1799
+ function credentialsFile() {
1800
+ return path.join(credentialsDir(), "credentials");
1801
+ }
1802
+ function legacyCredentialsDir() {
1803
+ if (process.env.AURACHECK_HOME || process.env.SIXSEVEN_HOME) return null;
1804
+ return path.join(homedir(), ".sixseven");
1805
+ }
1806
+ function legacyCredentialsFile() {
1807
+ const dir = legacyCredentialsDir();
1808
+ return dir ? path.join(dir, "credentials") : null;
1809
+ }
1810
+ var projectConfigSchema = z9.object({
1811
+ baseUrl: z9.string().url(),
1812
+ projectId: z9.string().min(1),
1813
+ defaultFeatureId: z9.string().nullish(),
1814
+ codeRoots: z9.array(z9.string().min(1)).default(["."]),
1815
+ exclude: z9.array(z9.string()).default(DEFAULT_EXCLUDE),
1816
+ platform: z9.enum(["web", "android", "ios"]).default("web")
1817
+ });
1818
+ var credentialsSchema = z9.object({
1819
+ tokens: z9.record(z9.string()).default({}),
1820
+ /** Base URL of the last `auracheck login`; used when no project config names one. */
1821
+ defaultBaseUrl: z9.string().optional(),
1822
+ /** Base URLs whose saved token was pasted with `--token` (not created by this sign-in). */
1823
+ pasted: z9.array(z9.string()).optional(),
1824
+ /**
1825
+ * Machine-wide default project, set by `auracheck.bind_project` (MCP) when
1826
+ * run outside a bound repo — i.e. there's no `.sixseven/config.json` to
1827
+ * write a per-repo binding into. A per-repo binding always wins over this.
1828
+ */
1829
+ defaultProjectId: z9.string().optional()
1830
+ });
1831
+ async function fileExists(p) {
1832
+ try {
1833
+ await fs.stat(p);
1834
+ return true;
1835
+ } catch {
1836
+ return false;
1837
+ }
1838
+ }
1839
+ async function findRepoRoot(start) {
1840
+ let cur = path.resolve(start);
1841
+ while (true) {
1842
+ if (await fileExists(path.join(cur, PROJECT_CONFIG_FILENAME))) {
1843
+ return cur;
1844
+ }
1845
+ const parent = path.dirname(cur);
1846
+ if (parent === cur) return null;
1847
+ cur = parent;
1848
+ }
1849
+ }
1850
+ async function readProjectConfig(repoRoot) {
1851
+ const p = path.join(repoRoot, PROJECT_CONFIG_FILENAME);
1852
+ const raw = await fs.readFile(p, "utf8");
1853
+ const parsed = JSON.parse(raw);
1854
+ const config = projectConfigSchema.parse(parsed);
1855
+ const baseUrl = migrateLegacyBaseUrl(config.baseUrl);
1856
+ if (baseUrl !== normalizeBaseUrl2(config.baseUrl)) {
1857
+ process.stderr.write(
1858
+ `AuraCheck CLI: ${PROJECT_CONFIG_FILENAME} points at a retired host; using ${baseUrl} for this run. Update "baseUrl" in that file to stop seeing this.
1859
+ `
1860
+ );
1861
+ return { ...config, baseUrl };
1862
+ }
1863
+ return config;
1864
+ }
1865
+ async function writeProjectConfig(repoRoot, cfg) {
1866
+ const dir = path.join(repoRoot, ".sixseven");
1867
+ await fs.mkdir(dir, { recursive: true });
1868
+ const p = path.join(dir, "config.json");
1869
+ await fs.writeFile(p, `${JSON.stringify(cfg, null, 2)}
1870
+ `, "utf8");
1871
+ return p;
1872
+ }
1873
+ function migrateLegacyCredentials(creds) {
1874
+ const tokens = {};
1875
+ for (const [key, token] of Object.entries(creds.tokens)) {
1876
+ const normalized = normalizeBaseUrl2(key);
1877
+ if (migrateLegacyBaseUrl(key) === normalized) tokens[normalized] = token;
1878
+ }
1879
+ const migratedFrom = /* @__PURE__ */ new Set();
1880
+ for (const [key, token] of Object.entries(creds.tokens)) {
1881
+ const normalized = normalizeBaseUrl2(key);
1882
+ const mapped = migrateLegacyBaseUrl(key);
1883
+ if (mapped === normalized) continue;
1884
+ migratedFrom.add(normalized);
1885
+ if (!(mapped in tokens)) tokens[mapped] = token;
1886
+ }
1887
+ const defaultBaseUrl = creds.defaultBaseUrl ? migrateLegacyBaseUrl(creds.defaultBaseUrl) : creds.defaultBaseUrl;
1888
+ const changed = migratedFrom.size > 0 || defaultBaseUrl !== creds.defaultBaseUrl;
1889
+ if (!changed) return { creds, changed: false, migratedFrom: [] };
1890
+ return {
1891
+ creds: { tokens, defaultBaseUrl, defaultProjectId: creds.defaultProjectId },
1892
+ changed: true,
1893
+ migratedFrom: [...migratedFrom]
1894
+ };
1895
+ }
1896
+ async function removeLegacyCredentials(legacyFile) {
1897
+ await fs.unlink(legacyFile).catch(() => {
1898
+ });
1899
+ const dir = path.dirname(legacyFile);
1900
+ const entries = await fs.readdir(dir).catch(() => null);
1901
+ if (entries && entries.length === 0) {
1902
+ await fs.rmdir(dir).catch(() => {
1903
+ });
1904
+ }
1905
+ }
1906
+ async function migrateCredentialsDirOnce() {
1907
+ const legacyFile = legacyCredentialsFile();
1908
+ if (!legacyFile || !await fileExists(legacyFile)) return;
1909
+ let legacyCreds;
1910
+ try {
1911
+ legacyCreds = credentialsSchema.parse(
1912
+ JSON.parse(await fs.readFile(legacyFile, "utf8"))
1913
+ );
1914
+ } catch {
1915
+ await removeLegacyCredentials(legacyFile);
1916
+ return;
1917
+ }
1918
+ const file = credentialsFile();
1919
+ if (!await fileExists(file)) {
1920
+ await fs.mkdir(credentialsDir(), { recursive: true, mode: 448 });
1921
+ await fs.writeFile(file, `${JSON.stringify(legacyCreds, null, 2)}
1922
+ `, {
1923
+ mode: 384
1924
+ });
1925
+ const verified = await fs.readFile(file, "utf8").then((raw) => credentialsSchema.parse(JSON.parse(raw))).catch(() => null);
1926
+ if (!verified || JSON.stringify(verified.tokens) !== JSON.stringify(legacyCreds.tokens)) {
1927
+ return;
1928
+ }
1929
+ } else {
1930
+ const existing = await fs.readFile(file, "utf8").then((raw) => credentialsSchema.parse(JSON.parse(raw))).catch(() => null);
1931
+ if (!existing) return;
1932
+ const mergedTokens = { ...legacyCreds.tokens, ...existing.tokens };
1933
+ if (Object.keys(mergedTokens).length !== Object.keys(existing.tokens).length) {
1934
+ await writeCredentials({ ...existing, tokens: mergedTokens });
1935
+ }
1936
+ }
1937
+ await removeLegacyCredentials(legacyFile);
1938
+ process.stderr.write(
1939
+ "AuraCheck CLI: moved your sign-in from ~/.sixseven to ~/.auracheck.\n"
1940
+ );
1941
+ }
1942
+ async function readCredentials() {
1943
+ await migrateCredentialsDirOnce();
1944
+ const file = credentialsFile();
1945
+ if (!await fileExists(file)) {
1946
+ return { tokens: {} };
1947
+ }
1948
+ const raw = await fs.readFile(file, "utf8");
1949
+ let creds;
1950
+ try {
1951
+ creds = credentialsSchema.parse(JSON.parse(raw));
1952
+ } catch {
1953
+ return { tokens: {} };
1954
+ }
1955
+ const migration = migrateLegacyCredentials(creds);
1956
+ if (migration.changed) {
1957
+ await writeCredentials(migration.creds);
1958
+ process.stderr.write(
1959
+ `AuraCheck CLI: your sign-in was saved for ${migration.migratedFrom.join(", ")}, which AuraCheck has moved off of. Switched it to ${DEFAULT_BASE_URL} \u2014 same account, nothing to redo.
1960
+ `
1961
+ );
1962
+ }
1963
+ return migration.creds;
1964
+ }
1965
+ async function writeCredentials(creds) {
1966
+ await fs.mkdir(credentialsDir(), { recursive: true, mode: 448 });
1967
+ await fs.writeFile(credentialsFile(), `${JSON.stringify(creds, null, 2)}
1968
+ `, {
1969
+ mode: 384
1970
+ });
1971
+ }
1972
+ async function saveToken(baseUrl, token, opts = {}) {
1973
+ const creds = await readCredentials();
1974
+ const key = normalizeBaseUrl2(baseUrl);
1975
+ for (const k of Object.keys(creds.tokens)) {
1976
+ if (k !== key && normalizeBaseUrl2(k) === key) delete creds.tokens[k];
1977
+ }
1978
+ creds.tokens[key] = token;
1979
+ creds.pasted = (creds.pasted ?? []).filter(
1980
+ (k) => normalizeBaseUrl2(k) !== key
1981
+ );
1982
+ if (opts.pasted) creds.pasted.push(key);
1983
+ if (opts.makeDefault) creds.defaultBaseUrl = key;
1984
+ await writeCredentials(creds);
1985
+ }
1986
+ async function isPastedToken(baseUrl) {
1987
+ const creds = await readCredentials();
1988
+ const key = normalizeBaseUrl2(baseUrl);
1989
+ return (creds.pasted ?? []).some((k) => normalizeBaseUrl2(k) === key);
1990
+ }
1991
+ async function removeToken(baseUrl) {
1992
+ const creds = await readCredentials();
1993
+ const key = normalizeBaseUrl2(baseUrl);
1994
+ creds.pasted = (creds.pasted ?? []).filter(
1995
+ (k) => normalizeBaseUrl2(k) !== key
1996
+ );
1997
+ let removed = false;
1998
+ for (const k of Object.keys(creds.tokens)) {
1999
+ if (normalizeBaseUrl2(k) === key) {
2000
+ delete creds.tokens[k];
2001
+ removed = true;
2002
+ }
2003
+ }
2004
+ if (creds.defaultBaseUrl && normalizeBaseUrl2(creds.defaultBaseUrl) === key) {
2005
+ creds.defaultBaseUrl = void 0;
2006
+ }
2007
+ if (removed) await writeCredentials(creds);
2008
+ return removed;
2009
+ }
2010
+ async function setDefaultProjectId(projectId) {
2011
+ const creds = await readCredentials();
2012
+ creds.defaultProjectId = projectId;
2013
+ await writeCredentials(creds);
2014
+ }
2015
+ async function getToken(baseUrl) {
2016
+ const creds = await readCredentials();
2017
+ const key = normalizeBaseUrl2(baseUrl);
2018
+ const exact = creds.tokens[key];
2019
+ if (exact) return exact;
2020
+ for (const [k, v] of Object.entries(creds.tokens)) {
2021
+ if (normalizeBaseUrl2(k) === key) return v;
2022
+ }
2023
+ return null;
2024
+ }
2025
+ function normalizeBaseUrl2(u) {
2026
+ return u.replace(new RegExp("\\p{Cc}", "gu"), "").trim().replace(/\/+$/, "");
2027
+ }
2028
+ async function loadContext(cwd) {
2029
+ const repoRoot = await findRepoRoot(cwd);
2030
+ if (!repoRoot) {
2031
+ throw new Error(
2032
+ `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent. Run \`auracheck init\` to create one.`
2033
+ );
2034
+ }
2035
+ const config = await readProjectConfig(repoRoot);
2036
+ const token = process.env.AURACHECK_TOKEN?.trim() || process.env.SIXSEVEN_TOKEN?.trim() || await getToken(config.baseUrl);
2037
+ if (!token) {
2038
+ throw new Error(
2039
+ `No saved token for ${config.baseUrl}. Run \`auracheck login\` first.`
2040
+ );
2041
+ }
2042
+ return {
2043
+ config,
2044
+ configPath: path.join(repoRoot, PROJECT_CONFIG_FILENAME),
2045
+ repoRoot,
2046
+ token
2047
+ };
2048
+ }
2049
+ async function resolveContext(cwd, overrides = {}) {
2050
+ const root = await findRepoRoot(cwd);
2051
+ const config = root ? await readProjectConfig(root) : null;
2052
+ const creds = await readCredentials();
2053
+ const rawBaseUrl = normalizeBaseUrl2(
2054
+ overrides.baseUrl || process.env.AURACHECK_BASE_URL || process.env.SIXSEVEN_BASE_URL || config?.baseUrl || creds.defaultBaseUrl || DEFAULT_BASE_URL
2055
+ );
2056
+ const baseUrl = migrateLegacyBaseUrl(rawBaseUrl);
2057
+ if (baseUrl !== rawBaseUrl) {
2058
+ process.stderr.write(
2059
+ `AuraCheck CLI: ${rawBaseUrl} is retired; using ${baseUrl} instead.
2060
+ `
2061
+ );
2062
+ }
2063
+ const projectId = overrides.projectId || process.env.AURACHECK_PROJECT_ID || process.env.SIXSEVEN_PROJECT_ID || config?.projectId || creds.defaultProjectId || null;
2064
+ const envToken = process.env.AURACHECK_TOKEN?.trim() || process.env.SIXSEVEN_TOKEN?.trim() || null;
2065
+ const savedToken = envToken ? null : await getToken(baseUrl);
2066
+ return {
2067
+ config,
2068
+ configPath: root ? path.join(root, PROJECT_CONFIG_FILENAME) : null,
2069
+ repoRoot: root ?? path.resolve(cwd),
2070
+ baseUrl,
2071
+ projectId,
2072
+ platform: config?.platform ?? "web",
2073
+ token: envToken ?? savedToken,
2074
+ tokenSource: envToken ? "env" : savedToken ? "credentials" : null
2075
+ };
2076
+ }
2077
+
2078
+ // src/commands/doctor.ts
2079
+ function ok(msg) {
2080
+ process.stdout.write(pc.green(` \u2713 ${msg}
2081
+ `));
2082
+ }
2083
+ function bad(msg) {
2084
+ process.stdout.write(pc.red(` \u2717 ${msg}
2085
+ `));
2086
+ process.exitCode = 1;
2087
+ }
2088
+ function warn(msg) {
2089
+ process.stdout.write(pc.yellow(` ! ${msg}
2090
+ `));
2091
+ }
2092
+ async function doctorCommand() {
2093
+ process.stdout.write(pc.bold("AuraCheck CLI doctor\n"));
2094
+ const repoRoot = await findRepoRoot(process.cwd());
2095
+ if (!repoRoot) {
2096
+ bad("No .sixseven/config.json found. Run `auracheck init`.");
2097
+ return;
2098
+ }
2099
+ ok(`repo root: ${repoRoot}`);
2100
+ let cfg;
2101
+ try {
2102
+ cfg = await readProjectConfig(repoRoot);
2103
+ ok(`config parsed: projectId=${cfg.projectId} platform=${cfg.platform}`);
2104
+ } catch (err) {
2105
+ bad(`config invalid: ${err.message}`);
2106
+ return;
2107
+ }
2108
+ const token = await getToken(cfg.baseUrl);
2109
+ if (!token) {
2110
+ bad(`no saved token for ${cfg.baseUrl}. Run \`auracheck login\`.`);
2111
+ return;
2112
+ }
2113
+ ok(`token present for ${cfg.baseUrl}`);
2114
+ try {
2115
+ const r = await fetch2(`${cfg.baseUrl}/api/auth/me`);
2116
+ if (r.status >= 200 && r.status < 600)
2117
+ ok(`backend reachable (${r.status})`);
2118
+ else warn(`backend status ${r.status}`);
2119
+ } catch (err) {
2120
+ bad(`backend unreachable: ${err.message}`);
2121
+ return;
2122
+ }
2123
+ const api = new AuraCheckApi({ baseUrl: cfg.baseUrl, token });
2124
+ try {
2125
+ const user = await api.me();
2126
+ ok(`token valid: ${user.email} (${user.role})`);
2127
+ } catch (err) {
2128
+ bad(`token invalid: ${err.message}`);
2129
+ return;
2130
+ }
2131
+ let features = [];
2132
+ try {
2133
+ features = await api.listFeatures(cfg.projectId);
2134
+ ok(`project ${cfg.projectId} accessible, ${features.length} feature(s)`);
2135
+ } catch (err) {
2136
+ bad(`project access failed: ${err.message}`);
2137
+ return;
2138
+ }
2139
+ try {
2140
+ const project = await api.getProject(cfg.projectId);
2141
+ const supported = project.platforms ?? [];
2142
+ if (supported.length && !supported.includes(cfg.platform)) {
2143
+ warn(
2144
+ `default platform "${cfg.platform}" is NOT in project.platforms [${supported.join(", ")}] \u2014 auracheck.create_run will fail until you fix .sixseven/config.json`
2145
+ );
2146
+ } else if (supported.length) {
2147
+ ok(`platform "${cfg.platform}" is supported by project`);
2148
+ }
2149
+ } catch {
2150
+ warn("could not verify project platforms (non-fatal)");
2151
+ }
2152
+ if (cfg.defaultFeatureId) {
2153
+ const exists = features.some((f) => f.id === cfg.defaultFeatureId);
2154
+ if (!exists) {
2155
+ warn(
2156
+ `defaultFeatureId ${cfg.defaultFeatureId} not found in project \u2014 clear it from .sixseven/config.json or pick a real feature id`
2157
+ );
2158
+ } else {
2159
+ ok("defaultFeatureId resolves to a real feature");
2160
+ }
2161
+ }
2162
+ }
2163
+
2164
+ // src/commands/init.ts
2165
+ import { promises as fs2 } from "fs";
2166
+ import path2 from "path";
2167
+ import pc2 from "picocolors";
2168
+ import prompts from "prompts";
2169
+ async function suggestCodeRoots(cwd) {
2170
+ const candidates = ["src", "app", "apps", "packages", "lib", "server"];
2171
+ const found = [];
2172
+ for (const c of candidates) {
2173
+ try {
2174
+ const stat = await fs2.stat(path2.join(cwd, c));
2175
+ if (stat.isDirectory()) found.push(c);
2176
+ } catch {
2177
+ }
2178
+ }
2179
+ return found.length ? found : ["."];
2180
+ }
2181
+ async function initCommand(opts) {
2182
+ const cwd = process.cwd();
2183
+ let baseUrl = opts.baseUrl;
2184
+ if (!baseUrl) {
2185
+ if (opts.nonInteractive) {
2186
+ const creds = await readCredentials();
2187
+ baseUrl = migrateLegacyBaseUrl(
2188
+ normalizeBaseUrl2(creds.defaultBaseUrl || DEFAULT_BASE_URL)
2189
+ );
2190
+ }
2191
+ }
2192
+ if (!baseUrl) {
2193
+ const ans = await prompts({
2194
+ type: "text",
2195
+ name: "baseUrl",
2196
+ message: "AuraCheck platform URL (not your app)",
2197
+ initial: "https://space.auracheck.ai.id"
2198
+ });
2199
+ baseUrl = ans.baseUrl;
2200
+ }
2201
+ if (!baseUrl) throw new Error("Aborted.");
2202
+ const token = await getToken(baseUrl);
2203
+ if (!token) {
2204
+ throw new Error(
2205
+ `No saved token for ${normalizeBaseUrl2(baseUrl)}. Run \`auracheck login\` first.`
2206
+ );
2207
+ }
2208
+ const api = new AuraCheckApi({ baseUrl, token });
2209
+ let projectId = opts.projectId;
2210
+ if (!projectId) {
2211
+ process.stdout.write(pc2.dim("Fetching projects...\n"));
2212
+ const projects = await api.listProjects();
2213
+ if (!projects.length) {
2214
+ throw new Error("No projects accessible with this token.");
2215
+ }
2216
+ if (opts.nonInteractive) {
2217
+ throw new Error("--project-id required in non-interactive mode");
2218
+ }
2219
+ const ans = await prompts({
2220
+ type: "select",
2221
+ name: "projectId",
2222
+ message: "Select AuraCheck project to bind this repo to",
2223
+ choices: projects.map((p) => ({
2224
+ title: p.name,
2225
+ description: p.id,
2226
+ value: p.id
2227
+ }))
2228
+ });
2229
+ projectId = ans.projectId;
2230
+ }
2231
+ if (!projectId) throw new Error("Aborted.");
2232
+ const codeRoots = await suggestCodeRoots(cwd);
2233
+ const platformAns = opts.nonInteractive ? { platform: "web" } : await prompts({
2234
+ type: "select",
2235
+ name: "platform",
2236
+ message: "Default platform for testcases",
2237
+ choices: [
2238
+ { title: "web", value: "web" },
2239
+ { title: "android", value: "android" },
2240
+ { title: "ios", value: "ios" }
2241
+ ],
2242
+ initial: 0
2243
+ });
2244
+ const cfg = projectConfigSchema.parse({
2245
+ baseUrl: normalizeBaseUrl2(baseUrl),
2246
+ projectId,
2247
+ defaultFeatureId: null,
2248
+ codeRoots,
2249
+ exclude: DEFAULT_EXCLUDE,
2250
+ platform: platformAns.platform ?? "web"
2251
+ });
2252
+ const written = await writeProjectConfig(cwd, cfg);
2253
+ process.stdout.write(pc2.green(`\u2713 Wrote ${path2.relative(cwd, written)}
2254
+ `));
2255
+ process.stdout.write(pc2.dim(` baseUrl: ${cfg.baseUrl}
2256
+ `));
2257
+ process.stdout.write(pc2.dim(` projectId: ${cfg.projectId}
2258
+ `));
2259
+ process.stdout.write(pc2.dim(` codeRoots: ${cfg.codeRoots.join(", ")}
2260
+ `));
2261
+ process.stdout.write(pc2.dim(` platform: ${cfg.platform}
2262
+ `));
2263
+ process.stdout.write(
2264
+ `
2265
+ Next: register the MCP server with Claude Code:
2266
+ ${pc2.cyan(" claude mcp add auracheck -- npx -y @auracheck-ai/cli mcp\n")}`
2267
+ );
2268
+ }
2269
+
2270
+ // src/commands/login.ts
2271
+ import os from "os";
2272
+ import pc3 from "picocolors";
2273
+ import prompts2 from "prompts";
2274
+
2275
+ // src/browser-login.ts
2276
+ import { spawn } from "child_process";
2277
+ import { createHash, randomBytes } from "crypto";
2278
+ import http from "http";
2279
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
2280
+ function makePkce() {
2281
+ const verifier = randomBytes(48).toString("base64url");
2282
+ return {
2283
+ state: randomBytes(24).toString("base64url"),
2284
+ verifier,
2285
+ challenge: createHash("sha256").update(verifier).digest("base64url")
2286
+ };
2287
+ }
2288
+ function buildLoginUrl(baseUrl, p) {
2289
+ const url = new URL("/desktop-login", `${normalizeBaseUrl2(baseUrl)}/`);
2290
+ url.searchParams.set("state", p.state);
2291
+ url.searchParams.set("code_challenge", p.challenge);
2292
+ url.searchParams.set("code_challenge_method", "S256");
2293
+ url.searchParams.set("redirect_uri", p.redirectUri);
2294
+ url.searchParams.set("client", "cli");
2295
+ return url.toString();
2296
+ }
2297
+ function openInBrowser(url) {
2298
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url]] : ["xdg-open", [url]];
2299
+ try {
2300
+ const child = spawn(cmd, args, {
2301
+ stdio: "ignore",
2302
+ detached: true
2303
+ });
2304
+ child.on("error", () => void 0);
2305
+ child.unref();
2306
+ } catch {
2307
+ }
2308
+ }
2309
+ var PAGE_STYLE = "font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px;line-height:1.5";
2310
+ var PAGE = (title, body) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="${PAGE_STYLE}"><h2>${title}</h2><p>${body}</p></body>`;
2311
+ async function browserLogin(opts) {
2312
+ const pkce = makePkce();
2313
+ const exchange = opts.exchange ?? exchangeCliCode;
2314
+ const server = http.createServer();
2315
+ await new Promise((resolve, reject) => {
2316
+ server.once("error", reject);
2317
+ server.listen(0, "127.0.0.1", () => resolve());
2318
+ });
2319
+ const { port } = server.address();
2320
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
2321
+ try {
2322
+ return await new Promise((resolve, reject) => {
2323
+ let settled = false;
2324
+ const timer = setTimeout(() => {
2325
+ settled = true;
2326
+ reject(
2327
+ new Error(
2328
+ "Timed out waiting for the browser sign-in. Run `auracheck login` again."
2329
+ )
2330
+ );
2331
+ }, opts.timeoutMs ?? LOGIN_TIMEOUT_MS);
2332
+ server.on("request", (req, res) => {
2333
+ const url = new URL(req.url ?? "/", redirectUri);
2334
+ if (url.pathname !== "/callback") {
2335
+ res.writeHead(404).end();
2336
+ return;
2337
+ }
2338
+ const send = (status, title, body) => {
2339
+ res.writeHead(status, {
2340
+ "Content-Type": "text/html; charset=utf-8",
2341
+ "Cache-Control": "no-store"
2342
+ });
2343
+ res.end(PAGE(title, body));
2344
+ };
2345
+ if (settled) {
2346
+ send(410, "Sign-in already finished", "You can close this tab.");
2347
+ return;
2348
+ }
2349
+ const code = url.searchParams.get("code");
2350
+ if (url.searchParams.get("state") !== pkce.state || !code) {
2351
+ send(
2352
+ 400,
2353
+ "This sign-in link is not for this terminal",
2354
+ "Go back to the terminal and run <code>auracheck login</code> again."
2355
+ );
2356
+ return;
2357
+ }
2358
+ settled = true;
2359
+ clearTimeout(timer);
2360
+ exchange(opts.baseUrl, {
2361
+ code,
2362
+ codeVerifier: pkce.verifier,
2363
+ redirectUri,
2364
+ label: opts.label
2365
+ }).then(
2366
+ (result) => {
2367
+ send(
2368
+ 200,
2369
+ "Signed in to the AuraCheck CLI",
2370
+ "You can close this tab and go back to your terminal."
2371
+ );
2372
+ resolve(result);
2373
+ },
2374
+ (err) => {
2375
+ send(
2376
+ 400,
2377
+ "Sign-in failed",
2378
+ "Go back to the terminal for details, then run <code>auracheck login</code> again."
2379
+ );
2380
+ reject(err);
2381
+ }
2382
+ );
2383
+ });
2384
+ const loginUrl = buildLoginUrl(opts.baseUrl, {
2385
+ state: pkce.state,
2386
+ challenge: pkce.challenge,
2387
+ redirectUri
2388
+ });
2389
+ opts.onUrl(loginUrl);
2390
+ if (opts.openBrowser !== false) openInBrowser(loginUrl);
2391
+ });
2392
+ } finally {
2393
+ server.close();
2394
+ server.closeAllConnections?.();
2395
+ }
2396
+ }
2397
+
2398
+ // src/commands/login.ts
2399
+ async function targetBaseUrl(flag) {
2400
+ return (await resolveContext(process.cwd(), { baseUrl: flag })).baseUrl;
2401
+ }
2402
+ function tokenPreview(token) {
2403
+ return `${token.slice(0, 12)}\u2026`;
2404
+ }
2405
+ async function loginCommand(opts) {
2406
+ const baseUrl = normalizeBaseUrl2(await targetBaseUrl(opts.baseUrl));
2407
+ let token = opts.token?.trim();
2408
+ if (!token && opts.promptToken) {
2409
+ if (opts.nonInteractive)
2410
+ throw new Error("--token required in non-interactive mode");
2411
+ const ans = await prompts2({
2412
+ type: "password",
2413
+ name: "token",
2414
+ message: "CI token (starts with 67ci_)",
2415
+ validate: (v) => v.startsWith("67ci_") ? true : "must start with 67ci_"
2416
+ });
2417
+ token = ans.token;
2418
+ if (!token) throw new Error("Aborted.");
2419
+ }
2420
+ if (token) {
2421
+ process.stdout.write(pc3.dim(`Verifying token against ${baseUrl}...
2422
+ `));
2423
+ const user = await new AuraCheckApi({ baseUrl, token }).me();
2424
+ await saveToken(baseUrl, token, { makeDefault: true, pasted: true });
2425
+ process.stdout.write(
2426
+ pc3.green(`\u2713 Logged in as ${user.email} (role: ${user.role})
2427
+ `)
2428
+ );
2429
+ process.stdout.write(
2430
+ pc3.dim(`Saved token for ${baseUrl} to ~/.auracheck/credentials
2431
+ `)
2432
+ );
2433
+ return;
2434
+ }
2435
+ if (opts.nonInteractive) {
2436
+ throw new Error("--token required in non-interactive mode");
2437
+ }
2438
+ const label = opts.label?.trim() || `AuraCheck CLI \xB7 ${os.hostname() || "unknown host"}`;
2439
+ process.stdout.write(pc3.bold(`Signing in to ${baseUrl}
2440
+ `));
2441
+ const result = await browserLogin({
2442
+ baseUrl,
2443
+ label,
2444
+ openBrowser: !opts.noBrowser,
2445
+ onUrl: (url) => {
2446
+ process.stdout.write(
2447
+ opts.noBrowser ? "Open this link in a browser on this computer to sign in:\n" : "Your browser should open. If it does not, open this link:\n"
2448
+ );
2449
+ process.stdout.write(` ${pc3.cyan(url)}
2450
+ `);
2451
+ process.stdout.write(pc3.dim("Waiting for you to allow the CLI...\n"));
2452
+ }
2453
+ });
2454
+ await saveToken(baseUrl, result.token, { makeDefault: true });
2455
+ process.stdout.write(
2456
+ pc3.green(
2457
+ `\u2713 Signed in as ${result.user.email} (role: ${result.user.role})
2458
+ `
2459
+ )
2460
+ );
2461
+ process.stdout.write(
2462
+ pc3.dim(
2463
+ `Saved to ~/.auracheck/credentials as "${result.label}". Revoke it any time under Profile \u2192 Active devices, or with \`auracheck logout\`.
2464
+ `
2465
+ )
2466
+ );
2467
+ }
2468
+ async function logoutCommand(opts) {
2469
+ const ctx = await resolveContext(process.cwd(), { baseUrl: opts.baseUrl });
2470
+ if (ctx.tokenSource === "env") {
2471
+ throw new Error(
2472
+ "The token comes from AURACHECK_TOKEN/SIXSEVEN_TOKEN; unset it instead (nothing was changed)."
2473
+ );
2474
+ }
2475
+ if (!ctx.token) {
2476
+ process.stdout.write(`Not signed in to ${ctx.baseUrl}.
2477
+ `);
2478
+ return;
2479
+ }
2480
+ if (await isPastedToken(ctx.baseUrl)) {
2481
+ await removeToken(ctx.baseUrl);
2482
+ process.stdout.write(
2483
+ pc3.green(`\u2713 Signed out of ${ctx.baseUrl}`) + pc3.dim(
2484
+ "\nThe token was pasted with --token, so it was only removed from this computer and still works elsewhere. Revoke it under Profile \u2192 Active devices (or the project's Integrations page) if you no longer need it.\n"
2485
+ )
2486
+ );
2487
+ return;
2488
+ }
2489
+ let revoked = false;
2490
+ try {
2491
+ const { tokens } = await listCliTokens({
2492
+ baseUrl: ctx.baseUrl,
2493
+ token: ctx.token
2494
+ });
2495
+ const current = tokens.find((t) => t.current);
2496
+ if (current) {
2497
+ await revokeCliToken(
2498
+ { baseUrl: ctx.baseUrl, token: ctx.token },
2499
+ current.id
2500
+ );
2501
+ revoked = true;
2502
+ }
2503
+ } catch (err) {
2504
+ if (!(err instanceof ApiError) || ![401, 403, 404].includes(err.status)) {
2505
+ throw err;
2506
+ }
2507
+ }
2508
+ await removeToken(ctx.baseUrl);
2509
+ process.stdout.write(
2510
+ pc3.green(`\u2713 Signed out of ${ctx.baseUrl}`) + (revoked ? pc3.dim(" (token revoked)\n") : pc3.dim(
2511
+ "\nThis was a project CI token; it still works until it's revoked on the project's Integrations page.\n"
2512
+ ))
2513
+ );
2514
+ }
2515
+ async function authStatusCommand(opts) {
2516
+ const ctx = await resolveContext(process.cwd(), { baseUrl: opts.baseUrl });
2517
+ process.stdout.write(pc3.bold("AuraCheck CLI sign-in\n"));
2518
+ process.stdout.write(` baseUrl: ${ctx.baseUrl}
2519
+ `);
2520
+ process.stdout.write(
2521
+ ` project: ${ctx.projectId ?? pc3.dim("none bound (MCP tools take a projectId)")}
2522
+ `
2523
+ );
2524
+ if (ctx.configPath) process.stdout.write(` config: ${ctx.configPath}
2525
+ `);
2526
+ if (!ctx.token) {
2527
+ process.stdout.write(
2528
+ pc3.red(" token: \u2717 not signed in \u2014 run `auracheck login`\n")
2529
+ );
2530
+ process.exitCode = 1;
2531
+ return;
2532
+ }
2533
+ process.stdout.write(
2534
+ ` token: ${tokenPreview(ctx.token)} (${ctx.tokenSource === "env" ? "AURACHECK_TOKEN" : "~/.auracheck/credentials"})
2535
+ `
2536
+ );
2537
+ const api = new AuraCheckApi({ baseUrl: ctx.baseUrl, token: ctx.token });
2538
+ try {
2539
+ const user = await api.me();
2540
+ process.stdout.write(
2541
+ pc3.green(` user: \u2713 ${user.email} (role: ${user.role})
2542
+ `)
2543
+ );
2544
+ process.stdout.write(
2545
+ ` company: ${user.companyName ?? user.companyId ?? pc3.dim("none")}
2546
+ `
2547
+ );
2548
+ } catch (err) {
2549
+ process.stdout.write(pc3.red(` user: \u2717 ${err.message}
2550
+ `));
2551
+ process.exitCode = 1;
2552
+ return;
2553
+ }
2554
+ try {
2555
+ const { tokens } = await listCliTokens({
2556
+ baseUrl: ctx.baseUrl,
2557
+ token: ctx.token
2558
+ });
2559
+ const current = tokens.find((t) => t.current);
2560
+ process.stdout.write(
2561
+ ` kind: ${current ? `personal CLI sign-in "${current.label}"` : "personal CLI sign-in"}
2562
+ `
2563
+ );
2564
+ } catch (err) {
2565
+ if (err instanceof ApiError && err.status === 403) {
2566
+ process.stdout.write(
2567
+ ` kind: project CI token ${pc3.dim("(only reaches its own project; `auracheck login` gives a personal sign-in)")}
2568
+ `
2569
+ );
2570
+ } else if (err instanceof ApiError && err.status === 404) {
2571
+ process.stdout.write(
2572
+ ` kind: CI token ${pc3.dim("(server predates CLI sign-in)")}
2573
+ `
2574
+ );
2575
+ }
2576
+ }
2577
+ }
2578
+
2579
+ // src/commands/setup.ts
2580
+ import { spawn as spawn2, spawnSync } from "child_process";
2581
+ import { promises as fs3 } from "fs";
2582
+ import path3 from "path";
2583
+ import pc4 from "picocolors";
2584
+ import prompts3 from "prompts";
2585
+ function hasBinaryOnPath(bin) {
2586
+ const r = spawnSync(process.platform === "win32" ? "where" : "which", [bin], {
2587
+ stdio: "ignore"
2588
+ });
2589
+ return r.status === 0;
2590
+ }
2591
+ function resolveMcpInvocation() {
2592
+ if (hasBinaryOnPath("auracheck")) {
2593
+ return { command: "auracheck", args: ["mcp"], display: "auracheck mcp" };
2594
+ }
2595
+ const entry = process.argv[1];
2596
+ return {
2597
+ command: process.execPath,
2598
+ args: [entry, "mcp"],
2599
+ display: `node ${entry} mcp`
2600
+ };
2601
+ }
2602
+ async function registerWithClaudeCode(invocation) {
2603
+ if (!hasBinaryOnPath("claude")) {
2604
+ process.stdout.write(
2605
+ pc4.yellow(
2606
+ "! `claude` CLI not found on PATH \u2014 skipping auto-registration.\n"
2607
+ )
2608
+ );
2609
+ return false;
2610
+ }
2611
+ return await new Promise((resolve) => {
2612
+ const child = spawn2(
2613
+ "claude",
2614
+ ["mcp", "add", "auracheck", "--", invocation.command, ...invocation.args],
2615
+ { stdio: "inherit" }
2616
+ );
2617
+ child.on("exit", (code) => resolve(code === 0));
2618
+ child.on("error", () => resolve(false));
2619
+ });
2620
+ }
2621
+ function printManualSnippets(target, invocation) {
2622
+ const argsJson = JSON.stringify(invocation.args);
2623
+ if (target === "cursor") {
2624
+ process.stdout.write(
2625
+ `
2626
+ ${pc4.bold("Add to")} ${pc4.cyan(".cursor/mcp.json")}:
2627
+ `
2628
+ );
2629
+ process.stdout.write(
2630
+ `${pc4.dim(
2631
+ JSON.stringify(
2632
+ {
2633
+ mcpServers: {
2634
+ auracheck: { command: invocation.command, args: invocation.args }
2635
+ }
2636
+ },
2637
+ null,
2638
+ 2
2639
+ )
2640
+ )}
2641
+ `
2642
+ );
2643
+ return;
2644
+ }
2645
+ if (target === "claude-desktop") {
2646
+ process.stdout.write(
2647
+ `
2648
+ ${pc4.bold("Add to Claude Desktop config")} (${pc4.cyan("~/Library/Application Support/Claude/claude_desktop_config.json")} on macOS):
2649
+ `
2650
+ );
2651
+ process.stdout.write(
2652
+ `${pc4.dim(
2653
+ JSON.stringify(
2654
+ {
2655
+ mcpServers: {
2656
+ auracheck: { command: invocation.command, args: invocation.args }
2657
+ }
2658
+ },
2659
+ null,
2660
+ 2
2661
+ )
2662
+ )}
2663
+ `
2664
+ );
2665
+ void argsJson;
2666
+ }
2667
+ }
2668
+ async function setupCommand(opts) {
2669
+ const cwd = process.cwd();
2670
+ process.stdout.write(
2671
+ pc4.bold("AuraCheck setup\n") + pc4.dim("Walks through: login \u2192 bind project \u2192 register MCP.\n\n")
2672
+ );
2673
+ let baseUrl = opts.baseUrl;
2674
+ if (!baseUrl && !opts.nonInteractive) {
2675
+ const ans = await prompts3({
2676
+ type: "text",
2677
+ name: "baseUrl",
2678
+ message: "AuraCheck platform URL (not your app)",
2679
+ initial: "https://space.auracheck.ai.id",
2680
+ validate: (v) => /^https?:\/\//.test(v) ? true : "must start with http(s)://"
101
2681
  });
102
- loginOptions(auth.command('login').description('Same as `auracheck login`')).action(runLogin);
103
- auth
104
- .command('logout')
105
- .description('Same as `auracheck logout`')
106
- .option('--base-url <url>', 'AuraCheck base URL')
107
- .action(async (opts) => {
108
- await logoutCommand({ baseUrl: opts.baseUrl });
109
- });
110
- program
111
- .command('init')
112
- .description('Create .sixseven/config.json bound to a SixSeven project')
113
- .option('--base-url <url>', 'SixSeven base URL')
114
- .option('--project-id <id>', 'SixSeven project id')
115
- .option('--non-interactive', 'fail instead of prompting')
116
- .action(async (opts) => {
117
- await initCommand({
118
- baseUrl: opts.baseUrl,
119
- projectId: opts.projectId,
120
- nonInteractive: !!opts.nonInteractive,
2682
+ baseUrl = ans.baseUrl;
2683
+ }
2684
+ if (!baseUrl) throw new Error("Aborted (no base URL).");
2685
+ const existingToken = await getToken(baseUrl);
2686
+ let tokenValid = false;
2687
+ if (existingToken) {
2688
+ try {
2689
+ const api = new AuraCheckApi({ baseUrl, token: existingToken });
2690
+ const user = await api.me();
2691
+ process.stdout.write(
2692
+ pc4.green(
2693
+ `\u2713 Token already saved for ${normalizeBaseUrl2(baseUrl)} (${user.email}). Skipping login.
2694
+ `
2695
+ )
2696
+ );
2697
+ tokenValid = true;
2698
+ } catch {
2699
+ process.stdout.write(
2700
+ pc4.yellow(
2701
+ `! Saved token for ${normalizeBaseUrl2(baseUrl)} is invalid \u2014 re-login required.
2702
+ `
2703
+ )
2704
+ );
2705
+ }
2706
+ }
2707
+ if (!tokenValid) {
2708
+ process.stdout.write(pc4.bold("\n[1/3] Login\n"));
2709
+ await loginCommand({
2710
+ baseUrl,
2711
+ token: opts.token,
2712
+ nonInteractive: !!opts.nonInteractive
2713
+ });
2714
+ }
2715
+ process.stdout.write(pc4.bold("\n[2/3] Bind project\n"));
2716
+ const existing = await readProjectConfig(cwd).catch(() => null);
2717
+ let shouldInit = true;
2718
+ if (existing) {
2719
+ process.stdout.write(
2720
+ pc4.dim(
2721
+ ` Found existing .sixseven/config.json \u2192 projectId ${existing.projectId} on ${existing.baseUrl}
2722
+ `
2723
+ )
2724
+ );
2725
+ if (opts.nonInteractive) {
2726
+ shouldInit = false;
2727
+ } else {
2728
+ const ans = await prompts3({
2729
+ type: "confirm",
2730
+ name: "rebind",
2731
+ message: "Re-bind this repo to a different project?",
2732
+ initial: false
2733
+ });
2734
+ shouldInit = !!ans.rebind;
2735
+ }
2736
+ }
2737
+ if (shouldInit) {
2738
+ await initCommand({
2739
+ baseUrl,
2740
+ projectId: opts.projectId,
2741
+ nonInteractive: !!opts.nonInteractive
2742
+ });
2743
+ } else {
2744
+ process.stdout.write(pc4.dim(" Keeping existing binding.\n"));
2745
+ }
2746
+ process.stdout.write(pc4.bold("\n[3/3] Register MCP server\n"));
2747
+ if (opts.skipMcp) {
2748
+ process.stdout.write(pc4.dim(" --skip-mcp set, skipping.\n"));
2749
+ return;
2750
+ }
2751
+ const invocation = resolveMcpInvocation();
2752
+ process.stdout.write(
2753
+ pc4.dim(` MCP launch command: ${invocation.display}
2754
+
2755
+ `)
2756
+ );
2757
+ let target;
2758
+ if (opts.nonInteractive) {
2759
+ target = "claude-code";
2760
+ } else {
2761
+ const ans = await prompts3({
2762
+ type: "select",
2763
+ name: "target",
2764
+ message: "Where do you want to register the MCP server?",
2765
+ choices: [
2766
+ {
2767
+ title: "Claude Code (auto via `claude mcp add`)",
2768
+ value: "claude-code"
2769
+ },
2770
+ { title: "Cursor (print .cursor/mcp.json snippet)", value: "cursor" },
2771
+ {
2772
+ title: "Claude Desktop (print config snippet)",
2773
+ value: "claude-desktop"
2774
+ },
2775
+ { title: "Skip \u2014 I will do it manually", value: "skip" }
2776
+ ],
2777
+ initial: 0
2778
+ });
2779
+ target = ans.target ?? "skip";
2780
+ }
2781
+ if (target === "claude-code") {
2782
+ const ok2 = await registerWithClaudeCode(invocation);
2783
+ if (ok2) {
2784
+ process.stdout.write(
2785
+ pc4.green(
2786
+ '\n\u2713 Registered as MCP server "auracheck" with Claude Code.\n'
2787
+ )
2788
+ );
2789
+ } else {
2790
+ process.stdout.write(
2791
+ pc4.yellow("\n! Auto-registration failed. Run manually:\n") + pc4.cyan(
2792
+ ` claude mcp add auracheck -- ${invocation.command} ${invocation.args.join(" ")}
2793
+ `
2794
+ )
2795
+ );
2796
+ }
2797
+ } else if (target === "skip") {
2798
+ process.stdout.write(
2799
+ pc4.dim(" Manual command:\n") + pc4.cyan(
2800
+ ` claude mcp add auracheck -- ${invocation.command} ${invocation.args.join(" ")}
2801
+ `
2802
+ )
2803
+ );
2804
+ } else {
2805
+ printManualSnippets(target, invocation);
2806
+ }
2807
+ const cfgPath = path3.join(cwd, ".sixseven", "config.json");
2808
+ const cfgExists = await fs3.stat(cfgPath).then(() => true).catch(() => false);
2809
+ process.stdout.write(
2810
+ `
2811
+ ${pc4.bold("Done.")} ${pc4.dim("Next:")}
2812
+ ${pc4.dim(
2813
+ ` \u2022 auracheck status \u2014 verify binding (${cfgExists ? "config OK" : "no config"})
2814
+ `
2815
+ )}${pc4.dim(" \u2022 auracheck doctor \u2014 full diagnostics\n")}${pc4.dim(' \u2022 Open Claude Code and ask: "list auracheck features"\n')}`
2816
+ );
2817
+ }
2818
+
2819
+ // src/commands/status.ts
2820
+ import pc5 from "picocolors";
2821
+ async function statusCommand() {
2822
+ const ctx = await loadContext(process.cwd());
2823
+ const api = new AuraCheckApi({
2824
+ baseUrl: ctx.config.baseUrl,
2825
+ token: ctx.token
2826
+ });
2827
+ process.stdout.write(pc5.bold("AuraCheck CLI status\n"));
2828
+ process.stdout.write(` config: ${ctx.configPath}
2829
+ `);
2830
+ process.stdout.write(` repoRoot: ${ctx.repoRoot}
2831
+ `);
2832
+ process.stdout.write(` baseUrl: ${ctx.config.baseUrl}
2833
+ `);
2834
+ process.stdout.write(` projectId: ${ctx.config.projectId}
2835
+ `);
2836
+ process.stdout.write(` platform: ${ctx.config.platform}
2837
+ `);
2838
+ process.stdout.write(` codeRoots: ${ctx.config.codeRoots.join(", ")}
2839
+ `);
2840
+ try {
2841
+ const user = await api.me();
2842
+ process.stdout.write(
2843
+ pc5.green(
2844
+ ` token: \u2713 valid (user: ${user.email}, role: ${user.role})
2845
+ `
2846
+ )
2847
+ );
2848
+ } catch (err) {
2849
+ process.stdout.write(pc5.red(` token: \u2717 ${err.message}
2850
+ `));
2851
+ process.exitCode = 1;
2852
+ return;
2853
+ }
2854
+ try {
2855
+ const features = await api.listFeatures(ctx.config.projectId);
2856
+ process.stdout.write(` features: ${features.length}
2857
+ `);
2858
+ const tcs = await api.listTestCasesByProject(ctx.config.projectId);
2859
+ process.stdout.write(` testcases: ${tcs.length}
2860
+ `);
2861
+ } catch (err) {
2862
+ process.stdout.write(pc5.yellow(` warn: ${err.message}
2863
+ `));
2864
+ }
2865
+ }
2866
+
2867
+ // src/mcp/server.ts
2868
+ import { hostname } from "os";
2869
+ import { McpServer } from "@modelcontextprotocol/server";
2870
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
2871
+ import { z as z10 } from "zod";
2872
+
2873
+ // src/source-reader.ts
2874
+ import { promises as fs4 } from "fs";
2875
+ import path4 from "path";
2876
+ var DEFAULT_MAX_FILE_BYTES = 2e5;
2877
+ var DEFAULT_MAX_SEARCH_RESULTS = 200;
2878
+ var TEXT_EXT = /* @__PURE__ */ new Set([
2879
+ ".ts",
2880
+ ".tsx",
2881
+ ".js",
2882
+ ".jsx",
2883
+ ".mjs",
2884
+ ".cjs",
2885
+ ".json",
2886
+ ".yml",
2887
+ ".yaml",
2888
+ ".md",
2889
+ ".html",
2890
+ ".css",
2891
+ ".scss",
2892
+ ".less",
2893
+ ".toml",
2894
+ ".env",
2895
+ ".txt",
2896
+ ".py",
2897
+ ".go",
2898
+ ".rb",
2899
+ ".java",
2900
+ ".kt",
2901
+ ".swift",
2902
+ ".rs",
2903
+ ".php",
2904
+ ".cs",
2905
+ ".vue",
2906
+ ".svelte",
2907
+ ".sql",
2908
+ ".graphql",
2909
+ ".prisma"
2910
+ ]);
2911
+ var SourceReader = class {
2912
+ repoRoot;
2913
+ roots;
2914
+ excludeNames;
2915
+ excludeGlobs;
2916
+ maxFileBytes;
2917
+ constructor(opts) {
2918
+ this.repoRoot = path4.resolve(opts.repoRoot);
2919
+ this.roots = (opts.config.codeRoots.length ? opts.config.codeRoots : ["."]).map((r) => path4.resolve(this.repoRoot, r));
2920
+ const excludeNames = /* @__PURE__ */ new Set();
2921
+ const excludeGlobs = [];
2922
+ for (const e of opts.config.exclude) {
2923
+ if (e.includes("/") || e.includes("*")) excludeGlobs.push(e);
2924
+ else excludeNames.add(e);
2925
+ }
2926
+ this.excludeNames = excludeNames;
2927
+ this.excludeGlobs = excludeGlobs;
2928
+ this.maxFileBytes = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
2929
+ }
2930
+ /**
2931
+ * Resolve a user-supplied relative path. Rejects paths outside the repo root
2932
+ * and outside any configured codeRoot.
2933
+ */
2934
+ resolveSafe(relPath) {
2935
+ const cleaned = relPath.replace(/^[./\\]+/, "").replace(/\\/g, "/");
2936
+ const abs = path4.resolve(this.repoRoot, cleaned);
2937
+ const repoRel = path4.relative(this.repoRoot, abs);
2938
+ if (repoRel.startsWith("..") || path4.isAbsolute(repoRel)) {
2939
+ throw new Error(`Path escapes repo root: ${relPath}`);
2940
+ }
2941
+ if (!this.roots.some(
2942
+ (root) => abs === root || abs.startsWith(root + path4.sep)
2943
+ )) {
2944
+ throw new Error(
2945
+ `Path is outside configured codeRoots (${this.roots.map((r) => path4.relative(this.repoRoot, r)).join(", ")}): ${relPath}`
2946
+ );
2947
+ }
2948
+ if (this.isExcluded(abs)) {
2949
+ throw new Error(`Path matches exclude pattern: ${relPath}`);
2950
+ }
2951
+ return abs;
2952
+ }
2953
+ isExcluded(absPath) {
2954
+ const rel = path4.relative(this.repoRoot, absPath);
2955
+ const parts = rel.split(path4.sep);
2956
+ if (parts.some((p) => this.excludeNames.has(p))) return true;
2957
+ for (const g of this.excludeGlobs) {
2958
+ if (rel.includes(g.replace(/\*/g, ""))) return true;
2959
+ }
2960
+ return false;
2961
+ }
2962
+ async readFile(relPath) {
2963
+ const abs = this.resolveSafe(relPath);
2964
+ const stat = await fs4.stat(abs);
2965
+ if (!stat.isFile()) throw new Error(`Not a file: ${relPath}`);
2966
+ const ext = path4.extname(abs).toLowerCase();
2967
+ if (ext && !TEXT_EXT.has(ext)) {
2968
+ throw new Error(
2969
+ `Refusing to read non-text file: ${relPath} (extension ${ext})`
2970
+ );
2971
+ }
2972
+ const buf = await fs4.readFile(abs);
2973
+ const truncated = buf.byteLength > this.maxFileBytes;
2974
+ const sliced = truncated ? buf.subarray(0, this.maxFileBytes) : buf;
2975
+ return {
2976
+ path: path4.relative(this.repoRoot, abs),
2977
+ bytes: stat.size,
2978
+ content: sliced.toString("utf8"),
2979
+ truncated
2980
+ };
2981
+ }
2982
+ async listDir(relPath) {
2983
+ const abs = this.resolveSafe(relPath || ".");
2984
+ const stat = await fs4.stat(abs);
2985
+ if (!stat.isDirectory()) throw new Error(`Not a directory: ${relPath}`);
2986
+ const dirents = await fs4.readdir(abs, { withFileTypes: true });
2987
+ const entries = dirents.filter((d) => !this.isExcluded(path4.join(abs, d.name))).map((d) => ({
2988
+ name: d.name,
2989
+ type: d.isDirectory() ? "dir" : "file"
2990
+ })).sort(
2991
+ (a, b) => a.type === b.type ? a.name.localeCompare(b.name) : a.type === "dir" ? -1 : 1
2992
+ );
2993
+ return { path: path4.relative(this.repoRoot, abs), entries };
2994
+ }
2995
+ /**
2996
+ * Substring/regex search across configured codeRoots. Returns up to
2997
+ * maxResults matches (default 200). Walks the tree itself — no shell.
2998
+ */
2999
+ async search(query, opts = {}) {
3000
+ if (!query) return [];
3001
+ const maxResults = opts.maxResults ?? DEFAULT_MAX_SEARCH_RESULTS;
3002
+ const flags = opts.caseSensitive ? "g" : "gi";
3003
+ const re = opts.regex ? new RegExp(query, flags) : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags);
3004
+ const results = [];
3005
+ const walk = async (dir) => {
3006
+ if (results.length >= maxResults) return;
3007
+ let dirents;
3008
+ try {
3009
+ dirents = await fs4.readdir(dir, { withFileTypes: true });
3010
+ } catch {
3011
+ return;
3012
+ }
3013
+ for (const d of dirents) {
3014
+ if (results.length >= maxResults) return;
3015
+ const abs = path4.join(dir, d.name);
3016
+ if (this.isExcluded(abs)) continue;
3017
+ if (d.isDirectory()) {
3018
+ await walk(abs);
3019
+ } else if (d.isFile()) {
3020
+ const ext = path4.extname(d.name).toLowerCase();
3021
+ if (ext && !TEXT_EXT.has(ext)) continue;
3022
+ let content;
3023
+ try {
3024
+ const buf = await fs4.readFile(abs);
3025
+ if (buf.byteLength > this.maxFileBytes) continue;
3026
+ content = buf.toString("utf8");
3027
+ } catch {
3028
+ continue;
3029
+ }
3030
+ const lines = content.split(/\r?\n/);
3031
+ for (let i = 0; i < lines.length; i++) {
3032
+ const line = lines[i];
3033
+ if (re.test(line)) {
3034
+ results.push({
3035
+ file: path4.relative(this.repoRoot, abs),
3036
+ line: i + 1,
3037
+ preview: line.length > 240 ? `${line.slice(0, 240)}\u2026` : line
3038
+ });
3039
+ if (results.length >= maxResults) return;
3040
+ }
3041
+ re.lastIndex = 0;
3042
+ }
3043
+ }
3044
+ }
3045
+ };
3046
+ for (const root of this.roots) {
3047
+ await walk(root);
3048
+ if (results.length >= maxResults) break;
3049
+ }
3050
+ return results;
3051
+ }
3052
+ };
3053
+
3054
+ // src/mcp/server.ts
3055
+ var CLI_VERSION = "0.2.5";
3056
+ var LOCAL_ALL_CAPABILITIES = [
3057
+ "viewProject",
3058
+ "viewReports",
3059
+ "manageTestCases",
3060
+ "manageRuns",
3061
+ "runTests",
3062
+ "manageProjectSetup",
3063
+ "manageBugs"
3064
+ ];
3065
+ function fallbackAccountContext(user, baseUrl) {
3066
+ return {
3067
+ user: {
3068
+ id: user?.id ?? "unknown",
3069
+ name: user?.name ?? null,
3070
+ email: user?.email ?? "",
3071
+ roleLabel: user?.role ?? "unknown",
3072
+ capabilities: LOCAL_ALL_CAPABILITIES
3073
+ },
3074
+ company: { id: user?.companyId ?? "", name: "" },
3075
+ projects: [],
3076
+ subscription: {
3077
+ status: "unknown",
3078
+ planName: "",
3079
+ daysLeft: null,
3080
+ readOnly: false,
3081
+ inGrace: false,
3082
+ billingEnabled: false,
3083
+ runUsage: null
3084
+ },
3085
+ adminContact: null,
3086
+ renewalUrl: `${baseUrl}/admin/billing`,
3087
+ minLocalMcp: CLI_VERSION
3088
+ };
3089
+ }
3090
+ async function resolveLocalAccount(api, baseUrl) {
3091
+ try {
3092
+ const account = await api.mcpContext();
3093
+ return {
3094
+ ...account,
3095
+ user: { ...account.user, capabilities: LOCAL_ALL_CAPABILITIES }
3096
+ };
3097
+ } catch {
3098
+ const user = await api.me().catch(() => null);
3099
+ return fallbackAccountContext(user, baseUrl);
3100
+ }
3101
+ }
3102
+ var LOCAL_TOOLS = [
3103
+ // ---------- Whitebox: source code ----------
3104
+ {
3105
+ name: "auracheck.read_code",
3106
+ description: "Read a text file from the developer repo. Path is relative to repo root and must fall within configured codeRoots. Use to understand routes, components, validators, and fixtures before generating a testcase.",
3107
+ zod: z10.object({ path: z10.string().min(1) }),
3108
+ handler: async ({ path: path6 }, { reader }) => reader.readFile(path6)
3109
+ },
3110
+ {
3111
+ name: "auracheck.list_dir",
3112
+ description: "List entries of a directory inside the developer repo. Path is relative to repo root.",
3113
+ zod: z10.object({ path: z10.string().default(".") }),
3114
+ handler: async ({ path: path6 }, { reader }) => reader.listDir(path6)
3115
+ },
3116
+ {
3117
+ name: "auracheck.search_code",
3118
+ description: "Search developer repo (within codeRoots) for a substring or regex. Returns up to 200 matches with file + line + preview. Use to locate routes, handlers, components by name.",
3119
+ zod: z10.object({
3120
+ query: z10.string().min(1),
3121
+ regex: z10.boolean().optional(),
3122
+ caseSensitive: z10.boolean().optional(),
3123
+ maxResults: z10.number().int().positive().max(1e3).optional()
3124
+ }),
3125
+ handler: async (args, { reader }) => reader.search(args.query, args)
3126
+ },
3127
+ // ---------- AuraCheck: project context & onboarding ----------
3128
+ {
3129
+ name: "auracheck.whoami",
3130
+ description: "Report sign-in status, the base URL, and the project this MCP session is bound to, plus a nextStep hint for what to do next (sign in, bind a project, or nothing \u2014 already set up). Safe to call first, before signing in.",
3131
+ zod: z10.object({}).passthrough(),
3132
+ handler: async (_args, { api, signedIn, baseUrl, tokenSource }) => {
3133
+ const boundProjectId = await currentDefaultProjectId();
3134
+ if (!signedIn) {
3135
+ return {
3136
+ signedIn: false,
3137
+ baseUrl,
3138
+ cliVersion: CLI_VERSION,
3139
+ projectId: boundProjectId,
3140
+ nextStep: "Not signed in \u2014 call auracheck.login."
3141
+ };
3142
+ }
3143
+ const [user, project] = await Promise.all([
3144
+ api.me(),
3145
+ boundProjectId ? api.getProject(boundProjectId).catch(() => null) : Promise.resolve(null)
3146
+ ]);
3147
+ return {
3148
+ signedIn: true,
3149
+ user,
3150
+ baseUrl,
3151
+ tokenSource,
3152
+ cliVersion: CLI_VERSION,
3153
+ projectId: boundProjectId,
3154
+ project,
3155
+ nextStep: boundProjectId ? null : "No project bound \u2014 call auracheck.list_projects, ask the person which one, then auracheck.bind_project({ projectId })."
3156
+ };
3157
+ }
3158
+ },
3159
+ {
3160
+ name: "auracheck.login",
3161
+ description: "Sign in to AuraCheck through the browser (same OAuth/PKCE flow as `auracheck login` in a terminal) \u2014 no terminal needed. Opens the system browser and waits up to ~90s for the person to click Allow. If it times out before that, it returns the sign-in url and 'Not finished \u2014 call auracheck.login again to resume.'; calling it again starts a fresh attempt (no duplicate tokens are saved \u2014 a new sign-in simply replaces the old one for this baseUrl). On success the token is saved exactly like the CLI command, and tool calls that needed auracheck.login now work.",
3162
+ zod: z10.object({
3163
+ baseUrl: z10.string().url().optional(),
3164
+ timeoutSec: z10.number().int().positive().max(600).optional()
3165
+ }),
3166
+ handler: async (args, { baseUrl: ctxBaseUrl }) => {
3167
+ const baseUrl = normalizeBaseUrl2(args.baseUrl ?? ctxBaseUrl);
3168
+ let signInUrl = "";
3169
+ try {
3170
+ const result = await browserLogin({
3171
+ baseUrl,
3172
+ label: `AuraCheck MCP \xB7 ${hostname() || "unknown host"}`,
3173
+ timeoutMs: (args.timeoutSec ?? 90) * 1e3,
3174
+ openBrowser: process.env.AURACHECK_NO_BROWSER !== "1",
3175
+ onUrl: (url) => {
3176
+ signInUrl = url;
3177
+ }
121
3178
  });
3179
+ await saveToken(baseUrl, result.token, { makeDefault: true });
3180
+ return {
3181
+ ok: true,
3182
+ baseUrl,
3183
+ user: result.user,
3184
+ message: `Signed in as ${result.user.email}.`
3185
+ };
3186
+ } catch (err) {
3187
+ if (signInUrl) {
3188
+ return {
3189
+ ok: false,
3190
+ baseUrl,
3191
+ url: signInUrl,
3192
+ message: "Not finished \u2014 the browser sign-in was not completed in time. Call auracheck.login again to resume (open the url yourself if the browser did not open)."
3193
+ };
3194
+ }
3195
+ throw err;
3196
+ }
3197
+ }
3198
+ },
3199
+ {
3200
+ name: "auracheck.logout",
3201
+ description: "Forget the locally saved sign-in for this baseUrl. Local only \u2014 does not revoke the token on the server (do that from Profile \u2192 Active devices if needed).",
3202
+ zod: z10.object({ baseUrl: z10.string().url().optional() }),
3203
+ handler: async (args, { baseUrl: ctxBaseUrl }) => {
3204
+ const baseUrl = normalizeBaseUrl2(args.baseUrl ?? ctxBaseUrl);
3205
+ const removed = await removeToken(baseUrl);
3206
+ return { ok: true, baseUrl, removed };
3207
+ }
3208
+ },
3209
+ {
3210
+ name: "auracheck.bind_project",
3211
+ description: "Set the default AuraCheck project for this repo (if a .sixseven/config.json binding exists or can be created in the current working directory) or, otherwise, as this machine-wide default \u2014 the same fallback project tools use when no projectId is passed. Verifies the id against auracheck.list_projects when signed in. Onboarding order: auracheck.login \u2192 auracheck.list_projects \u2192 ask the person which one \u2192 auracheck.bind_project.",
3212
+ zod: z10.object({ projectId: z10.string().min(1) }),
3213
+ handler: async ({ projectId }, { api, signedIn, repoRoot, config }) => {
3214
+ if (signedIn) {
3215
+ const projects = await api.listProjects().catch(() => null);
3216
+ if (projects && !projects.some((p) => p.id === projectId)) {
3217
+ throw new Error(
3218
+ `${projectId} is not in the list of projects this sign-in can reach. Call auracheck.list_projects.`
3219
+ );
3220
+ }
3221
+ }
3222
+ if (config) {
3223
+ const path6 = await writeProjectConfig(repoRoot, {
3224
+ ...config,
3225
+ projectId
3226
+ });
3227
+ return { ok: true, scope: "repo", projectId, configPath: path6 };
3228
+ }
3229
+ await setDefaultProjectId(projectId);
3230
+ return { ok: true, scope: "global", projectId };
3231
+ }
3232
+ },
3233
+ // ---------- AuraCheck: get_screenshot (local keeps its own outPath arg) ----------
3234
+ {
3235
+ name: "auracheck.get_screenshot",
3236
+ description: "Download a run screenshot (or any authenticated blob) to a local file and return its path, so it can then be opened and looked at. Pass a `screenshotUrl` straight from auracheck.get_evidence \u2014 those are bare paths that cannot be fetched without the bound base URL and CI token, so this is the only way to actually SEE a step's screenshot. Reach for it whenever a failure's cause is visual: 'the page froze' is often disproved by two consecutive screenshots being identical, or by the page rendering fine with a control merely disabled.",
3237
+ zod: z10.object({
3238
+ url: z10.string().min(1).describe(
3239
+ "screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host."
3240
+ ),
3241
+ outPath: z10.string().optional().describe(
3242
+ "Where to write it. Defaults to a temp file named after the blob."
3243
+ )
3244
+ }),
3245
+ handler: async (args, { api }) => {
3246
+ const { tmpdir } = await import("os");
3247
+ const path6 = await import("path");
3248
+ const { mkdir, writeFile } = await import("fs/promises");
3249
+ const { bytes, contentType } = await api.downloadBlob(args.url);
3250
+ const base = path6.basename(args.url.split("?")[0] || "").replace(/[^\w.-]/g, "_") || "screenshot.png";
3251
+ const dest = args.outPath ?? path6.join(tmpdir(), `auracheck-${Date.now()}-${base}`);
3252
+ await mkdir(path6.dirname(dest), { recursive: true });
3253
+ await writeFile(dest, bytes);
3254
+ return {
3255
+ path: dest,
3256
+ bytes: bytes.length,
3257
+ contentType,
3258
+ hint: "Open this path with your file-reading tool to view the image."
3259
+ };
3260
+ }
3261
+ }
3262
+ ];
3263
+ var NO_AUTH_TOOLS = /* @__PURE__ */ new Set([
3264
+ "auracheck.login",
3265
+ "auracheck.logout",
3266
+ "auracheck.whoami",
3267
+ "auracheck.bind_project"
3268
+ ]);
3269
+ var CODE_TOOLS = /* @__PURE__ */ new Set([
3270
+ "auracheck.read_code",
3271
+ "auracheck.list_dir",
3272
+ "auracheck.search_code"
3273
+ ]);
3274
+ function logErr(msg) {
3275
+ process.stderr.write(`[auracheck-mcp] ${msg}
3276
+ `);
3277
+ }
3278
+ var NotSignedInError = class extends Error {
3279
+ constructor(baseUrl) {
3280
+ super(
3281
+ `Not signed in to AuraCheck (${baseUrl}). Call auracheck.login (or run \`auracheck login\` in a terminal) \u2014 the MCP server picks up the new sign-in on the next call, no restart needed.`
3282
+ );
3283
+ }
3284
+ };
3285
+ var ONBOARDING_INSTRUCTIONS = `This server works before sign-in: auracheck.whoami, auracheck.login, auracheck.logout, auracheck.bind_project, and tools/list all work with no credentials. Every other tool needs a sign-in and a bound project.
3286
+
3287
+ First-run order for a new user: 1) auracheck.whoami to check status. 2) If not signed in, auracheck.login \u2014 it opens the person's browser and waits up to ~90s for them to click Allow; if it times out, call it again. 3) auracheck.list_projects, ask the person which project, then auracheck.bind_project({ projectId }). 4) Proceed with the project tools (they fall back to the bound project when projectId is omitted).
3288
+
3289
+ ${serverInstructions("local")}`;
3290
+ function toolResultContent(result) {
3291
+ return {
3292
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
3293
+ };
3294
+ }
3295
+ function errorResultContent(err) {
3296
+ return {
3297
+ isError: true,
3298
+ content: [
3299
+ {
3300
+ type: "text",
3301
+ text: err instanceof Error ? err.message : String(err)
3302
+ }
3303
+ ]
3304
+ };
3305
+ }
3306
+ var overridesRef = {};
3307
+ var runtimeCtx;
3308
+ async function currentDefaultProjectId() {
3309
+ if (overridesRef.projectId) return overridesRef.projectId;
3310
+ const envProjectId = process.env.AURACHECK_PROJECT_ID || process.env.SIXSEVEN_PROJECT_ID;
3311
+ if (envProjectId) return envProjectId;
3312
+ if (runtimeCtx.configPath) {
3313
+ const fresh = await readProjectConfig(runtimeCtx.repoRoot).catch(
3314
+ () => null
3315
+ );
3316
+ if (fresh?.projectId) return fresh.projectId;
3317
+ }
3318
+ const creds = await readCredentials();
3319
+ return creds.defaultProjectId ?? null;
3320
+ }
3321
+ async function runMcpServer(overrides = {}) {
3322
+ overridesRef = overrides;
3323
+ const ctx = await resolveContext(process.cwd(), overrides);
3324
+ runtimeCtx = ctx;
3325
+ const reader = new SourceReader({
3326
+ repoRoot: ctx.repoRoot,
3327
+ config: ctx.config ?? {
3328
+ baseUrl: ctx.baseUrl,
3329
+ projectId: ctx.projectId ?? "",
3330
+ defaultFeatureId: null,
3331
+ codeRoots: ["."],
3332
+ exclude: DEFAULT_EXCLUDE,
3333
+ platform: ctx.platform
3334
+ }
3335
+ });
3336
+ let cached = null;
3337
+ async function currentApi() {
3338
+ const token = ctx.tokenSource === "env" ? ctx.token : await getToken(ctx.baseUrl);
3339
+ if (!token) throw new NotSignedInError(ctx.baseUrl);
3340
+ if (cached?.token !== token) {
3341
+ cached = {
3342
+ token,
3343
+ api: new AuraCheckApi({
3344
+ baseUrl: ctx.baseUrl,
3345
+ token,
3346
+ signInHint: "Run `auracheck login` in a terminal to sign in again."
3347
+ })
3348
+ };
3349
+ }
3350
+ return cached.api;
3351
+ }
3352
+ const server = new McpServer(
3353
+ { name: "auracheck", version: CLI_VERSION },
3354
+ { instructions: ONBOARDING_INSTRUCTIONS }
3355
+ );
3356
+ for (const tool of LOCAL_TOOLS) {
3357
+ server.registerTool(
3358
+ tool.name,
3359
+ {
3360
+ description: tool.description,
3361
+ inputSchema: toStandardSchemaWithJSON(tool.zod)
3362
+ },
3363
+ async (rawArgs) => {
3364
+ try {
3365
+ const parsed = tool.zod.parse(rawArgs ?? {});
3366
+ let api;
3367
+ let signedIn;
3368
+ if (CODE_TOOLS.has(tool.name)) {
3369
+ api = null;
3370
+ signedIn = false;
3371
+ } else if (NO_AUTH_TOOLS.has(tool.name)) {
3372
+ try {
3373
+ api = await currentApi();
3374
+ signedIn = true;
3375
+ } catch {
3376
+ api = null;
3377
+ signedIn = false;
3378
+ }
3379
+ } else {
3380
+ api = await currentApi();
3381
+ signedIn = true;
3382
+ }
3383
+ const localCtx = {
3384
+ api,
3385
+ signedIn,
3386
+ reader,
3387
+ baseUrl: ctx.baseUrl,
3388
+ tokenSource: ctx.tokenSource === "env" ? "env" : "credentials",
3389
+ config: ctx.config,
3390
+ repoRoot: ctx.repoRoot
3391
+ };
3392
+ const result = await tool.handler(parsed, localCtx);
3393
+ return toolResultContent(result);
3394
+ } catch (err) {
3395
+ return errorResultContent(err);
3396
+ }
3397
+ }
3398
+ );
3399
+ }
3400
+ for (const tool of ALL_TOOLS.filter((t) => t.surfaces.includes("local"))) {
3401
+ server.registerTool(
3402
+ `auracheck.${localName(tool)}`,
3403
+ {
3404
+ title: tool.title,
3405
+ description: tool.description,
3406
+ inputSchema: toStandardSchemaWithJSON(tool.input),
3407
+ annotations: tool.annotations
3408
+ },
3409
+ async (rawArgs) => {
3410
+ try {
3411
+ const api = await currentApi();
3412
+ const account = await resolveLocalAccount(api, ctx.baseUrl);
3413
+ const defaultProjectId = await currentDefaultProjectId();
3414
+ const toolCtx = {
3415
+ api,
3416
+ surface: "local",
3417
+ appUrl: ctx.baseUrl,
3418
+ renewalUrl: account.renewalUrl,
3419
+ account,
3420
+ projectId: defaultProjectId,
3421
+ defaultPlatform: ctx.platform,
3422
+ onSetProject: async (projectId) => {
3423
+ if (ctx.config) {
3424
+ await writeProjectConfig(ctx.repoRoot, {
3425
+ ...ctx.config,
3426
+ projectId
3427
+ });
3428
+ } else {
3429
+ await setDefaultProjectId(projectId);
3430
+ }
3431
+ },
3432
+ waitForRunMaxSec: 300
3433
+ };
3434
+ const result = await callTool(tool.name, rawArgs, toolCtx);
3435
+ if (result.ok) return toolResultContent(result.result);
3436
+ return errorResultContent(new Error(result.error));
3437
+ } catch (err) {
3438
+ return errorResultContent(err);
3439
+ }
3440
+ }
3441
+ );
3442
+ }
3443
+ for (const prompt of PROMPTS) {
3444
+ server.registerPrompt(
3445
+ prompt.name,
3446
+ { title: prompt.name, description: prompt.description },
3447
+ () => ({
3448
+ messages: [
3449
+ {
3450
+ role: "user",
3451
+ content: { type: "text", text: prompt.text }
3452
+ }
3453
+ ]
3454
+ })
3455
+ );
3456
+ }
3457
+ serveStdio(() => server, {
3458
+ // 2025-era clients (Claude Code's current MCP client, as of this
3459
+ // writing) open with the legacy `initialize` handshake; pin them to a
3460
+ // 2025-era instance from this same factory rather than rejecting them.
3461
+ legacy: "serve"
3462
+ });
3463
+ logErr(
3464
+ `ready v${CLI_VERSION}. baseUrl=${ctx.baseUrl} project=${ctx.projectId ?? "(none bound)"} repo=${ctx.repoRoot}`
3465
+ );
3466
+ currentApi().then((api) => api.me()).then((u) => logErr(`signed in as ${u.email} (${u.role})`)).catch(
3467
+ (err) => logErr(
3468
+ `sign-in check failed: ${err instanceof ApiError || err instanceof NotSignedInError ? err.message : String(err)}`
3469
+ )
3470
+ );
3471
+ }
3472
+
3473
+ // src/bin.ts
3474
+ var version = "0.2.5";
3475
+ function invokedCommandName() {
3476
+ const argv1 = process.argv[1] ?? "";
3477
+ const base = path5.basename(argv1).replace(/\.(c|m)?js$/, "");
3478
+ return base === "sixseven" ? "sixseven" : "auracheck";
3479
+ }
3480
+ async function main() {
3481
+ const program = new Command();
3482
+ program.name(invokedCommandName()).description(
3483
+ "AuraCheck CLI \u2014 login, init repo, and run an MCP server so Claude Code can author whitebox testcases against your app. (`sixseven` also works, same command.)"
3484
+ ).version(version);
3485
+ program.command("setup").description(
3486
+ "Guided wizard: login \u2192 bind project \u2192 register MCP with Claude Code in one go"
3487
+ ).option("--base-url <url>", "AuraCheck base URL").option("--token <token>", "CI token starting with 67ci_").option("--project-id <id>", "AuraCheck project id").option("--skip-mcp", "do not register the MCP server").option("--non-interactive", "fail instead of prompting").action(async (opts) => {
3488
+ await setupCommand({
3489
+ baseUrl: opts.baseUrl,
3490
+ token: opts.token,
3491
+ projectId: opts.projectId,
3492
+ skipMcp: !!opts.skipMcp,
3493
+ nonInteractive: !!opts.nonInteractive
122
3494
  });
123
- program
124
- .command('status')
125
- .description('Show current binding, token validity, and project counts')
126
- .action(async () => {
127
- await statusCommand();
3495
+ });
3496
+ const loginOptions = (cmd) => cmd.option(
3497
+ "--base-url <url>",
3498
+ "AuraCheck base URL (default: last login, else https://space.auracheck.ai.id)"
3499
+ ).option(
3500
+ "--token <token>",
3501
+ "use a CI token (67ci_\u2026) instead of the browser sign-in \u2014 for CI"
3502
+ ).option("--paste-token", "prompt for a CI token instead of the browser").option("--no-browser", "print the sign-in link instead of opening it").option("--label <name>", "name shown under Active devices").option("--non-interactive", "fail instead of prompting");
3503
+ const runLogin = async (opts) => {
3504
+ await loginCommand({
3505
+ baseUrl: opts.baseUrl,
3506
+ token: opts.token,
3507
+ promptToken: !!opts.pasteToken,
3508
+ noBrowser: opts.browser === false,
3509
+ label: opts.label,
3510
+ nonInteractive: !!opts.nonInteractive
128
3511
  });
129
- program
130
- .command('doctor')
131
- .description('Run diagnostics: config, token, backend reachability, project access')
132
- .action(async () => {
133
- await doctorCommand();
3512
+ };
3513
+ loginOptions(
3514
+ program.command("login").description(
3515
+ "Sign in through your browser (or with --token for CI); the CLI and MCP server use it"
3516
+ )
3517
+ ).action(runLogin);
3518
+ program.command("logout").description("Revoke this sign-in and forget the saved token").option("--base-url <url>", "AuraCheck base URL").action(async (opts) => {
3519
+ await logoutCommand({ baseUrl: opts.baseUrl });
3520
+ });
3521
+ const auth = program.command("auth").description(
3522
+ "Sign-in commands: `auth status`, `auth login`, `auth logout`; `auth --token <t>` saves a CI token"
3523
+ ).option("--base-url <url>", "AuraCheck base URL").option("--token <token>", "save a CI token (67ci_\u2026) for this base URL").action(async (opts) => {
3524
+ if (opts.token) {
3525
+ await loginCommand({
3526
+ baseUrl: opts.baseUrl,
3527
+ token: opts.token,
3528
+ nonInteractive: true
3529
+ });
3530
+ return;
3531
+ }
3532
+ await authStatusCommand({ baseUrl: opts.baseUrl });
3533
+ });
3534
+ auth.command("status").description(
3535
+ "Show who the CLI/MCP is signed in as (never prints the token)"
3536
+ ).option("--base-url <url>", "AuraCheck base URL").action(async (opts, cmd) => {
3537
+ await authStatusCommand({
3538
+ baseUrl: opts.baseUrl ?? cmd.parent?.opts().baseUrl
134
3539
  });
135
- program
136
- .command('mcp')
137
- .description('Start the SixSeven MCP server on stdio (spawned by Claude Code)')
138
- .option('--project <id>', 'default project (else SIXSEVEN_PROJECT_ID, else .sixseven/config.json)')
139
- .option('--base-url <url>', 'AuraCheck base URL')
140
- .action(async (opts) => {
141
- await runMcpServer({ projectId: opts.project, baseUrl: opts.baseUrl });
3540
+ });
3541
+ loginOptions(
3542
+ auth.command("login").description("Same as `auracheck login`")
3543
+ ).action(runLogin);
3544
+ auth.command("logout").description("Same as `auracheck logout`").option("--base-url <url>", "AuraCheck base URL").action(async (opts) => {
3545
+ await logoutCommand({ baseUrl: opts.baseUrl });
3546
+ });
3547
+ program.command("init").description("Create .sixseven/config.json bound to an AuraCheck project").option("--base-url <url>", "AuraCheck base URL").option("--project-id <id>", "AuraCheck project id").option("--non-interactive", "fail instead of prompting").action(async (opts) => {
3548
+ await initCommand({
3549
+ baseUrl: opts.baseUrl,
3550
+ projectId: opts.projectId,
3551
+ nonInteractive: !!opts.nonInteractive
142
3552
  });
143
- await program.parseAsync(process.argv);
3553
+ });
3554
+ program.command("status").description("Show current binding, token validity, and project counts").action(async () => {
3555
+ await statusCommand();
3556
+ });
3557
+ program.command("doctor").description(
3558
+ "Run diagnostics: config, token, backend reachability, project access"
3559
+ ).action(async () => {
3560
+ await doctorCommand();
3561
+ });
3562
+ program.command("mcp").description(
3563
+ "Start the AuraCheck MCP server on stdio (spawned by Claude Code)"
3564
+ ).option(
3565
+ "--project <id>",
3566
+ "default project (else AURACHECK_PROJECT_ID, else .sixseven/config.json)"
3567
+ ).option("--base-url <url>", "AuraCheck base URL").action(async (opts) => {
3568
+ await runMcpServer({ projectId: opts.project, baseUrl: opts.baseUrl });
3569
+ });
3570
+ await program.parseAsync(process.argv);
144
3571
  }
145
3572
  main().catch((err) => {
146
- process.stderr.write(pc.red(`\nerror: ${err?.message ?? err}\n`));
147
- if (process.env.SIXSEVEN_DEBUG) {
148
- process.stderr.write(`${String(err?.stack ?? '')}\n`);
149
- }
150
- process.exit(1);
3573
+ process.stderr.write(pc6.red(`
3574
+ error: ${err?.message ?? err}
3575
+ `));
3576
+ if (process.env.AURACHECK_DEBUG || process.env.SIXSEVEN_DEBUG) {
3577
+ process.stderr.write(`${String(err?.stack ?? "")}
3578
+ `);
3579
+ }
3580
+ process.exit(1);
151
3581
  });
152
3582
  //# sourceMappingURL=bin.js.map