@spekn/cli 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/main.js +34806 -29538
  2. package/dist/prompts/governance-analysis.prompt.md +109 -0
  3. package/dist/resources/prompts/repo-analysis.prompt.md +28 -136
  4. package/dist/resources/prompts/repo-sync-analysis.prompt.md +31 -68
  5. package/dist/tui/app.d.ts +7 -0
  6. package/dist/tui/app.js +122 -0
  7. package/dist/tui/args.d.ts +8 -0
  8. package/dist/tui/args.js +57 -0
  9. package/dist/tui/capabilities/policy.d.ts +7 -0
  10. package/dist/tui/capabilities/policy.js +64 -0
  11. package/dist/tui/chunk-4WEASLXY.mjs +3444 -0
  12. package/dist/tui/chunk-755CADEG.mjs +3401 -0
  13. package/dist/tui/chunk-BUJQVTY5.mjs +3409 -0
  14. package/dist/tui/chunk-BZKKMGFB.mjs +1959 -0
  15. package/dist/tui/chunk-DJYOBCNM.mjs +3159 -0
  16. package/dist/tui/chunk-GTFTFDY4.mjs +3417 -0
  17. package/dist/tui/chunk-IMEBD2KA.mjs +3444 -0
  18. package/dist/tui/chunk-IX6DR5SW.mjs +3433 -0
  19. package/dist/tui/chunk-JKFOY4IF.mjs +2003 -0
  20. package/dist/tui/chunk-OXXZ3O5L.mjs +3378 -0
  21. package/dist/tui/chunk-SHJNIAAJ.mjs +1697 -0
  22. package/dist/tui/chunk-V4SNDRUS.mjs +1666 -0
  23. package/dist/tui/chunk-VXVHNZST.mjs +1666 -0
  24. package/dist/tui/chunk-WCTSFKTA.mjs +3459 -0
  25. package/dist/tui/chunk-X2XP5ACW.mjs +3443 -0
  26. package/dist/tui/chunk-YUYJ7VBG.mjs +2029 -0
  27. package/dist/tui/chunk-ZM3EI5IA.mjs +3384 -0
  28. package/dist/tui/chunk-ZYOX64HP.mjs +1653 -0
  29. package/dist/tui/components/frame.d.ts +8 -0
  30. package/dist/tui/components/frame.js +8 -0
  31. package/dist/tui/components/status-bar.d.ts +8 -0
  32. package/dist/tui/components/status-bar.js +8 -0
  33. package/dist/tui/index.d.ts +2 -0
  34. package/dist/tui/index.js +23 -0
  35. package/dist/tui/index.mjs +6999 -6938
  36. package/dist/tui/keymap/use-global-keymap.d.ts +19 -0
  37. package/dist/tui/keymap/use-global-keymap.js +82 -0
  38. package/dist/tui/navigation/nav-items.d.ts +3 -0
  39. package/dist/tui/navigation/nav-items.js +18 -0
  40. package/dist/tui/prompts/spec-creation-system.prompt.md +47 -0
  41. package/dist/tui/prompts/spec-refinement-system.prompt.md +72 -0
  42. package/dist/tui/screens/bridge.d.ts +8 -0
  43. package/dist/tui/screens/bridge.js +19 -0
  44. package/dist/tui/screens/decisions.d.ts +5 -0
  45. package/dist/tui/screens/decisions.js +28 -0
  46. package/dist/tui/screens/export.d.ts +5 -0
  47. package/dist/tui/screens/export.js +16 -0
  48. package/dist/tui/screens/home.d.ts +5 -0
  49. package/dist/tui/screens/home.js +33 -0
  50. package/dist/tui/screens/locked.d.ts +5 -0
  51. package/dist/tui/screens/locked.js +9 -0
  52. package/dist/tui/screens/specs.d.ts +5 -0
  53. package/dist/tui/screens/specs.js +31 -0
  54. package/dist/tui/services/client.d.ts +1 -0
  55. package/dist/tui/services/client.js +18 -0
  56. package/dist/tui/services/context-service.d.ts +19 -0
  57. package/dist/tui/services/context-service.js +246 -0
  58. package/dist/tui/shared-enums.d.ts +16 -0
  59. package/dist/tui/shared-enums.js +19 -0
  60. package/dist/tui/state/use-app-state.d.ts +35 -0
  61. package/dist/tui/state/use-app-state.js +177 -0
  62. package/dist/tui/types.d.ts +77 -0
  63. package/dist/tui/types.js +2 -0
  64. package/dist/tui/use-session-store-63YUGUFA.mjs +8 -0
  65. package/dist/tui/use-session-store-ACO2SMJC.mjs +8 -0
  66. package/dist/tui/use-session-store-BVFDAWOB.mjs +8 -0
  67. package/dist/tui/use-session-store-DJIZ3FQZ.mjs +9 -0
  68. package/dist/tui/use-session-store-EAIQA4UG.mjs +9 -0
  69. package/dist/tui/use-session-store-EFBAXC3G.mjs +8 -0
  70. package/dist/tui/use-session-store-FJOR4KTG.mjs +8 -0
  71. package/dist/tui/use-session-store-IJE5KVOC.mjs +8 -0
  72. package/dist/tui/use-session-store-KGAFXCKI.mjs +8 -0
  73. package/dist/tui/use-session-store-KS4DPNDY.mjs +8 -0
  74. package/dist/tui/use-session-store-MMHJENNL.mjs +8 -0
  75. package/dist/tui/use-session-store-OZ6HC4I2.mjs +9 -0
  76. package/dist/tui/use-session-store-PTMWISNJ.mjs +8 -0
  77. package/dist/tui/use-session-store-VCDECQMW.mjs +8 -0
  78. package/dist/tui/use-session-store-VOK5ML5J.mjs +9 -0
  79. package/package.json +6 -3
@@ -0,0 +1,2003 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __esm = (fn, res) => function __init() {
15
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
+ };
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
40
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
+
42
+ // src/auth/credentials-store.ts
43
+ import * as fs from "fs";
44
+ import * as os from "os";
45
+ import * as path from "path";
46
+ import { z } from "zod";
47
+ var CliCredentialsSchema = z.object({
48
+ accessToken: z.string(),
49
+ refreshToken: z.string(),
50
+ expiresAt: z.number(),
51
+ keycloakUrl: z.string(),
52
+ realm: z.string(),
53
+ organizationId: z.string().optional(),
54
+ user: z.object({
55
+ sub: z.string(),
56
+ email: z.string(),
57
+ name: z.string().optional()
58
+ }).optional()
59
+ });
60
+ var TokenResponseSchema = z.object({
61
+ access_token: z.string(),
62
+ refresh_token: z.string(),
63
+ expires_in: z.number()
64
+ });
65
+ var CredentialsStore = class {
66
+ static {
67
+ __name(this, "CredentialsStore");
68
+ }
69
+ configDir;
70
+ credentialsPath;
71
+ constructor(configDir) {
72
+ this.configDir = configDir ?? path.join(os.homedir(), ".spekn");
73
+ this.credentialsPath = path.join(this.configDir, "credentials.json");
74
+ }
75
+ load() {
76
+ try {
77
+ const raw = fs.readFileSync(this.credentialsPath, "utf-8");
78
+ return CliCredentialsSchema.parse(JSON.parse(raw));
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ save(creds) {
84
+ fs.mkdirSync(this.configDir, {
85
+ recursive: true,
86
+ mode: 448
87
+ });
88
+ const json = JSON.stringify(creds, null, 2);
89
+ fs.writeFileSync(this.credentialsPath, json, {
90
+ encoding: "utf-8",
91
+ mode: 384
92
+ });
93
+ }
94
+ clear() {
95
+ try {
96
+ fs.rmSync(this.credentialsPath);
97
+ } catch (err) {
98
+ if (err.code !== "ENOENT") {
99
+ throw err;
100
+ }
101
+ }
102
+ }
103
+ async getValidToken() {
104
+ const creds = this.load();
105
+ if (creds === null) {
106
+ return null;
107
+ }
108
+ const bufferMs = 3e4;
109
+ if (Date.now() + bufferMs < creds.expiresAt) {
110
+ return creds.accessToken;
111
+ }
112
+ try {
113
+ const tokenUrl = `${creds.keycloakUrl}/realms/${creds.realm}/protocol/openid-connect/token`;
114
+ const body = new URLSearchParams({
115
+ grant_type: "refresh_token",
116
+ client_id: "spekn-cli",
117
+ refresh_token: creds.refreshToken
118
+ });
119
+ const res = await fetch(tokenUrl, {
120
+ method: "POST",
121
+ body,
122
+ headers: {
123
+ "Content-Type": "application/x-www-form-urlencoded"
124
+ }
125
+ });
126
+ if (!res.ok) {
127
+ return null;
128
+ }
129
+ const data = TokenResponseSchema.parse(await res.json());
130
+ const updated = {
131
+ ...creds,
132
+ accessToken: data.access_token,
133
+ refreshToken: data.refresh_token,
134
+ expiresAt: Date.now() + data.expires_in * 1e3
135
+ };
136
+ this.save(updated);
137
+ return updated.accessToken;
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+ };
143
+
144
+ // src/auth/jwt.ts
145
+ function decodeJwtPayload(token) {
146
+ try {
147
+ const parts = token.split(".");
148
+ if (parts.length !== 3) {
149
+ return null;
150
+ }
151
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
152
+ const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
153
+ const json = Buffer.from(padded, "base64").toString("utf-8");
154
+ return JSON.parse(json);
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+ __name(decodeJwtPayload, "decodeJwtPayload");
160
+
161
+ // src/services/cli-runner.ts
162
+ import { spawn } from "child_process";
163
+ var CliRunner = class {
164
+ static {
165
+ __name(this, "CliRunner");
166
+ }
167
+ apiUrl;
168
+ credentialsStore = new CredentialsStore();
169
+ constructor(apiUrl) {
170
+ this.apiUrl = apiUrl;
171
+ }
172
+ resolveCliEntry() {
173
+ const cliEntry = process.argv[1];
174
+ return typeof cliEntry === "string" && cliEntry.length > 0 ? cliEntry : null;
175
+ }
176
+ buildCliEnv(options) {
177
+ const env = {
178
+ ...process.env
179
+ };
180
+ delete env.SPEKN_ORGANIZATION_ID;
181
+ if (options?.organizationId) {
182
+ env.SPEKN_ORGANIZATION_ID = options.organizationId;
183
+ }
184
+ if (options?.interactionEnabled) {
185
+ env.SPEKN_INTERACTION_MODE = "json-stdio";
186
+ } else {
187
+ delete env.SPEKN_INTERACTION_MODE;
188
+ }
189
+ return env;
190
+ }
191
+ async respondToInteraction(child, request, onProgress, requestInteraction) {
192
+ const requestPromise = requestInteraction?.(request);
193
+ const value = await Promise.race([
194
+ requestPromise,
195
+ new Promise((resolve) => setTimeout(() => resolve(void 0), 12e4))
196
+ ]);
197
+ if (!child.stdin || child.stdin.destroyed) return;
198
+ if (value === "skip") {
199
+ child.stdin.write(`${JSON.stringify({
200
+ id: request.id,
201
+ skip: true
202
+ })}
203
+ `);
204
+ return;
205
+ }
206
+ const allowed = new Set(request.options.map((option) => option?.value).filter((optionValue) => typeof optionValue === "string"));
207
+ if (typeof value === "string" && allowed.has(value)) {
208
+ child.stdin.write(`${JSON.stringify({
209
+ id: request.id,
210
+ value
211
+ })}
212
+ `);
213
+ return;
214
+ }
215
+ const fallbackValue = request.options[0]?.value;
216
+ if (typeof fallbackValue === "string") {
217
+ onProgress?.(`[interaction] Auto-selecting default: ${fallbackValue}`);
218
+ child.stdin.write(`${JSON.stringify({
219
+ id: request.id,
220
+ value: fallbackValue
221
+ })}
222
+ `);
223
+ return;
224
+ }
225
+ child.stdin.write(`${JSON.stringify({
226
+ id: request.id
227
+ })}
228
+ `);
229
+ }
230
+ async runCliCommand(args, options) {
231
+ const cliEntry = this.resolveCliEntry();
232
+ if (!cliEntry) {
233
+ return {
234
+ success: false,
235
+ exitCode: 1,
236
+ stdoutLines: [],
237
+ stderrLines: [],
238
+ outputLines: [],
239
+ output: "Could not resolve CLI entrypoint.",
240
+ error: "Could not resolve CLI entrypoint."
241
+ };
242
+ }
243
+ const includeAuthToken = options?.includeAuthToken !== false;
244
+ const token = includeAuthToken ? await this.credentialsStore.getValidToken().catch(() => null) : null;
245
+ const env = this.buildCliEnv({
246
+ organizationId: options?.organizationId,
247
+ interactionEnabled: Boolean(options?.requestInteraction)
248
+ });
249
+ if (includeAuthToken && token) {
250
+ env.SPEKN_AUTH_TOKEN = token;
251
+ } else if (!includeAuthToken) {
252
+ delete env.SPEKN_AUTH_TOKEN;
253
+ }
254
+ const finalArgs = [
255
+ cliEntry,
256
+ ...args
257
+ ];
258
+ const stdoutLines = [];
259
+ const stderrLines = [];
260
+ const outputLines = [];
261
+ const maxLines = options?.maxOutputLines ?? 250;
262
+ let stdoutBuffer = "";
263
+ let stderrBuffer = "";
264
+ const pushLine = /* @__PURE__ */ __name((line, stream) => {
265
+ const target = stream === "stdout" ? stdoutLines : stderrLines;
266
+ target.push(line);
267
+ outputLines.push(line);
268
+ if (target.length > maxLines) target.shift();
269
+ if (outputLines.length > maxLines) outputLines.shift();
270
+ options?.onProgress?.(line);
271
+ }, "pushLine");
272
+ const processLine = /* @__PURE__ */ __name((line, stream, child) => {
273
+ const trimmed = line.trim();
274
+ if (!trimmed) return;
275
+ const activityMarker = "[spekn-activity] ";
276
+ const activityIdx = trimmed.indexOf(activityMarker);
277
+ if (activityIdx >= 0) {
278
+ try {
279
+ const parsed = JSON.parse(trimmed.slice(activityIdx + activityMarker.length));
280
+ if (parsed.type === "spekn.activity") {
281
+ options?.onActivity?.(parsed);
282
+ return;
283
+ }
284
+ } catch {
285
+ }
286
+ }
287
+ const marker = "[spekn-interaction] ";
288
+ const markerIndex = trimmed.indexOf(marker);
289
+ if (options?.requestInteraction && markerIndex >= 0) {
290
+ const payloadRaw = trimmed.slice(markerIndex + marker.length);
291
+ let payload = null;
292
+ try {
293
+ payload = JSON.parse(payloadRaw);
294
+ } catch {
295
+ payload = null;
296
+ }
297
+ if (payload?.type === "spekn.interaction.request" && typeof payload.id === "string" && Array.isArray(payload.options)) {
298
+ options.onProgress?.(`[interaction] ${payload.title ?? "Selection required"}`);
299
+ const request = {
300
+ id: payload.id,
301
+ title: payload.title ?? "Selection required",
302
+ message: payload.message ?? "Choose an option",
303
+ options: payload.options,
304
+ allowSkip: payload.allowSkip === true
305
+ };
306
+ void this.respondToInteraction(child, request, options.onProgress, options.requestInteraction).catch(() => {
307
+ if (!child.stdin || child.stdin.destroyed) return;
308
+ child.stdin.write(`${JSON.stringify({
309
+ id: request.id
310
+ })}
311
+ `);
312
+ });
313
+ return;
314
+ }
315
+ }
316
+ pushLine(trimmed, stream);
317
+ }, "processLine");
318
+ try {
319
+ const child = spawn(process.execPath, finalArgs, {
320
+ cwd: options?.cwd ?? process.cwd(),
321
+ env,
322
+ stdio: [
323
+ "pipe",
324
+ "pipe",
325
+ "pipe"
326
+ ]
327
+ });
328
+ const onData = /* @__PURE__ */ __name((stream, data) => {
329
+ const chunk = String(data);
330
+ if (stream === "stdout") {
331
+ stdoutBuffer += chunk;
332
+ } else {
333
+ stderrBuffer += chunk;
334
+ }
335
+ const buffer = stream === "stdout" ? stdoutBuffer : stderrBuffer;
336
+ const lines = buffer.split(/\r?\n|\r/);
337
+ const remainder = lines.pop() ?? "";
338
+ if (stream === "stdout") {
339
+ stdoutBuffer = remainder;
340
+ } else {
341
+ stderrBuffer = remainder;
342
+ }
343
+ for (const line of lines) {
344
+ processLine(line, stream, child);
345
+ }
346
+ }, "onData");
347
+ child.stdout?.on("data", (data) => onData("stdout", data));
348
+ child.stderr?.on("data", (data) => onData("stderr", data));
349
+ if (options?.signal) {
350
+ if (options.signal.aborted) {
351
+ child.kill("SIGTERM");
352
+ } else {
353
+ const onAbort = /* @__PURE__ */ __name(() => {
354
+ child.kill("SIGTERM");
355
+ }, "onAbort");
356
+ options.signal.addEventListener("abort", onAbort, {
357
+ once: true
358
+ });
359
+ child.on("close", () => options.signal?.removeEventListener("abort", onAbort));
360
+ }
361
+ }
362
+ const exitCode = await new Promise((resolve, reject) => {
363
+ child.on("error", reject);
364
+ child.on("close", (code) => resolve(code ?? 1));
365
+ });
366
+ if (stdoutBuffer.trim().length > 0) {
367
+ processLine(stdoutBuffer, "stdout", child);
368
+ }
369
+ if (stderrBuffer.trim().length > 0) {
370
+ processLine(stderrBuffer, "stderr", child);
371
+ }
372
+ return {
373
+ success: exitCode === 0,
374
+ exitCode,
375
+ stdoutLines,
376
+ stderrLines,
377
+ outputLines,
378
+ output: outputLines.join("\n")
379
+ };
380
+ } catch (error) {
381
+ const message = error instanceof Error ? error.message : String(error);
382
+ return {
383
+ success: false,
384
+ exitCode: 1,
385
+ stdoutLines,
386
+ stderrLines,
387
+ outputLines,
388
+ output: message,
389
+ error: message
390
+ };
391
+ }
392
+ }
393
+ async runCliJson(args, cwd, organizationId) {
394
+ const result = await this.runCliCommand(args, {
395
+ cwd,
396
+ organizationId,
397
+ includeAuthToken: true
398
+ });
399
+ if (!result.success && result.output.trim().length === 0) {
400
+ return {
401
+ ok: false,
402
+ error: result.error ?? "CLI command failed."
403
+ };
404
+ }
405
+ const output = result.stdoutLines.join("\n").trim() || result.output.trim();
406
+ const jsonStart = output.indexOf("{");
407
+ if (jsonStart === -1) {
408
+ return {
409
+ ok: false,
410
+ error: output || "Command produced no JSON output."
411
+ };
412
+ }
413
+ try {
414
+ const parsed = JSON.parse(output.slice(jsonStart));
415
+ return {
416
+ ok: true,
417
+ value: parsed
418
+ };
419
+ } catch (error) {
420
+ const message = error instanceof Error ? error.message : String(error);
421
+ return {
422
+ ok: false,
423
+ error: message
424
+ };
425
+ }
426
+ }
427
+ };
428
+
429
+ // src/services/auth-service.ts
430
+ var AuthService = class {
431
+ static {
432
+ __name(this, "AuthService");
433
+ }
434
+ credentialsStore = new CredentialsStore();
435
+ cliRunner;
436
+ constructor(apiUrl) {
437
+ this.cliRunner = new CliRunner(apiUrl);
438
+ }
439
+ async checkAuthentication() {
440
+ try {
441
+ const token = await this.credentialsStore.getValidToken();
442
+ return token || null;
443
+ } catch {
444
+ return null;
445
+ }
446
+ }
447
+ async authenticateViaCli(onProgress) {
448
+ const result = await this.cliRunner.runCliCommand([
449
+ "auth",
450
+ "login"
451
+ ], {
452
+ cwd: process.cwd(),
453
+ includeAuthToken: false,
454
+ onProgress
455
+ });
456
+ return result.success;
457
+ }
458
+ extractUserEmail(token) {
459
+ try {
460
+ const claims = decodeJwtPayload(token);
461
+ return typeof claims?.["email"] === "string" ? claims["email"] : void 0;
462
+ } catch {
463
+ return void 0;
464
+ }
465
+ }
466
+ extractTokenExpiry(token) {
467
+ try {
468
+ const claims = decodeJwtPayload(token);
469
+ if (typeof claims?.["exp"] === "number") {
470
+ return claims["exp"] * 1e3;
471
+ }
472
+ return void 0;
473
+ } catch {
474
+ return void 0;
475
+ }
476
+ }
477
+ extractPermissions(token) {
478
+ const claims = decodeJwtPayload(token);
479
+ return Array.isArray(claims?.permissions) ? claims.permissions.filter((item) => typeof item === "string") : [];
480
+ }
481
+ };
482
+
483
+ // src/shared-enums.ts
484
+ var OrganizationPlan = {
485
+ FREE: "free",
486
+ PRO: "pro",
487
+ TEAM: "team",
488
+ ENTERPRISE: "enterprise"
489
+ };
490
+ var WorkflowPhase = {
491
+ SPECIFY: "specify",
492
+ CLARIFY: "clarify",
493
+ PLAN: "plan",
494
+ IMPLEMENT: "implement",
495
+ VERIFY: "verify",
496
+ COMPLETE: "complete"
497
+ };
498
+
499
+ // src/services/client.ts
500
+ import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
501
+
502
+ // src/utils/trpc-url.ts
503
+ function normalizeTrpcUrl(apiUrl) {
504
+ if (apiUrl.endsWith("/trpc")) {
505
+ return apiUrl;
506
+ }
507
+ if (apiUrl.endsWith("/")) {
508
+ return `${apiUrl}trpc`;
509
+ }
510
+ return `${apiUrl}/trpc`;
511
+ }
512
+ __name(normalizeTrpcUrl, "normalizeTrpcUrl");
513
+
514
+ // src/services/client.ts
515
+ function createApiClient(apiUrl, token, organizationId) {
516
+ return createTRPCProxyClient({
517
+ links: [
518
+ httpBatchLink({
519
+ url: normalizeTrpcUrl(apiUrl),
520
+ headers: {
521
+ authorization: token ? `Bearer ${token}` : "",
522
+ "x-organization-id": organizationId
523
+ }
524
+ })
525
+ ]
526
+ });
527
+ }
528
+ __name(createApiClient, "createApiClient");
529
+
530
+ // src/utils/project-context.ts
531
+ import fs2 from "fs";
532
+ import os2 from "os";
533
+ import path2 from "path";
534
+ var LOCAL_CONTEXT_FILE = ".spekn";
535
+ var GLOBAL_CONTEXT_PATH = path2.join(os2.homedir(), ".spekn", "context.json");
536
+ var GLOBAL_CONFIG_PATH = path2.join(os2.homedir(), ".spekn", "config.json");
537
+ var GLOBAL_ERROR_LOG_PATH = "~/.spekn/error.log";
538
+ var DEFAULT_GLOBAL_CONFIG = {
539
+ logging: {
540
+ enabled: false,
541
+ path: GLOBAL_ERROR_LOG_PATH,
542
+ level: "info"
543
+ }
544
+ };
545
+ var LOG_LEVEL_RANK = {
546
+ debug: 10,
547
+ info: 20,
548
+ warn: 30,
549
+ error: 40
550
+ };
551
+ function loadContextFile(filePath) {
552
+ try {
553
+ const raw = fs2.readFileSync(filePath, "utf-8");
554
+ const parsed = JSON.parse(raw);
555
+ if (!parsed || typeof parsed !== "object") return null;
556
+ return parsed;
557
+ } catch {
558
+ return null;
559
+ }
560
+ }
561
+ __name(loadContextFile, "loadContextFile");
562
+ function loadGlobalContextData() {
563
+ try {
564
+ const raw = fs2.readFileSync(GLOBAL_CONTEXT_PATH, "utf-8");
565
+ const parsed = JSON.parse(raw);
566
+ if (!parsed || typeof parsed !== "object") return null;
567
+ return parsed;
568
+ } catch {
569
+ return null;
570
+ }
571
+ }
572
+ __name(loadGlobalContextData, "loadGlobalContextData");
573
+ function getGlobalProjects(global) {
574
+ if (!global) return [];
575
+ return Array.isArray(global.projects) ? global.projects : [];
576
+ }
577
+ __name(getGlobalProjects, "getGlobalProjects");
578
+ function isRoot(dirPath) {
579
+ return path2.dirname(dirPath) === dirPath;
580
+ }
581
+ __name(isRoot, "isRoot");
582
+ function findNearestLocalContextFile(startDir = process.cwd()) {
583
+ let current = path2.resolve(startDir);
584
+ while (true) {
585
+ const candidate = path2.join(current, LOCAL_CONTEXT_FILE);
586
+ if (fs2.existsSync(candidate) && fs2.statSync(candidate).isFile()) {
587
+ return candidate;
588
+ }
589
+ if (isRoot(current)) return null;
590
+ current = path2.dirname(current);
591
+ }
592
+ }
593
+ __name(findNearestLocalContextFile, "findNearestLocalContextFile");
594
+ function resolveContextWorkspaceRoot(input) {
595
+ const fallback = path2.resolve(input?.fallbackDir ?? process.cwd());
596
+ try {
597
+ const raw = fs2.readFileSync(GLOBAL_CONTEXT_PATH, "utf-8");
598
+ const global = JSON.parse(raw);
599
+ const projects = getGlobalProjects(global);
600
+ const selectedProjectId = input?.projectId ?? global.lastUsedProjectId;
601
+ const selected = projects.find((entry) => entry?.id === selectedProjectId) ?? projects.find((entry) => Array.isArray(entry?.repoPaths) && entry.repoPaths.length > 0);
602
+ const repoPaths = Array.isArray(selected?.repoPaths) ? selected.repoPaths : [];
603
+ const existingPath = repoPaths.find((repoPath) => {
604
+ try {
605
+ return fs2.existsSync(repoPath);
606
+ } catch {
607
+ return false;
608
+ }
609
+ });
610
+ const resolvedPath = existingPath ?? repoPaths[0];
611
+ if (typeof resolvedPath === "string" && resolvedPath.trim().length > 0) {
612
+ return path2.resolve(resolvedPath);
613
+ }
614
+ } catch {
615
+ }
616
+ return fallback;
617
+ }
618
+ __name(resolveContextWorkspaceRoot, "resolveContextWorkspaceRoot");
619
+ function resolveDeclaredContext(input) {
620
+ const localPath = input.repoPath ? path2.join(path2.resolve(input.repoPath), LOCAL_CONTEXT_FILE) : findNearestLocalContextFile();
621
+ const local = localPath ? loadContextFile(localPath) : null;
622
+ const global = loadGlobalContextData();
623
+ const globalProjectId = global?.lastUsedProjectId;
624
+ const globalProjectOrganizationId = (globalProjectId ? getGlobalProjects(global).find((project) => project.id === globalProjectId)?.organizationId : void 0) ?? global?.defaultOrganizationId;
625
+ const projectId = input.explicitProjectId ?? local?.projectId ?? globalProjectId;
626
+ const organizationId = input.explicitOrganizationId ?? local?.organizationId ?? (projectId ? getGlobalProjects(global).find((project) => project.id === projectId)?.organizationId : void 0) ?? globalProjectOrganizationId ?? input.credentialsOrganizationId;
627
+ return {
628
+ projectId,
629
+ organizationId
630
+ };
631
+ }
632
+ __name(resolveDeclaredContext, "resolveDeclaredContext");
633
+ function saveLocalContext(repoPath, context) {
634
+ const filePath = path2.join(path2.resolve(repoPath), LOCAL_CONTEXT_FILE);
635
+ const content = {
636
+ projectId: context.projectId,
637
+ organizationId: context.organizationId,
638
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
639
+ };
640
+ fs2.writeFileSync(filePath, JSON.stringify(content, null, 2) + "\n", "utf-8");
641
+ }
642
+ __name(saveLocalContext, "saveLocalContext");
643
+ function saveGlobalContext(repoPathInput, context) {
644
+ const dirPath = path2.dirname(GLOBAL_CONTEXT_PATH);
645
+ fs2.mkdirSync(dirPath, {
646
+ recursive: true,
647
+ mode: 448
648
+ });
649
+ const existing = loadGlobalContextData();
650
+ const now = (/* @__PURE__ */ new Date()).toISOString();
651
+ const repoPath = path2.resolve(repoPathInput);
652
+ const organizationId = context.organizationId ?? existing?.defaultOrganizationId ?? "";
653
+ const previousProjects = getGlobalProjects(existing);
654
+ const updatedProjects = previousProjects.map((project) => project.id === context.projectId ? {
655
+ ...project,
656
+ organizationId: organizationId || project.organizationId,
657
+ lastUsed: now,
658
+ repoPaths: Array.from(/* @__PURE__ */ new Set([
659
+ ...project.repoPaths ?? [],
660
+ repoPath
661
+ ]))
662
+ } : project);
663
+ if (!updatedProjects.some((project) => project.id === context.projectId) && organizationId) {
664
+ updatedProjects.unshift({
665
+ id: context.projectId,
666
+ organizationId,
667
+ lastUsed: now,
668
+ repoPaths: [
669
+ repoPath
670
+ ]
671
+ });
672
+ }
673
+ const content = {
674
+ defaultOrganizationId: organizationId || existing?.defaultOrganizationId,
675
+ projects: updatedProjects.slice(0, 10),
676
+ lastUsedProjectId: context.projectId,
677
+ preferences: existing?.preferences,
678
+ repoSync: existing?.repoSync,
679
+ updatedAt: now
680
+ };
681
+ fs2.writeFileSync(GLOBAL_CONTEXT_PATH, JSON.stringify(content, null, 2) + "\n", {
682
+ encoding: "utf-8",
683
+ mode: 384
684
+ });
685
+ }
686
+ __name(saveGlobalContext, "saveGlobalContext");
687
+ function saveGlobalContextSelectionOnly(context) {
688
+ const dirPath = path2.dirname(GLOBAL_CONTEXT_PATH);
689
+ fs2.mkdirSync(dirPath, {
690
+ recursive: true,
691
+ mode: 448
692
+ });
693
+ const existing = loadGlobalContextData();
694
+ const now = (/* @__PURE__ */ new Date()).toISOString();
695
+ const organizationId = context.organizationId ?? existing?.defaultOrganizationId ?? "";
696
+ const previousProjects = getGlobalProjects(existing);
697
+ const updatedProjects = previousProjects.map((project) => project.id === context.projectId ? {
698
+ ...project,
699
+ organizationId: organizationId || project.organizationId,
700
+ lastUsed: now
701
+ } : project);
702
+ if (!updatedProjects.some((project) => project.id === context.projectId) && organizationId) {
703
+ updatedProjects.unshift({
704
+ id: context.projectId,
705
+ organizationId,
706
+ lastUsed: now,
707
+ repoPaths: []
708
+ });
709
+ }
710
+ const content = {
711
+ defaultOrganizationId: organizationId || existing?.defaultOrganizationId,
712
+ projects: updatedProjects.slice(0, 10),
713
+ lastUsedProjectId: context.projectId,
714
+ preferences: existing?.preferences,
715
+ repoSync: existing?.repoSync,
716
+ updatedAt: now
717
+ };
718
+ fs2.writeFileSync(GLOBAL_CONTEXT_PATH, JSON.stringify(content, null, 2) + "\n", {
719
+ encoding: "utf-8",
720
+ mode: 384
721
+ });
722
+ }
723
+ __name(saveGlobalContextSelectionOnly, "saveGlobalContextSelectionOnly");
724
+ function ensureGitignoreHasSpekn(repoPath) {
725
+ const gitignorePath = path2.join(path2.resolve(repoPath), ".gitignore");
726
+ const entry = ".spekn";
727
+ if (!fs2.existsSync(gitignorePath)) {
728
+ fs2.writeFileSync(gitignorePath, `${entry}
729
+ `, "utf-8");
730
+ return;
731
+ }
732
+ const content = fs2.readFileSync(gitignorePath, "utf-8");
733
+ const lines = content.split(/\r?\n/);
734
+ if (lines.some((line) => line.trim() === entry)) return;
735
+ const needsNewline = content.length > 0 && !content.endsWith("\n");
736
+ const toAppend = `${needsNewline ? "\n" : ""}${entry}
737
+ `;
738
+ fs2.appendFileSync(gitignorePath, toAppend, "utf-8");
739
+ }
740
+ __name(ensureGitignoreHasSpekn, "ensureGitignoreHasSpekn");
741
+ function hasLocalContext(repoPath) {
742
+ const startDir = repoPath ? path2.resolve(repoPath) : process.cwd();
743
+ return findNearestLocalContextFile(startDir) !== null;
744
+ }
745
+ __name(hasLocalContext, "hasLocalContext");
746
+ function persistProjectContext(repoPath, context) {
747
+ saveLocalContext(repoPath, context);
748
+ saveGlobalContext(repoPath, context);
749
+ ensureGitignoreHasSpekn(repoPath);
750
+ }
751
+ __name(persistProjectContext, "persistProjectContext");
752
+ function persistSelectedProjectContext(context) {
753
+ saveGlobalContextSelectionOnly(context);
754
+ }
755
+ __name(persistSelectedProjectContext, "persistSelectedProjectContext");
756
+ function persistProjectContextWithoutRepoPath(repoPath, context) {
757
+ saveLocalContext(repoPath, context);
758
+ saveGlobalContextSelectionOnly(context);
759
+ ensureGitignoreHasSpekn(repoPath);
760
+ }
761
+ __name(persistProjectContextWithoutRepoPath, "persistProjectContextWithoutRepoPath");
762
+ function loadGlobalContextConfig() {
763
+ try {
764
+ const raw = fs2.readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
765
+ const parsed = JSON.parse(raw);
766
+ const levelCandidate = parsed?.logging?.level;
767
+ const level = levelCandidate === "debug" || levelCandidate === "info" || levelCandidate === "warn" || levelCandidate === "error" ? levelCandidate : DEFAULT_GLOBAL_CONFIG.logging.level;
768
+ return {
769
+ logging: {
770
+ enabled: typeof parsed?.logging?.enabled === "boolean" ? parsed.logging.enabled : DEFAULT_GLOBAL_CONFIG.logging.enabled,
771
+ path: typeof parsed?.logging?.path === "string" && parsed.logging.path.trim().length > 0 ? parsed.logging.path : DEFAULT_GLOBAL_CONFIG.logging.path,
772
+ level
773
+ }
774
+ };
775
+ } catch {
776
+ return DEFAULT_GLOBAL_CONFIG;
777
+ }
778
+ }
779
+ __name(loadGlobalContextConfig, "loadGlobalContextConfig");
780
+ function saveGlobalContextConfig(config) {
781
+ const dirPath = path2.dirname(GLOBAL_CONFIG_PATH);
782
+ fs2.mkdirSync(dirPath, {
783
+ recursive: true,
784
+ mode: 448
785
+ });
786
+ fs2.writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {
787
+ encoding: "utf-8",
788
+ mode: 384
789
+ });
790
+ }
791
+ __name(saveGlobalContextConfig, "saveGlobalContextConfig");
792
+ function ensureGlobalContextConfig() {
793
+ const config = loadGlobalContextConfig();
794
+ if (!fs2.existsSync(GLOBAL_CONFIG_PATH)) {
795
+ saveGlobalContextConfig(config);
796
+ }
797
+ return config;
798
+ }
799
+ __name(ensureGlobalContextConfig, "ensureGlobalContextConfig");
800
+ function expandHomePath(filePath) {
801
+ if (filePath === "~") return os2.homedir();
802
+ if (filePath.startsWith("~/")) {
803
+ return path2.join(os2.homedir(), filePath.slice(2));
804
+ }
805
+ return filePath;
806
+ }
807
+ __name(expandHomePath, "expandHomePath");
808
+ function appendGlobalStructuredLog(input) {
809
+ try {
810
+ const config = ensureGlobalContextConfig();
811
+ if (!config.logging.enabled) return;
812
+ if (LOG_LEVEL_RANK[input.level] < LOG_LEVEL_RANK[config.logging.level]) return;
813
+ const logPath = path2.resolve(expandHomePath(config.logging.path));
814
+ const dirPath = path2.dirname(logPath);
815
+ fs2.mkdirSync(dirPath, {
816
+ recursive: true,
817
+ mode: 448
818
+ });
819
+ const payload = {
820
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
821
+ source: input.source,
822
+ level: input.level,
823
+ message: input.message,
824
+ details: input.details ?? {}
825
+ };
826
+ fs2.appendFileSync(logPath, `${JSON.stringify(payload)}
827
+ `, {
828
+ encoding: "utf-8",
829
+ mode: 384
830
+ });
831
+ } catch {
832
+ }
833
+ }
834
+ __name(appendGlobalStructuredLog, "appendGlobalStructuredLog");
835
+ function appendGlobalErrorLog(input) {
836
+ appendGlobalStructuredLog({
837
+ source: input.source,
838
+ level: "error",
839
+ message: input.message,
840
+ details: input.details
841
+ });
842
+ }
843
+ __name(appendGlobalErrorLog, "appendGlobalErrorLog");
844
+
845
+ // src/services/bootstrap-service.ts
846
+ function normalizePlan(raw) {
847
+ if (raw === OrganizationPlan.PRO) return OrganizationPlan.PRO;
848
+ if (raw === OrganizationPlan.TEAM) return OrganizationPlan.TEAM;
849
+ if (raw === OrganizationPlan.ENTERPRISE) return OrganizationPlan.ENTERPRISE;
850
+ return OrganizationPlan.FREE;
851
+ }
852
+ __name(normalizePlan, "normalizePlan");
853
+ function normalizeRole(raw) {
854
+ if (raw === "owner" || raw === "admin" || raw === "member" || raw === "viewer") {
855
+ return raw;
856
+ }
857
+ return "member";
858
+ }
859
+ __name(normalizeRole, "normalizeRole");
860
+ var BootstrapService = class {
861
+ static {
862
+ __name(this, "BootstrapService");
863
+ }
864
+ apiUrl;
865
+ credentialsStore = new CredentialsStore();
866
+ authService;
867
+ constructor(apiUrl) {
868
+ this.apiUrl = apiUrl;
869
+ this.authService = new AuthService(apiUrl);
870
+ }
871
+ async bootstrap(projectIdArg) {
872
+ const token = await this.credentialsStore.getValidToken();
873
+ if (!token) {
874
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
875
+ }
876
+ const permissions = this.authService.extractPermissions(token);
877
+ const stored = this.credentialsStore.load();
878
+ const declared = resolveDeclaredContext({
879
+ explicitProjectId: projectIdArg,
880
+ repoPath: process.cwd(),
881
+ credentialsOrganizationId: stored?.organizationId,
882
+ envOrganizationId: process.env.SPEKN_ORGANIZATION_ID
883
+ });
884
+ if (!declared.projectId) {
885
+ throw new Error("PROJECT_CONTEXT_REQUIRED");
886
+ }
887
+ const fallbackOrg = declared.organizationId ?? "";
888
+ const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
889
+ const orgs = await bootstrapClient.organization.list.query();
890
+ if (orgs.length === 0) {
891
+ throw new Error("No organization membership found for this account.");
892
+ }
893
+ const org = orgs.find((candidate) => candidate.id === fallbackOrg) ?? orgs[0];
894
+ const organizationId = org.id;
895
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
896
+ const projects = await client2.project.list.query({
897
+ limit: 20,
898
+ offset: 0
899
+ });
900
+ if (projects.length === 0) {
901
+ throw new Error("ONBOARDING_REQUIRED");
902
+ }
903
+ const project = projects.find((candidate) => candidate.id === declared.projectId);
904
+ if (!project) {
905
+ throw new Error("ONBOARDING_REQUIRED");
906
+ }
907
+ const repoPath = resolveContextWorkspaceRoot({
908
+ projectId: project.id,
909
+ fallbackDir: process.cwd()
910
+ });
911
+ return {
912
+ boot: {
913
+ apiUrl: this.apiUrl,
914
+ organizationId,
915
+ organizationName: org.name,
916
+ role: normalizeRole(org.role),
917
+ plan: normalizePlan(org.plan),
918
+ projectId: project.id,
919
+ projectName: project.name,
920
+ repoPath,
921
+ permissions
922
+ },
923
+ client: client2
924
+ };
925
+ }
926
+ hasDeclaredProjectContext(projectIdArg) {
927
+ const stored = this.credentialsStore.load();
928
+ const declared = resolveDeclaredContext({
929
+ explicitProjectId: projectIdArg,
930
+ repoPath: process.cwd(),
931
+ credentialsOrganizationId: stored?.organizationId,
932
+ envOrganizationId: process.env.SPEKN_ORGANIZATION_ID
933
+ });
934
+ return Boolean(declared.projectId);
935
+ }
936
+ async loadWorkflowSummary(client2, projectId) {
937
+ const states = await client2.workflowState.listByProject.query({
938
+ projectId
939
+ });
940
+ const first = Array.isArray(states) && states.length > 0 ? states[0] : null;
941
+ const currentPhase = first?.currentPhase ?? null;
942
+ const blockedCount = Array.isArray(states) ? states.filter((state) => state.specificationLockStatus === "locked").length : 0;
943
+ return {
944
+ currentPhase,
945
+ blockedCount,
946
+ hasVerificationEvidence: Boolean(first?.hasVerificationEvidence),
947
+ hasPlanningArtifacts: Boolean(first?.hasPlanningArtifacts)
948
+ };
949
+ }
950
+ hasLocalProjectContext(repoPath) {
951
+ return hasLocalContext(repoPath);
952
+ }
953
+ persistContext(organizationId, projectId) {
954
+ persistSelectedProjectContext({
955
+ organizationId,
956
+ projectId
957
+ });
958
+ }
959
+ };
960
+
961
+ // src/services/bridge-service.ts
962
+ import fs3 from "fs";
963
+ import os3 from "os";
964
+ import path3 from "path";
965
+ import { spawn as spawn2 } from "child_process";
966
+ var DEFAULT_BRIDGE_CONFIG = {
967
+ port: 19550,
968
+ pairing: null
969
+ };
970
+ function loadLocalBridgeConfig() {
971
+ const configPath = path3.join(os3.homedir(), ".spekn", "bridge", "config.json");
972
+ try {
973
+ const raw = fs3.readFileSync(configPath, "utf-8");
974
+ const parsed = JSON.parse(raw);
975
+ return {
976
+ port: typeof parsed.port === "number" ? parsed.port : DEFAULT_BRIDGE_CONFIG.port,
977
+ pairing: parsed.pairing ?? DEFAULT_BRIDGE_CONFIG.pairing
978
+ };
979
+ } catch {
980
+ return DEFAULT_BRIDGE_CONFIG;
981
+ }
982
+ }
983
+ __name(loadLocalBridgeConfig, "loadLocalBridgeConfig");
984
+ async function loadWebMcpChannels(port) {
985
+ try {
986
+ const res = await fetch(`http://127.0.0.1:${port}/webmcp/channels`);
987
+ if (!res.ok) return [];
988
+ const data = await res.json();
989
+ return data.channels ?? [];
990
+ } catch {
991
+ return [];
992
+ }
993
+ }
994
+ __name(loadWebMcpChannels, "loadWebMcpChannels");
995
+ var BridgeService = class {
996
+ static {
997
+ __name(this, "BridgeService");
998
+ }
999
+ cliRunner;
1000
+ constructor(apiUrl) {
1001
+ this.cliRunner = new CliRunner(apiUrl);
1002
+ }
1003
+ async loadBridgeSummary(client2) {
1004
+ const [flag, devices, metrics] = await Promise.all([
1005
+ client2.bridge.getFeatureFlag.query().catch(() => ({
1006
+ enabled: false
1007
+ })),
1008
+ client2.bridge.listDevices.query().catch(() => []),
1009
+ client2.bridge.getMetrics.query().catch(() => ({
1010
+ connectedDevices: 0,
1011
+ authFailures: 0
1012
+ }))
1013
+ ]);
1014
+ return {
1015
+ featureEnabled: Boolean(flag.enabled),
1016
+ devices: Array.isArray(devices) ? devices.map((device) => ({
1017
+ id: device.id,
1018
+ name: device.name,
1019
+ status: device.status,
1020
+ isDefault: Boolean(device.isDefault),
1021
+ lastSeenAt: device.lastSeenAt
1022
+ })) : [],
1023
+ connectedDevices: Number(metrics.connectedDevices ?? 0),
1024
+ authFailures: Number(metrics.authFailures ?? 0)
1025
+ };
1026
+ }
1027
+ async loadLocalBridgeSummary() {
1028
+ const config = loadLocalBridgeConfig();
1029
+ let running = false;
1030
+ let uptimeSec;
1031
+ try {
1032
+ const response = await fetch(`http://127.0.0.1:${config.port}/health`);
1033
+ if (response.ok) {
1034
+ const payload = await response.json();
1035
+ running = true;
1036
+ uptimeSec = Number(payload.uptime ?? 0);
1037
+ }
1038
+ } catch {
1039
+ running = false;
1040
+ }
1041
+ return {
1042
+ paired: config.pairing !== null,
1043
+ deviceId: config.pairing?.deviceId,
1044
+ deviceName: config.pairing?.deviceName,
1045
+ port: config.port,
1046
+ running,
1047
+ uptimeSec
1048
+ };
1049
+ }
1050
+ startLocalBridgeDetached() {
1051
+ const cliEntry = this.cliRunner.resolveCliEntry();
1052
+ if (!cliEntry) return;
1053
+ const args = [
1054
+ cliEntry,
1055
+ "bridge",
1056
+ "start"
1057
+ ];
1058
+ const child = spawn2(process.execPath, args, {
1059
+ detached: true,
1060
+ stdio: "ignore"
1061
+ });
1062
+ child.unref();
1063
+ }
1064
+ async stopLocalBridge(configPort) {
1065
+ const port = configPort ?? loadLocalBridgeConfig().port;
1066
+ try {
1067
+ await fetch(`http://127.0.0.1:${port}/shutdown`, {
1068
+ method: "POST"
1069
+ });
1070
+ } catch {
1071
+ }
1072
+ }
1073
+ async loadBridgeLogs(port, since) {
1074
+ const p = port ?? loadLocalBridgeConfig().port;
1075
+ try {
1076
+ const url = since ? `http://127.0.0.1:${p}/logs?since=${since}` : `http://127.0.0.1:${p}/logs`;
1077
+ const res = await fetch(url);
1078
+ if (!res.ok) return [];
1079
+ const data = await res.json();
1080
+ return data.logs;
1081
+ } catch {
1082
+ return [];
1083
+ }
1084
+ }
1085
+ };
1086
+
1087
+ // src/services/decision-service.ts
1088
+ var DecisionService = class {
1089
+ static {
1090
+ __name(this, "DecisionService");
1091
+ }
1092
+ async loadDecisions(client2, projectId) {
1093
+ const result = await client2.decision.getAll.query({
1094
+ projectId,
1095
+ limit: 50,
1096
+ offset: 0
1097
+ });
1098
+ const decisions = Array.isArray(result?.decisions) ? result.decisions : [];
1099
+ return decisions.map((decision) => ({
1100
+ id: decision.id,
1101
+ title: decision.title,
1102
+ status: decision.status,
1103
+ decisionType: decision.decisionType,
1104
+ specAnchor: decision.specAnchor,
1105
+ createdAt: decision.createdAt
1106
+ }));
1107
+ }
1108
+ async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1109
+ await client2.decision.update.mutate({
1110
+ projectId,
1111
+ id: decisionId,
1112
+ data: {
1113
+ status,
1114
+ rationale: reason || existingRationale
1115
+ }
1116
+ });
1117
+ }
1118
+ async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1119
+ const deleteMutation = client2?.decision?.delete?.mutate;
1120
+ if (typeof deleteMutation !== "function") {
1121
+ throw new Error("Decision delete route is unavailable.");
1122
+ }
1123
+ await deleteMutation({
1124
+ projectId,
1125
+ id: decisionId,
1126
+ mode
1127
+ });
1128
+ }
1129
+ };
1130
+
1131
+ // src/services/export-service.ts
1132
+ var ExportService = class {
1133
+ static {
1134
+ __name(this, "ExportService");
1135
+ }
1136
+ apiUrl;
1137
+ cliRunner;
1138
+ constructor(apiUrl) {
1139
+ this.apiUrl = apiUrl;
1140
+ this.cliRunner = new CliRunner(apiUrl);
1141
+ }
1142
+ async previewExport(client2, projectId, format) {
1143
+ const result = await client2.export.preview.query({
1144
+ projectId,
1145
+ formatId: format
1146
+ });
1147
+ return {
1148
+ content: String(result.content ?? ""),
1149
+ anchorCount: Number(result.anchorCount ?? 0),
1150
+ specGeneration: typeof result.specGeneration === "number" ? result.specGeneration : void 0,
1151
+ warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
1152
+ };
1153
+ }
1154
+ async generateExport(client2, projectId, format) {
1155
+ const result = await client2.export.generate.mutate({
1156
+ projectId,
1157
+ formatId: format
1158
+ });
1159
+ return {
1160
+ content: String(result.content ?? ""),
1161
+ anchorCount: Number(result.anchorCount ?? 0),
1162
+ specGeneration: typeof result.specGeneration === "number" ? result.specGeneration : void 0,
1163
+ warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
1164
+ };
1165
+ }
1166
+ async discoverExportCapabilities(projectId, organizationId) {
1167
+ const fallback = {
1168
+ plan: "free",
1169
+ modes: [
1170
+ "global"
1171
+ ],
1172
+ formats: [
1173
+ {
1174
+ id: "agents-md"
1175
+ },
1176
+ {
1177
+ id: "claude-md"
1178
+ },
1179
+ {
1180
+ id: "cursorrules"
1181
+ },
1182
+ {
1183
+ id: "gemini-md"
1184
+ }
1185
+ ]
1186
+ };
1187
+ const cliResult = await this.cliRunner.runCliJson([
1188
+ "export",
1189
+ "discover",
1190
+ "--project",
1191
+ projectId,
1192
+ "--api-url",
1193
+ this.apiUrl,
1194
+ "--json"
1195
+ ], void 0, organizationId);
1196
+ if (!cliResult.ok) {
1197
+ return fallback;
1198
+ }
1199
+ const result = cliResult.value;
1200
+ const modes = Array.isArray(result?.modes) ? result.modes.filter((mode) => mode === "global" || mode === "scoped") : fallback.modes;
1201
+ const formats = Array.isArray(result?.formats) ? result.formats.map((format) => {
1202
+ if (format?.id !== "agents-md" && format?.id !== "claude-md" && format?.id !== "cursorrules" && format?.id !== "gemini-md") {
1203
+ return null;
1204
+ }
1205
+ const formatModes = Array.isArray(format?.modes) ? format.modes.filter((mode) => mode === "global" || mode === "scoped") : void 0;
1206
+ return {
1207
+ id: format.id,
1208
+ name: typeof format?.name === "string" ? format.name : void 0,
1209
+ filename: typeof format?.filename === "string" ? format.filename : void 0,
1210
+ modes: formatModes
1211
+ };
1212
+ }).filter((format) => format !== null) : fallback.formats;
1213
+ return {
1214
+ plan: result?.plan === "pro" || result?.plan === "team" || result?.plan === "enterprise" ? result.plan : "free",
1215
+ modes: modes.length > 0 ? modes : fallback.modes,
1216
+ formats: formats.length > 0 ? formats : fallback.formats
1217
+ };
1218
+ }
1219
+ async exportStatus(projectId, format, options) {
1220
+ const args = [
1221
+ "export",
1222
+ "status",
1223
+ "--project",
1224
+ projectId,
1225
+ "--format",
1226
+ format,
1227
+ "--api-url",
1228
+ this.apiUrl,
1229
+ "--json"
1230
+ ];
1231
+ if (options?.mode) args.push("--mode", options.mode);
1232
+ if (options?.scopePath) args.push("--scope", options.scopePath);
1233
+ const cliResult = await this.cliRunner.runCliJson(args, void 0, options?.organizationId);
1234
+ if (!cliResult.ok) {
1235
+ return {
1236
+ overall: "missing",
1237
+ targets: []
1238
+ };
1239
+ }
1240
+ const result = cliResult.value;
1241
+ const overall = result?.overall === "diverged" || result?.overall === "outdated" || result?.overall === "up-to-date" ? result.overall : "missing";
1242
+ const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1243
+ const status = target?.status === "diverged" || target?.status === "outdated" || target?.status === "up-to-date" ? target.status : "missing";
1244
+ const kind = target?.kind === "canonical" ? "canonical" : "entrypoint";
1245
+ if (typeof target?.path !== "string") return null;
1246
+ return {
1247
+ path: target.path,
1248
+ kind,
1249
+ status
1250
+ };
1251
+ }).filter((target) => target !== null) : [];
1252
+ return {
1253
+ overall,
1254
+ targets
1255
+ };
1256
+ }
1257
+ async deliverExport(projectId, format, delivery, options) {
1258
+ const args = [
1259
+ "export",
1260
+ "--project",
1261
+ projectId,
1262
+ "--format",
1263
+ format,
1264
+ "--delivery",
1265
+ delivery,
1266
+ "--api-url",
1267
+ this.apiUrl,
1268
+ "--json"
1269
+ ];
1270
+ if (options?.mode) args.push("--mode", options.mode);
1271
+ if (options?.scopePath) args.push("--scope", options.scopePath);
1272
+ const exportCwd = delivery === "download" ? resolveContextWorkspaceRoot({
1273
+ projectId,
1274
+ fallbackDir: process.cwd()
1275
+ }) : process.cwd();
1276
+ const cliResult = await this.cliRunner.runCliJson(args, exportCwd, options?.organizationId);
1277
+ if (!cliResult.ok) {
1278
+ throw new Error(cliResult.error);
1279
+ }
1280
+ const result = cliResult.value;
1281
+ if (delivery === "commit") {
1282
+ return {
1283
+ message: typeof result?.commitSha === "string" ? `Committed to ${result.branch ?? "branch"}: ${result.commitSha}` : "Export commit completed."
1284
+ };
1285
+ }
1286
+ if (delivery === "pr") {
1287
+ return {
1288
+ message: typeof result?.prUrl === "string" ? `PR #${result.prNumber ?? "?"}: ${result.prUrl}` : "Export PR created."
1289
+ };
1290
+ }
1291
+ if (delivery === "download") {
1292
+ const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1293
+ if (typeof target?.path !== "string") return null;
1294
+ return {
1295
+ path: target.path,
1296
+ kind: target?.kind === "canonical" ? "canonical" : "entrypoint",
1297
+ status: "up-to-date"
1298
+ };
1299
+ }).filter((target) => target !== null) : [];
1300
+ const count = targets.length;
1301
+ return {
1302
+ message: `Wrote ${count} export file(s) to ${exportCwd}.`,
1303
+ localStatus: {
1304
+ overall: "up-to-date",
1305
+ targets
1306
+ }
1307
+ };
1308
+ }
1309
+ return {
1310
+ message: "Export copy payload generated."
1311
+ };
1312
+ }
1313
+ };
1314
+
1315
+ // src/services/organization-service.ts
1316
+ var OrganizationService = class {
1317
+ static {
1318
+ __name(this, "OrganizationService");
1319
+ }
1320
+ apiUrl;
1321
+ credentialsStore = new CredentialsStore();
1322
+ constructor(apiUrl) {
1323
+ this.apiUrl = apiUrl;
1324
+ }
1325
+ async listOrganizations() {
1326
+ const token = await this.credentialsStore.getValidToken();
1327
+ if (!token) {
1328
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
1329
+ }
1330
+ const stored = this.credentialsStore.load();
1331
+ const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1332
+ const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
1333
+ const orgs = await bootstrapClient.organization.list.query();
1334
+ return orgs.map((org) => ({
1335
+ id: org.id,
1336
+ name: org.name,
1337
+ plan: org.plan,
1338
+ role: org.role
1339
+ }));
1340
+ }
1341
+ async createOrganization(input) {
1342
+ const token = await this.credentialsStore.getValidToken();
1343
+ if (!token) {
1344
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
1345
+ }
1346
+ const stored = this.credentialsStore.load();
1347
+ const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1348
+ const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
1349
+ const createdOrg = await bootstrapClient.organization.create.mutate(input);
1350
+ return {
1351
+ id: createdOrg.id,
1352
+ name: createdOrg.name,
1353
+ plan: createdOrg.plan,
1354
+ role: "owner"
1355
+ };
1356
+ }
1357
+ async listProjects(organizationId) {
1358
+ const token = await this.credentialsStore.getValidToken();
1359
+ if (!token) {
1360
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
1361
+ }
1362
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
1363
+ const projects = await client2.project.list.query({
1364
+ limit: 100,
1365
+ offset: 0
1366
+ });
1367
+ return projects.map((project) => ({
1368
+ id: project.id,
1369
+ name: project.name
1370
+ }));
1371
+ }
1372
+ async createProject(organizationId, name) {
1373
+ try {
1374
+ const token = await this.credentialsStore.getValidToken();
1375
+ if (!token) {
1376
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
1377
+ }
1378
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
1379
+ const created = await client2.project.create.mutate({
1380
+ name: name.trim()
1381
+ });
1382
+ return {
1383
+ id: created.id,
1384
+ name: String(created.name ?? name.trim())
1385
+ };
1386
+ } catch (error) {
1387
+ const message = error instanceof Error ? error.message : String(error);
1388
+ appendGlobalErrorLog({
1389
+ source: "wizard.createProject",
1390
+ message,
1391
+ details: {
1392
+ apiUrl: this.apiUrl,
1393
+ organizationId,
1394
+ projectName: name.trim(),
1395
+ cwd: process.cwd()
1396
+ }
1397
+ });
1398
+ throw error;
1399
+ }
1400
+ }
1401
+ canCreateProject(org) {
1402
+ const role = String(org?.role ?? "").toLowerCase();
1403
+ return role === "owner" || role === "admin";
1404
+ }
1405
+ };
1406
+
1407
+ // src/services/repo-service.ts
1408
+ import { execFileSync } from "child_process";
1409
+ import path4 from "path";
1410
+ var RepoService = class {
1411
+ static {
1412
+ __name(this, "RepoService");
1413
+ }
1414
+ apiUrl;
1415
+ credentialsStore = new CredentialsStore();
1416
+ cliRunner;
1417
+ constructor(apiUrl) {
1418
+ this.apiUrl = apiUrl;
1419
+ this.cliRunner = new CliRunner(apiUrl);
1420
+ }
1421
+ attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1422
+ const repoPath = process.cwd();
1423
+ let args = [];
1424
+ let lastOutputLines = [];
1425
+ try {
1426
+ const remoteUrl = this.execGit(repoPath, [
1427
+ "remote",
1428
+ "get-url",
1429
+ "origin"
1430
+ ]);
1431
+ const token = await this.credentialsStore.getValidToken();
1432
+ if (!token) {
1433
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
1434
+ }
1435
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
1436
+ const repos = await client2.gitRepository.list.query({
1437
+ projectId,
1438
+ limit: 100,
1439
+ offset: 0
1440
+ });
1441
+ const isAlreadyAttached = repos.some((repo) => repo.repositoryUrl === remoteUrl);
1442
+ const cliEntry = this.cliRunner.resolveCliEntry();
1443
+ if (!cliEntry) {
1444
+ throw new Error("Could not resolve CLI entrypoint for repo register.");
1445
+ }
1446
+ const runAnalyze = !isAlreadyAttached;
1447
+ args = isAlreadyAttached ? [
1448
+ cliEntry,
1449
+ "repo",
1450
+ "sync",
1451
+ "--project-id",
1452
+ projectId,
1453
+ "--path",
1454
+ repoPath,
1455
+ "--api-url",
1456
+ this.apiUrl,
1457
+ "--no-analyze"
1458
+ ] : [
1459
+ cliEntry,
1460
+ "repo",
1461
+ "register",
1462
+ "--project-id",
1463
+ projectId,
1464
+ "--path",
1465
+ repoPath,
1466
+ "--api-url",
1467
+ this.apiUrl,
1468
+ "--analyze"
1469
+ ];
1470
+ if (isAlreadyAttached) {
1471
+ onProgress?.("Repository already attached to this project. Syncing metadata only (no analysis)...");
1472
+ } else {
1473
+ onProgress?.("Repository not attached yet. Registering and running analysis...");
1474
+ }
1475
+ const runResult = await this.cliRunner.runCliCommand(args.slice(1), {
1476
+ cwd: repoPath,
1477
+ organizationId,
1478
+ onProgress,
1479
+ requestInteraction,
1480
+ onActivity
1481
+ });
1482
+ lastOutputLines = runResult.outputLines;
1483
+ const exitCode = runResult.exitCode;
1484
+ if (exitCode !== 0) {
1485
+ appendGlobalErrorLog({
1486
+ source: "wizard.registerCurrentRepository",
1487
+ message: `Repository registration/analysis failed (exit ${exitCode}).`,
1488
+ details: {
1489
+ apiUrl: this.apiUrl,
1490
+ organizationId,
1491
+ projectId,
1492
+ repoPath,
1493
+ command: process.execPath,
1494
+ args,
1495
+ lastOutputLines: lastOutputLines.slice(-80)
1496
+ }
1497
+ });
1498
+ throw new Error(`Repository registration/analysis failed (exit ${exitCode}).`);
1499
+ }
1500
+ if (runAnalyze) {
1501
+ persistProjectContext(repoPath, {
1502
+ projectId,
1503
+ organizationId
1504
+ });
1505
+ } else {
1506
+ persistProjectContextWithoutRepoPath(repoPath, {
1507
+ projectId,
1508
+ organizationId
1509
+ });
1510
+ }
1511
+ return {
1512
+ success: true,
1513
+ analyzed: runAnalyze
1514
+ };
1515
+ } catch (error) {
1516
+ const message = error instanceof Error ? error.message : String(error);
1517
+ appendGlobalErrorLog({
1518
+ source: "wizard.registerCurrentRepository",
1519
+ message,
1520
+ details: {
1521
+ apiUrl: this.apiUrl,
1522
+ organizationId,
1523
+ projectId,
1524
+ repoPath,
1525
+ command: process.execPath,
1526
+ args,
1527
+ lastOutputLines: lastOutputLines.slice(-80)
1528
+ }
1529
+ });
1530
+ throw error;
1531
+ }
1532
+ }, "attachOrSyncCurrentRepository");
1533
+ async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1534
+ const repoPath = path4.resolve(repoPathInput || process.cwd());
1535
+ if (!this.cliRunner.resolveCliEntry()) {
1536
+ return {
1537
+ success: false,
1538
+ output: "Could not resolve CLI entrypoint.",
1539
+ exitCode: 1
1540
+ };
1541
+ }
1542
+ const token = await this.credentialsStore.getValidToken();
1543
+ if (!token) {
1544
+ return {
1545
+ success: false,
1546
+ output: "No valid credentials. Run `spekn auth login` first.",
1547
+ exitCode: 1
1548
+ };
1549
+ }
1550
+ const args = [
1551
+ "repo",
1552
+ "sync",
1553
+ "--project-id",
1554
+ projectId,
1555
+ "--path",
1556
+ repoPath,
1557
+ "--api-url",
1558
+ this.apiUrl
1559
+ ];
1560
+ if (options?.analyze === false) {
1561
+ args.push("--no-analyze");
1562
+ }
1563
+ if (options?.importToProject) {
1564
+ args.push("--import-to-project");
1565
+ }
1566
+ if (typeof options?.maxFiles === "number" && Number.isFinite(options.maxFiles)) {
1567
+ args.push("--max-files", String(Math.max(1, Math.floor(options.maxFiles))));
1568
+ }
1569
+ if (options?.analysisEngine) {
1570
+ args.push("--analysis-engine", options.analysisEngine);
1571
+ }
1572
+ if (options?.agent && options.agent.trim().length > 0) {
1573
+ args.push("--agent", options.agent.trim());
1574
+ }
1575
+ try {
1576
+ const runResult = await this.cliRunner.runCliCommand(args, {
1577
+ cwd: repoPath,
1578
+ organizationId,
1579
+ onProgress: options?.onProgress,
1580
+ requestInteraction: options?.requestInteraction,
1581
+ onActivity: options?.onActivity,
1582
+ signal: options?.signal
1583
+ });
1584
+ return {
1585
+ success: runResult.success,
1586
+ output: runResult.output,
1587
+ exitCode: runResult.exitCode
1588
+ };
1589
+ } catch (error) {
1590
+ const message = error instanceof Error ? error.message : String(error);
1591
+ return {
1592
+ success: false,
1593
+ output: message,
1594
+ exitCode: 1
1595
+ };
1596
+ }
1597
+ }
1598
+ async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1599
+ const result = await this.cliRunner.runCliCommand([
1600
+ "repo",
1601
+ "detach",
1602
+ "--path",
1603
+ repoPath
1604
+ ], {
1605
+ cwd: repoPath,
1606
+ includeAuthToken: false
1607
+ });
1608
+ return {
1609
+ success: result.success,
1610
+ output: result.output || result.error || "Unknown detach error"
1611
+ };
1612
+ }
1613
+ execGit(repoPath, args) {
1614
+ try {
1615
+ return execFileSync("git", [
1616
+ "-C",
1617
+ repoPath,
1618
+ ...args
1619
+ ], {
1620
+ encoding: "utf-8",
1621
+ stdio: [
1622
+ "pipe",
1623
+ "pipe",
1624
+ "pipe"
1625
+ ]
1626
+ }).trim();
1627
+ } catch {
1628
+ throw new Error("Could not read git metadata. Run TUI from a git repository with an 'origin' remote.");
1629
+ }
1630
+ }
1631
+ };
1632
+
1633
+ // src/services/spec-service.ts
1634
+ var SpecService = class {
1635
+ static {
1636
+ __name(this, "SpecService");
1637
+ }
1638
+ async loadSpecs(client2, projectId) {
1639
+ const specs = await client2.specification.list.query({
1640
+ projectId,
1641
+ limit: 50,
1642
+ offset: 0
1643
+ });
1644
+ return (Array.isArray(specs) ? specs : []).map((spec) => {
1645
+ const frontmatter = spec.frontmatter ?? {};
1646
+ const hints = frontmatter.hints ?? {};
1647
+ const aiContext = frontmatter.aiContext ?? {};
1648
+ const acp = frontmatter.acp ?? {};
1649
+ const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags.filter((tag) => typeof tag === "string") : [];
1650
+ const aiFocusAreas = Array.isArray(aiContext.focusAreas) ? aiContext.focusAreas.filter((area) => typeof area === "string") : [];
1651
+ const acpAllowedAgents = Array.isArray(acp.allowedAgents) ? acp.allowedAgents.filter((agent) => typeof agent === "string") : [];
1652
+ const countArray = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.length : 0, "countArray");
1653
+ return {
1654
+ id: spec.id,
1655
+ specRef: typeof frontmatter.specRef === "string" ? frontmatter.specRef : typeof spec.specRef === "string" ? spec.specRef : void 0,
1656
+ frontmatter,
1657
+ title: spec.title,
1658
+ status: spec.status,
1659
+ generationNumber: typeof spec.generationNumber === "number" ? spec.generationNumber : 1,
1660
+ generationStatus: typeof spec.generationStatus === "string" ? spec.generationStatus : spec.status,
1661
+ updatedAt: spec.updatedAt,
1662
+ type: typeof frontmatter.type === "string" ? frontmatter.type : void 0,
1663
+ content: typeof spec.content === "string" ? spec.content : void 0,
1664
+ tags: tags.length > 0 ? tags : void 0,
1665
+ author: typeof frontmatter.author === "string" ? frontmatter.author : void 0,
1666
+ hintCounts: {
1667
+ constraints: countArray(hints.constraints),
1668
+ requirements: countArray(hints.requirements),
1669
+ technical: countArray(hints.technical),
1670
+ guidance: countArray(hints.guidance)
1671
+ },
1672
+ relationCounts: {
1673
+ dependsOn: countArray(frontmatter.dependsOn),
1674
+ conflictsWith: countArray(frontmatter.conflictsWith),
1675
+ compatibleWith: countArray(frontmatter.compatibleWith)
1676
+ },
1677
+ acpPolicyMode: typeof acp.policyMode === "string" ? acp.policyMode : void 0,
1678
+ acpAllowedAgents: acpAllowedAgents.length > 0 ? acpAllowedAgents : void 0,
1679
+ aiTokenBudget: typeof aiContext.tokenBudget === "number" ? aiContext.tokenBudget : void 0,
1680
+ aiFocusAreas: aiFocusAreas.length > 0 ? aiFocusAreas : void 0
1681
+ };
1682
+ });
1683
+ }
1684
+ async updateSpecificationContent(client2, projectId, specificationId, content) {
1685
+ await client2.specification.update.mutate({
1686
+ projectId,
1687
+ id: specificationId,
1688
+ data: {
1689
+ content,
1690
+ changeType: "patch",
1691
+ changeDescription: "Edited from TUI editor"
1692
+ }
1693
+ });
1694
+ }
1695
+ async updateSpecificationStatus(client2, projectId, specificationId, status) {
1696
+ await client2.specification.update.mutate({
1697
+ projectId,
1698
+ id: specificationId,
1699
+ data: {
1700
+ status,
1701
+ changeType: "metadata",
1702
+ changeDescription: `Status changed to ${status} from TUI`
1703
+ }
1704
+ });
1705
+ }
1706
+ async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1707
+ const deleteMutation = client2?.specification?.delete?.mutate;
1708
+ if (typeof deleteMutation !== "function") {
1709
+ throw new Error("Specification delete route is unavailable.");
1710
+ }
1711
+ await deleteMutation({
1712
+ projectId,
1713
+ id: specificationId,
1714
+ mode
1715
+ });
1716
+ }
1717
+ async refineSpecificationWithAi(client2, input) {
1718
+ const refineMutation = client2?.specification?.refine?.mutate;
1719
+ if (typeof refineMutation !== "function") {
1720
+ throw new Error("Specification refine route is unavailable.");
1721
+ }
1722
+ const result = await refineMutation({
1723
+ projectId: input.projectId,
1724
+ specificationContent: input.specContent,
1725
+ userMessage: input.userMessage,
1726
+ agentType: input.agentType
1727
+ });
1728
+ if (typeof result?.content !== "string") {
1729
+ throw new Error("AI refinement response was missing content.");
1730
+ }
1731
+ return result.content;
1732
+ }
1733
+ async createSpecification(client2, projectId, title, content, status = "draft") {
1734
+ const createMutation = client2?.specification?.create?.mutate;
1735
+ if (typeof createMutation !== "function") {
1736
+ throw new Error("Specification create route is unavailable.");
1737
+ }
1738
+ const result = await createMutation({
1739
+ projectId,
1740
+ title,
1741
+ content,
1742
+ status
1743
+ });
1744
+ return {
1745
+ id: result.id
1746
+ };
1747
+ }
1748
+ async listGenerations(client2, projectId, specId) {
1749
+ const query = client2?.specification?.listGenerations?.query;
1750
+ if (typeof query !== "function") {
1751
+ throw new Error("Specification listGenerations route is unavailable.");
1752
+ }
1753
+ const result = await query({
1754
+ projectId,
1755
+ specificationId: specId
1756
+ });
1757
+ return Array.isArray(result) ? result : [];
1758
+ }
1759
+ async startNewGeneration(client2, projectId, specId, fromGenerationId) {
1760
+ const mutation = client2?.specification?.startNewGeneration?.mutate;
1761
+ if (typeof mutation !== "function") {
1762
+ throw new Error("Specification startNewGeneration route is unavailable.");
1763
+ }
1764
+ return await mutation({
1765
+ projectId,
1766
+ specificationId: specId,
1767
+ fromGenerationId
1768
+ });
1769
+ }
1770
+ async lockGeneration(client2, projectId, specId) {
1771
+ const mutation = client2?.specification?.lock?.mutate;
1772
+ if (typeof mutation !== "function") {
1773
+ throw new Error("Specification lock route is unavailable.");
1774
+ }
1775
+ await mutation({
1776
+ projectId,
1777
+ specificationId: specId
1778
+ });
1779
+ }
1780
+ async unlockGeneration(client2, projectId, specId) {
1781
+ const mutation = client2?.specification?.unlock?.mutate;
1782
+ if (typeof mutation !== "function") {
1783
+ throw new Error("Specification unlock route is unavailable.");
1784
+ }
1785
+ await mutation({
1786
+ projectId,
1787
+ specificationId: specId
1788
+ });
1789
+ }
1790
+ async deleteGeneration(client2, projectId, generationId) {
1791
+ const mutation = client2?.specification?.deleteGeneration?.mutate;
1792
+ if (typeof mutation !== "function") {
1793
+ throw new Error("Specification deleteGeneration route is unavailable.");
1794
+ }
1795
+ await mutation({
1796
+ projectId,
1797
+ generationId
1798
+ });
1799
+ }
1800
+ };
1801
+
1802
+ // src/services/context-service.ts
1803
+ var TuiContextService = class {
1804
+ static {
1805
+ __name(this, "TuiContextService");
1806
+ }
1807
+ apiUrl;
1808
+ authService;
1809
+ bootstrapService;
1810
+ bridgeService;
1811
+ decisionService;
1812
+ exportService;
1813
+ organizationService;
1814
+ repoService;
1815
+ specService;
1816
+ constructor(apiUrl) {
1817
+ this.apiUrl = apiUrl;
1818
+ this.authService = new AuthService(apiUrl);
1819
+ this.bootstrapService = new BootstrapService(apiUrl);
1820
+ this.bridgeService = new BridgeService(apiUrl);
1821
+ this.decisionService = new DecisionService();
1822
+ this.exportService = new ExportService(apiUrl);
1823
+ this.organizationService = new OrganizationService(apiUrl);
1824
+ this.repoService = new RepoService(apiUrl);
1825
+ this.specService = new SpecService();
1826
+ }
1827
+ // ── Bootstrap ──────────────────────────────────────────────────────
1828
+ async bootstrap(projectIdArg) {
1829
+ return this.bootstrapService.bootstrap(projectIdArg);
1830
+ }
1831
+ hasDeclaredProjectContext(projectIdArg) {
1832
+ return this.bootstrapService.hasDeclaredProjectContext(projectIdArg);
1833
+ }
1834
+ hasLocalProjectContext(repoPath) {
1835
+ return this.bootstrapService.hasLocalProjectContext(repoPath);
1836
+ }
1837
+ async loadWorkflowSummary(client2, projectId) {
1838
+ return this.bootstrapService.loadWorkflowSummary(client2, projectId);
1839
+ }
1840
+ persistContext(organizationId, projectId) {
1841
+ this.bootstrapService.persistContext(organizationId, projectId);
1842
+ }
1843
+ // ── Auth ───────────────────────────────────────────────────────────
1844
+ async checkAuthentication() {
1845
+ return this.authService.checkAuthentication();
1846
+ }
1847
+ async authenticateViaCli(onProgress) {
1848
+ return this.authService.authenticateViaCli(onProgress);
1849
+ }
1850
+ extractUserEmail(token) {
1851
+ return this.authService.extractUserEmail(token);
1852
+ }
1853
+ extractTokenExpiry(token) {
1854
+ return this.authService.extractTokenExpiry(token);
1855
+ }
1856
+ // ── Organization & Project ─────────────────────────────────────────
1857
+ async listOrganizations() {
1858
+ return this.organizationService.listOrganizations();
1859
+ }
1860
+ async createOrganization(input) {
1861
+ return this.organizationService.createOrganization(input);
1862
+ }
1863
+ async listProjects(organizationId) {
1864
+ return this.organizationService.listProjects(organizationId);
1865
+ }
1866
+ async createProject(organizationId, name) {
1867
+ return this.organizationService.createProject(organizationId, name);
1868
+ }
1869
+ canCreateProject(org) {
1870
+ return this.organizationService.canCreateProject(org);
1871
+ }
1872
+ // ── Specs ──────────────────────────────────────────────────────────
1873
+ async loadSpecs(client2, projectId) {
1874
+ return this.specService.loadSpecs(client2, projectId);
1875
+ }
1876
+ async updateSpecificationContent(client2, projectId, specificationId, content) {
1877
+ return this.specService.updateSpecificationContent(client2, projectId, specificationId, content);
1878
+ }
1879
+ async updateSpecificationStatus(client2, projectId, specificationId, status) {
1880
+ return this.specService.updateSpecificationStatus(client2, projectId, specificationId, status);
1881
+ }
1882
+ async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1883
+ return this.specService.deleteSpecification(client2, projectId, specificationId, mode);
1884
+ }
1885
+ async refineSpecificationWithAi(client2, input) {
1886
+ return this.specService.refineSpecificationWithAi(client2, input);
1887
+ }
1888
+ async createSpecification(client2, projectId, title, content, status = "draft") {
1889
+ return this.specService.createSpecification(client2, projectId, title, content, status);
1890
+ }
1891
+ async listGenerations(client2, projectId, specId) {
1892
+ return this.specService.listGenerations(client2, projectId, specId);
1893
+ }
1894
+ async startNewGeneration(client2, projectId, specId, fromGenerationId) {
1895
+ return this.specService.startNewGeneration(client2, projectId, specId, fromGenerationId);
1896
+ }
1897
+ async lockGeneration(client2, projectId, specId) {
1898
+ return this.specService.lockGeneration(client2, projectId, specId);
1899
+ }
1900
+ async unlockGeneration(client2, projectId, specId) {
1901
+ return this.specService.unlockGeneration(client2, projectId, specId);
1902
+ }
1903
+ async deleteGeneration(client2, projectId, generationId) {
1904
+ return this.specService.deleteGeneration(client2, projectId, generationId);
1905
+ }
1906
+ // ── Decisions ──────────────────────────────────────────────────────
1907
+ async loadDecisions(client2, projectId) {
1908
+ return this.decisionService.loadDecisions(client2, projectId);
1909
+ }
1910
+ async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1911
+ return this.decisionService.resolveDecision(client2, projectId, decisionId, status, reason, existingRationale);
1912
+ }
1913
+ async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1914
+ return this.decisionService.deleteDecision(client2, projectId, decisionId, mode);
1915
+ }
1916
+ // ── Export ─────────────────────────────────────────────────────────
1917
+ async previewExport(client2, projectId, format) {
1918
+ return this.exportService.previewExport(client2, projectId, format);
1919
+ }
1920
+ async generateExport(client2, projectId, format) {
1921
+ return this.exportService.generateExport(client2, projectId, format);
1922
+ }
1923
+ async discoverExportCapabilities(projectId, organizationId) {
1924
+ return this.exportService.discoverExportCapabilities(projectId, organizationId);
1925
+ }
1926
+ async exportStatus(projectId, format, options) {
1927
+ return this.exportService.exportStatus(projectId, format, options);
1928
+ }
1929
+ async deliverExport(projectId, format, delivery, options) {
1930
+ return this.exportService.deliverExport(projectId, format, delivery, options);
1931
+ }
1932
+ // ── Bridge ─────────────────────────────────────────────────────────
1933
+ async loadBridgeSummary(client2) {
1934
+ return this.bridgeService.loadBridgeSummary(client2);
1935
+ }
1936
+ async loadLocalBridgeSummary() {
1937
+ return this.bridgeService.loadLocalBridgeSummary();
1938
+ }
1939
+ startLocalBridgeDetached() {
1940
+ this.bridgeService.startLocalBridgeDetached();
1941
+ }
1942
+ async stopLocalBridge(configPort) {
1943
+ return this.bridgeService.stopLocalBridge(configPort);
1944
+ }
1945
+ async loadBridgeLogs(port, since) {
1946
+ return this.bridgeService.loadBridgeLogs(port, since);
1947
+ }
1948
+ // ── Repository ─────────────────────────────────────────────────────
1949
+ attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
1950
+ return this.repoService.attachOrSyncCurrentRepository(organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity);
1951
+ }, "attachOrSyncCurrentRepository");
1952
+ async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1953
+ return this.repoService.syncRepositoryViaCli(organizationId, projectId, repoPathInput, options);
1954
+ }
1955
+ async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1956
+ return this.repoService.detachContextViaCli(_projectId, repoPath);
1957
+ }
1958
+ };
1959
+
1960
+ // src/store/service-bridge.ts
1961
+ var service = null;
1962
+ var client = null;
1963
+ function initServiceBridge(apiUrl) {
1964
+ if (!service) {
1965
+ service = new TuiContextService(apiUrl);
1966
+ }
1967
+ return service;
1968
+ }
1969
+ __name(initServiceBridge, "initServiceBridge");
1970
+ function getService() {
1971
+ if (!service) {
1972
+ throw new Error("Service bridge not initialized. Call initServiceBridge() first.");
1973
+ }
1974
+ return service;
1975
+ }
1976
+ __name(getService, "getService");
1977
+ function getClient() {
1978
+ return client;
1979
+ }
1980
+ __name(getClient, "getClient");
1981
+ function setClient(c) {
1982
+ client = c;
1983
+ }
1984
+ __name(setClient, "setClient");
1985
+
1986
+ export {
1987
+ __name,
1988
+ __require,
1989
+ __esm,
1990
+ __commonJS,
1991
+ __export,
1992
+ __toESM,
1993
+ __toCommonJS,
1994
+ OrganizationPlan,
1995
+ WorkflowPhase,
1996
+ persistProjectContext,
1997
+ appendGlobalStructuredLog,
1998
+ loadWebMcpChannels,
1999
+ initServiceBridge,
2000
+ getService,
2001
+ getClient,
2002
+ setClient
2003
+ };