@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,3159 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/store/use-session-store.ts
5
+ import { create as create6 } from "zustand";
6
+ import { subscribeWithSelector as subscribeWithSelector6 } from "zustand/middleware";
7
+
8
+ // src/utils/project-context.ts
9
+ import fs from "fs";
10
+ import os from "os";
11
+ import path from "path";
12
+ var LOCAL_CONTEXT_FILE = ".spekn";
13
+ var GLOBAL_CONTEXT_PATH = path.join(os.homedir(), ".spekn", "context.json");
14
+ var GLOBAL_CONFIG_PATH = path.join(os.homedir(), ".spekn", "config.json");
15
+ var GLOBAL_ERROR_LOG_PATH = "~/.spekn/error.log";
16
+ var DEFAULT_GLOBAL_CONFIG = {
17
+ logging: {
18
+ enabled: false,
19
+ path: GLOBAL_ERROR_LOG_PATH,
20
+ level: "info"
21
+ }
22
+ };
23
+ var LOG_LEVEL_RANK = {
24
+ debug: 10,
25
+ info: 20,
26
+ warn: 30,
27
+ error: 40
28
+ };
29
+ function loadContextFile(filePath) {
30
+ try {
31
+ const raw = fs.readFileSync(filePath, "utf-8");
32
+ const parsed = JSON.parse(raw);
33
+ if (!parsed || typeof parsed !== "object") return null;
34
+ return parsed;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+ __name(loadContextFile, "loadContextFile");
40
+ function loadGlobalContextData() {
41
+ try {
42
+ const raw = fs.readFileSync(GLOBAL_CONTEXT_PATH, "utf-8");
43
+ const parsed = JSON.parse(raw);
44
+ if (!parsed || typeof parsed !== "object") return null;
45
+ return parsed;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ __name(loadGlobalContextData, "loadGlobalContextData");
51
+ function getGlobalProjects(global) {
52
+ if (!global) return [];
53
+ return Array.isArray(global.projects) ? global.projects : [];
54
+ }
55
+ __name(getGlobalProjects, "getGlobalProjects");
56
+ function isRoot(dirPath) {
57
+ return path.dirname(dirPath) === dirPath;
58
+ }
59
+ __name(isRoot, "isRoot");
60
+ function findNearestLocalContextFile(startDir = process.cwd()) {
61
+ let current = path.resolve(startDir);
62
+ while (true) {
63
+ const candidate = path.join(current, LOCAL_CONTEXT_FILE);
64
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
65
+ return candidate;
66
+ }
67
+ if (isRoot(current)) return null;
68
+ current = path.dirname(current);
69
+ }
70
+ }
71
+ __name(findNearestLocalContextFile, "findNearestLocalContextFile");
72
+ function resolveContextWorkspaceRoot(input) {
73
+ const fallback = path.resolve(input?.fallbackDir ?? process.cwd());
74
+ try {
75
+ const raw = fs.readFileSync(GLOBAL_CONTEXT_PATH, "utf-8");
76
+ const global = JSON.parse(raw);
77
+ const projects = getGlobalProjects(global);
78
+ const selectedProjectId = input?.projectId ?? global.lastUsedProjectId;
79
+ const selected = projects.find((entry) => entry?.id === selectedProjectId) ?? projects.find((entry) => Array.isArray(entry?.repoPaths) && entry.repoPaths.length > 0);
80
+ const repoPaths = Array.isArray(selected?.repoPaths) ? selected.repoPaths : [];
81
+ const existingPath = repoPaths.find((repoPath) => {
82
+ try {
83
+ return fs.existsSync(repoPath);
84
+ } catch {
85
+ return false;
86
+ }
87
+ });
88
+ const resolvedPath = existingPath ?? repoPaths[0];
89
+ if (typeof resolvedPath === "string" && resolvedPath.trim().length > 0) {
90
+ return path.resolve(resolvedPath);
91
+ }
92
+ } catch {
93
+ }
94
+ return fallback;
95
+ }
96
+ __name(resolveContextWorkspaceRoot, "resolveContextWorkspaceRoot");
97
+ function resolveDeclaredContext(input) {
98
+ const localPath = input.repoPath ? path.join(path.resolve(input.repoPath), LOCAL_CONTEXT_FILE) : findNearestLocalContextFile();
99
+ const local = localPath ? loadContextFile(localPath) : null;
100
+ const global = loadGlobalContextData();
101
+ const globalProjectId = global?.lastUsedProjectId;
102
+ const globalProjectOrganizationId = (globalProjectId ? getGlobalProjects(global).find((project) => project.id === globalProjectId)?.organizationId : void 0) ?? global?.defaultOrganizationId;
103
+ const projectId = input.explicitProjectId ?? local?.projectId ?? globalProjectId;
104
+ const organizationId = input.explicitOrganizationId ?? local?.organizationId ?? (projectId ? getGlobalProjects(global).find((project) => project.id === projectId)?.organizationId : void 0) ?? globalProjectOrganizationId ?? input.credentialsOrganizationId;
105
+ return {
106
+ projectId,
107
+ organizationId
108
+ };
109
+ }
110
+ __name(resolveDeclaredContext, "resolveDeclaredContext");
111
+ function saveLocalContext(repoPath, context) {
112
+ const filePath = path.join(path.resolve(repoPath), LOCAL_CONTEXT_FILE);
113
+ const content = {
114
+ projectId: context.projectId,
115
+ organizationId: context.organizationId,
116
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
117
+ };
118
+ fs.writeFileSync(filePath, JSON.stringify(content, null, 2) + "\n", "utf-8");
119
+ }
120
+ __name(saveLocalContext, "saveLocalContext");
121
+ function saveGlobalContext(repoPathInput, context) {
122
+ const dirPath = path.dirname(GLOBAL_CONTEXT_PATH);
123
+ fs.mkdirSync(dirPath, {
124
+ recursive: true,
125
+ mode: 448
126
+ });
127
+ const existing = loadGlobalContextData();
128
+ const now = (/* @__PURE__ */ new Date()).toISOString();
129
+ const repoPath = path.resolve(repoPathInput);
130
+ const organizationId = context.organizationId ?? existing?.defaultOrganizationId ?? "";
131
+ const previousProjects = getGlobalProjects(existing);
132
+ const updatedProjects = previousProjects.map((project) => project.id === context.projectId ? {
133
+ ...project,
134
+ organizationId: organizationId || project.organizationId,
135
+ lastUsed: now,
136
+ repoPaths: Array.from(/* @__PURE__ */ new Set([
137
+ ...project.repoPaths ?? [],
138
+ repoPath
139
+ ]))
140
+ } : project);
141
+ if (!updatedProjects.some((project) => project.id === context.projectId) && organizationId) {
142
+ updatedProjects.unshift({
143
+ id: context.projectId,
144
+ organizationId,
145
+ lastUsed: now,
146
+ repoPaths: [
147
+ repoPath
148
+ ]
149
+ });
150
+ }
151
+ const content = {
152
+ defaultOrganizationId: organizationId || existing?.defaultOrganizationId,
153
+ projects: updatedProjects.slice(0, 10),
154
+ lastUsedProjectId: context.projectId,
155
+ preferences: existing?.preferences,
156
+ repoSync: existing?.repoSync,
157
+ updatedAt: now
158
+ };
159
+ fs.writeFileSync(GLOBAL_CONTEXT_PATH, JSON.stringify(content, null, 2) + "\n", {
160
+ encoding: "utf-8",
161
+ mode: 384
162
+ });
163
+ }
164
+ __name(saveGlobalContext, "saveGlobalContext");
165
+ function saveGlobalContextSelectionOnly(context) {
166
+ const dirPath = path.dirname(GLOBAL_CONTEXT_PATH);
167
+ fs.mkdirSync(dirPath, {
168
+ recursive: true,
169
+ mode: 448
170
+ });
171
+ const existing = loadGlobalContextData();
172
+ const now = (/* @__PURE__ */ new Date()).toISOString();
173
+ const organizationId = context.organizationId ?? existing?.defaultOrganizationId ?? "";
174
+ const previousProjects = getGlobalProjects(existing);
175
+ const updatedProjects = previousProjects.map((project) => project.id === context.projectId ? {
176
+ ...project,
177
+ organizationId: organizationId || project.organizationId,
178
+ lastUsed: now
179
+ } : project);
180
+ if (!updatedProjects.some((project) => project.id === context.projectId) && organizationId) {
181
+ updatedProjects.unshift({
182
+ id: context.projectId,
183
+ organizationId,
184
+ lastUsed: now,
185
+ repoPaths: []
186
+ });
187
+ }
188
+ const content = {
189
+ defaultOrganizationId: organizationId || existing?.defaultOrganizationId,
190
+ projects: updatedProjects.slice(0, 10),
191
+ lastUsedProjectId: context.projectId,
192
+ preferences: existing?.preferences,
193
+ repoSync: existing?.repoSync,
194
+ updatedAt: now
195
+ };
196
+ fs.writeFileSync(GLOBAL_CONTEXT_PATH, JSON.stringify(content, null, 2) + "\n", {
197
+ encoding: "utf-8",
198
+ mode: 384
199
+ });
200
+ }
201
+ __name(saveGlobalContextSelectionOnly, "saveGlobalContextSelectionOnly");
202
+ function ensureGitignoreHasSpekn(repoPath) {
203
+ const gitignorePath = path.join(path.resolve(repoPath), ".gitignore");
204
+ const entry = ".spekn";
205
+ if (!fs.existsSync(gitignorePath)) {
206
+ fs.writeFileSync(gitignorePath, `${entry}
207
+ `, "utf-8");
208
+ return;
209
+ }
210
+ const content = fs.readFileSync(gitignorePath, "utf-8");
211
+ const lines = content.split(/\r?\n/);
212
+ if (lines.some((line) => line.trim() === entry)) return;
213
+ const needsNewline = content.length > 0 && !content.endsWith("\n");
214
+ const toAppend = `${needsNewline ? "\n" : ""}${entry}
215
+ `;
216
+ fs.appendFileSync(gitignorePath, toAppend, "utf-8");
217
+ }
218
+ __name(ensureGitignoreHasSpekn, "ensureGitignoreHasSpekn");
219
+ function persistProjectContext(repoPath, context) {
220
+ saveLocalContext(repoPath, context);
221
+ saveGlobalContext(repoPath, context);
222
+ ensureGitignoreHasSpekn(repoPath);
223
+ }
224
+ __name(persistProjectContext, "persistProjectContext");
225
+ function persistSelectedProjectContext(context) {
226
+ saveGlobalContextSelectionOnly(context);
227
+ }
228
+ __name(persistSelectedProjectContext, "persistSelectedProjectContext");
229
+ function persistProjectContextWithoutRepoPath(repoPath, context) {
230
+ saveLocalContext(repoPath, context);
231
+ saveGlobalContextSelectionOnly(context);
232
+ ensureGitignoreHasSpekn(repoPath);
233
+ }
234
+ __name(persistProjectContextWithoutRepoPath, "persistProjectContextWithoutRepoPath");
235
+ function loadGlobalContextConfig() {
236
+ try {
237
+ const raw = fs.readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
238
+ const parsed = JSON.parse(raw);
239
+ const levelCandidate = parsed?.logging?.level;
240
+ const level = levelCandidate === "debug" || levelCandidate === "info" || levelCandidate === "warn" || levelCandidate === "error" ? levelCandidate : DEFAULT_GLOBAL_CONFIG.logging.level;
241
+ return {
242
+ logging: {
243
+ enabled: typeof parsed?.logging?.enabled === "boolean" ? parsed.logging.enabled : DEFAULT_GLOBAL_CONFIG.logging.enabled,
244
+ path: typeof parsed?.logging?.path === "string" && parsed.logging.path.trim().length > 0 ? parsed.logging.path : DEFAULT_GLOBAL_CONFIG.logging.path,
245
+ level
246
+ }
247
+ };
248
+ } catch {
249
+ return DEFAULT_GLOBAL_CONFIG;
250
+ }
251
+ }
252
+ __name(loadGlobalContextConfig, "loadGlobalContextConfig");
253
+ function saveGlobalContextConfig(config) {
254
+ const dirPath = path.dirname(GLOBAL_CONFIG_PATH);
255
+ fs.mkdirSync(dirPath, {
256
+ recursive: true,
257
+ mode: 448
258
+ });
259
+ fs.writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {
260
+ encoding: "utf-8",
261
+ mode: 384
262
+ });
263
+ }
264
+ __name(saveGlobalContextConfig, "saveGlobalContextConfig");
265
+ function ensureGlobalContextConfig() {
266
+ const config = loadGlobalContextConfig();
267
+ if (!fs.existsSync(GLOBAL_CONFIG_PATH)) {
268
+ saveGlobalContextConfig(config);
269
+ }
270
+ return config;
271
+ }
272
+ __name(ensureGlobalContextConfig, "ensureGlobalContextConfig");
273
+ function expandHomePath(filePath) {
274
+ if (filePath === "~") return os.homedir();
275
+ if (filePath.startsWith("~/")) {
276
+ return path.join(os.homedir(), filePath.slice(2));
277
+ }
278
+ return filePath;
279
+ }
280
+ __name(expandHomePath, "expandHomePath");
281
+ function appendGlobalStructuredLog(input) {
282
+ try {
283
+ const config = ensureGlobalContextConfig();
284
+ if (!config.logging.enabled) return;
285
+ if (LOG_LEVEL_RANK[input.level] < LOG_LEVEL_RANK[config.logging.level]) return;
286
+ const logPath = path.resolve(expandHomePath(config.logging.path));
287
+ const dirPath = path.dirname(logPath);
288
+ fs.mkdirSync(dirPath, {
289
+ recursive: true,
290
+ mode: 448
291
+ });
292
+ const payload = {
293
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
294
+ source: input.source,
295
+ level: input.level,
296
+ message: input.message,
297
+ details: input.details ?? {}
298
+ };
299
+ fs.appendFileSync(logPath, `${JSON.stringify(payload)}
300
+ `, {
301
+ encoding: "utf-8",
302
+ mode: 384
303
+ });
304
+ } catch {
305
+ }
306
+ }
307
+ __name(appendGlobalStructuredLog, "appendGlobalStructuredLog");
308
+ function appendGlobalErrorLog(input) {
309
+ appendGlobalStructuredLog({
310
+ source: input.source,
311
+ level: "error",
312
+ message: input.message,
313
+ details: input.details
314
+ });
315
+ }
316
+ __name(appendGlobalErrorLog, "appendGlobalErrorLog");
317
+
318
+ // src/services/context-service.ts
319
+ import { execFileSync, spawn } from "child_process";
320
+ import fs3 from "fs";
321
+ import os3 from "os";
322
+ import path3 from "path";
323
+
324
+ // src/auth/credentials-store.ts
325
+ import * as fs2 from "fs";
326
+ import * as os2 from "os";
327
+ import * as path2 from "path";
328
+ import { z } from "zod";
329
+ var CliCredentialsSchema = z.object({
330
+ accessToken: z.string(),
331
+ refreshToken: z.string(),
332
+ expiresAt: z.number(),
333
+ keycloakUrl: z.string(),
334
+ realm: z.string(),
335
+ organizationId: z.string().optional(),
336
+ user: z.object({
337
+ sub: z.string(),
338
+ email: z.string(),
339
+ name: z.string().optional()
340
+ }).optional()
341
+ });
342
+ var TokenResponseSchema = z.object({
343
+ access_token: z.string(),
344
+ refresh_token: z.string(),
345
+ expires_in: z.number()
346
+ });
347
+ var CredentialsStore = class {
348
+ static {
349
+ __name(this, "CredentialsStore");
350
+ }
351
+ configDir;
352
+ credentialsPath;
353
+ constructor(configDir) {
354
+ this.configDir = configDir ?? path2.join(os2.homedir(), ".spekn");
355
+ this.credentialsPath = path2.join(this.configDir, "credentials.json");
356
+ }
357
+ load() {
358
+ try {
359
+ const raw = fs2.readFileSync(this.credentialsPath, "utf-8");
360
+ return CliCredentialsSchema.parse(JSON.parse(raw));
361
+ } catch {
362
+ return null;
363
+ }
364
+ }
365
+ save(creds) {
366
+ fs2.mkdirSync(this.configDir, {
367
+ recursive: true,
368
+ mode: 448
369
+ });
370
+ const json = JSON.stringify(creds, null, 2);
371
+ fs2.writeFileSync(this.credentialsPath, json, {
372
+ encoding: "utf-8",
373
+ mode: 384
374
+ });
375
+ }
376
+ clear() {
377
+ try {
378
+ fs2.rmSync(this.credentialsPath);
379
+ } catch (err) {
380
+ if (err.code !== "ENOENT") {
381
+ throw err;
382
+ }
383
+ }
384
+ }
385
+ async getValidToken() {
386
+ const creds = this.load();
387
+ if (creds === null) {
388
+ return null;
389
+ }
390
+ const bufferMs = 3e4;
391
+ if (Date.now() + bufferMs < creds.expiresAt) {
392
+ return creds.accessToken;
393
+ }
394
+ try {
395
+ const tokenUrl = `${creds.keycloakUrl}/realms/${creds.realm}/protocol/openid-connect/token`;
396
+ const body = new URLSearchParams({
397
+ grant_type: "refresh_token",
398
+ client_id: "spekn-cli",
399
+ refresh_token: creds.refreshToken
400
+ });
401
+ const res = await fetch(tokenUrl, {
402
+ method: "POST",
403
+ body,
404
+ headers: {
405
+ "Content-Type": "application/x-www-form-urlencoded"
406
+ }
407
+ });
408
+ if (!res.ok) {
409
+ return null;
410
+ }
411
+ const data = TokenResponseSchema.parse(await res.json());
412
+ const updated = {
413
+ ...creds,
414
+ accessToken: data.access_token,
415
+ refreshToken: data.refresh_token,
416
+ expiresAt: Date.now() + data.expires_in * 1e3
417
+ };
418
+ this.save(updated);
419
+ return updated.accessToken;
420
+ } catch {
421
+ return null;
422
+ }
423
+ }
424
+ };
425
+
426
+ // src/auth/jwt.ts
427
+ function decodeJwtPayload(token) {
428
+ try {
429
+ const parts = token.split(".");
430
+ if (parts.length !== 3) {
431
+ return null;
432
+ }
433
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
434
+ const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
435
+ const json = Buffer.from(padded, "base64").toString("utf-8");
436
+ return JSON.parse(json);
437
+ } catch {
438
+ return null;
439
+ }
440
+ }
441
+ __name(decodeJwtPayload, "decodeJwtPayload");
442
+
443
+ // src/shared-enums.ts
444
+ var OrganizationPlan = {
445
+ FREE: "free",
446
+ PRO: "pro",
447
+ TEAM: "team",
448
+ ENTERPRISE: "enterprise"
449
+ };
450
+ var WorkflowPhase = {
451
+ SPECIFY: "specify",
452
+ CLARIFY: "clarify",
453
+ PLAN: "plan",
454
+ IMPLEMENT: "implement",
455
+ VERIFY: "verify",
456
+ COMPLETE: "complete"
457
+ };
458
+
459
+ // src/services/client.ts
460
+ import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
461
+
462
+ // src/utils/trpc-url.ts
463
+ function normalizeTrpcUrl(apiUrl) {
464
+ if (apiUrl.endsWith("/trpc")) {
465
+ return apiUrl;
466
+ }
467
+ if (apiUrl.endsWith("/")) {
468
+ return `${apiUrl}trpc`;
469
+ }
470
+ return `${apiUrl}/trpc`;
471
+ }
472
+ __name(normalizeTrpcUrl, "normalizeTrpcUrl");
473
+
474
+ // src/services/client.ts
475
+ function createApiClient(apiUrl, token, organizationId) {
476
+ return createTRPCProxyClient({
477
+ links: [
478
+ httpBatchLink({
479
+ url: normalizeTrpcUrl(apiUrl),
480
+ headers: {
481
+ authorization: token ? `Bearer ${token}` : "",
482
+ "x-organization-id": organizationId
483
+ }
484
+ })
485
+ ]
486
+ });
487
+ }
488
+ __name(createApiClient, "createApiClient");
489
+
490
+ // src/services/context-service.ts
491
+ var DEFAULT_BRIDGE_CONFIG = {
492
+ port: 19550,
493
+ pairing: null
494
+ };
495
+ function loadLocalBridgeConfig() {
496
+ const configPath = path3.join(os3.homedir(), ".spekn", "bridge", "config.json");
497
+ try {
498
+ const raw = fs3.readFileSync(configPath, "utf-8");
499
+ const parsed = JSON.parse(raw);
500
+ return {
501
+ port: typeof parsed.port === "number" ? parsed.port : DEFAULT_BRIDGE_CONFIG.port,
502
+ pairing: parsed.pairing ?? DEFAULT_BRIDGE_CONFIG.pairing
503
+ };
504
+ } catch {
505
+ return DEFAULT_BRIDGE_CONFIG;
506
+ }
507
+ }
508
+ __name(loadLocalBridgeConfig, "loadLocalBridgeConfig");
509
+ function normalizePlan(raw) {
510
+ if (raw === OrganizationPlan.PRO) return OrganizationPlan.PRO;
511
+ if (raw === OrganizationPlan.TEAM) return OrganizationPlan.TEAM;
512
+ if (raw === OrganizationPlan.ENTERPRISE) return OrganizationPlan.ENTERPRISE;
513
+ return OrganizationPlan.FREE;
514
+ }
515
+ __name(normalizePlan, "normalizePlan");
516
+ function normalizeRole(raw) {
517
+ if (raw === "owner" || raw === "admin" || raw === "member" || raw === "viewer") {
518
+ return raw;
519
+ }
520
+ return "member";
521
+ }
522
+ __name(normalizeRole, "normalizeRole");
523
+ var TuiContextService = class {
524
+ static {
525
+ __name(this, "TuiContextService");
526
+ }
527
+ apiUrl;
528
+ credentialsStore = new CredentialsStore();
529
+ constructor(apiUrl) {
530
+ this.apiUrl = apiUrl;
531
+ }
532
+ async bootstrap(projectIdArg) {
533
+ const token = await this.credentialsStore.getValidToken();
534
+ if (!token) {
535
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
536
+ }
537
+ const permissions = this.extractPermissions(token);
538
+ const stored = this.credentialsStore.load();
539
+ const declared = resolveDeclaredContext({
540
+ explicitProjectId: projectIdArg,
541
+ repoPath: process.cwd(),
542
+ credentialsOrganizationId: stored?.organizationId,
543
+ envOrganizationId: process.env.SPEKN_ORGANIZATION_ID
544
+ });
545
+ if (!declared.projectId) {
546
+ throw new Error("PROJECT_CONTEXT_REQUIRED");
547
+ }
548
+ const fallbackOrg = declared.organizationId ?? "";
549
+ const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
550
+ const orgs = await bootstrapClient.organization.list.query();
551
+ if (orgs.length === 0) {
552
+ throw new Error("No organization membership found for this account.");
553
+ }
554
+ const org = orgs.find((candidate) => candidate.id === fallbackOrg) ?? orgs[0];
555
+ const organizationId = org.id;
556
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
557
+ const projects = await client2.project.list.query({
558
+ limit: 20,
559
+ offset: 0
560
+ });
561
+ if (projects.length === 0) {
562
+ throw new Error("ONBOARDING_REQUIRED");
563
+ }
564
+ const project = projects.find((candidate) => candidate.id === declared.projectId);
565
+ if (!project) {
566
+ throw new Error("ONBOARDING_REQUIRED");
567
+ }
568
+ const repoPath = resolveContextWorkspaceRoot({
569
+ projectId: project.id,
570
+ fallbackDir: process.cwd()
571
+ });
572
+ return {
573
+ boot: {
574
+ apiUrl: this.apiUrl,
575
+ organizationId,
576
+ organizationName: org.name,
577
+ role: normalizeRole(org.role),
578
+ plan: normalizePlan(org.plan),
579
+ projectId: project.id,
580
+ projectName: project.name,
581
+ repoPath,
582
+ permissions
583
+ },
584
+ client: client2
585
+ };
586
+ }
587
+ hasDeclaredProjectContext(projectIdArg) {
588
+ const stored = this.credentialsStore.load();
589
+ const declared = resolveDeclaredContext({
590
+ explicitProjectId: projectIdArg,
591
+ repoPath: process.cwd(),
592
+ credentialsOrganizationId: stored?.organizationId,
593
+ envOrganizationId: process.env.SPEKN_ORGANIZATION_ID
594
+ });
595
+ return Boolean(declared.projectId);
596
+ }
597
+ async checkAuthentication() {
598
+ try {
599
+ const token = await this.credentialsStore.getValidToken();
600
+ return token || null;
601
+ } catch {
602
+ return null;
603
+ }
604
+ }
605
+ async authenticateViaCli(onProgress) {
606
+ const result = await this.runCliCommand([
607
+ "auth",
608
+ "login"
609
+ ], {
610
+ cwd: process.cwd(),
611
+ includeAuthToken: false,
612
+ onProgress
613
+ });
614
+ return result.success;
615
+ }
616
+ extractUserEmail(token) {
617
+ try {
618
+ const claims = decodeJwtPayload(token);
619
+ return typeof claims?.["email"] === "string" ? claims["email"] : void 0;
620
+ } catch {
621
+ return void 0;
622
+ }
623
+ }
624
+ extractTokenExpiry(token) {
625
+ try {
626
+ const claims = decodeJwtPayload(token);
627
+ if (typeof claims?.["exp"] === "number") {
628
+ return claims["exp"] * 1e3;
629
+ }
630
+ return void 0;
631
+ } catch {
632
+ return void 0;
633
+ }
634
+ }
635
+ async listOrganizations() {
636
+ const token = await this.credentialsStore.getValidToken();
637
+ if (!token) {
638
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
639
+ }
640
+ const stored = this.credentialsStore.load();
641
+ const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
642
+ const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
643
+ const orgs = await bootstrapClient.organization.list.query();
644
+ return orgs.map((org) => ({
645
+ id: org.id,
646
+ name: org.name,
647
+ plan: org.plan,
648
+ role: org.role
649
+ }));
650
+ }
651
+ async createOrganization(input) {
652
+ const token = await this.credentialsStore.getValidToken();
653
+ if (!token) {
654
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
655
+ }
656
+ const stored = this.credentialsStore.load();
657
+ const fallbackOrg = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
658
+ const bootstrapClient = createApiClient(this.apiUrl, token, fallbackOrg);
659
+ const createdOrg = await bootstrapClient.organization.create.mutate(input);
660
+ return {
661
+ id: createdOrg.id,
662
+ name: createdOrg.name,
663
+ plan: createdOrg.plan,
664
+ role: "owner"
665
+ };
666
+ }
667
+ async listProjects(organizationId) {
668
+ const token = await this.credentialsStore.getValidToken();
669
+ if (!token) {
670
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
671
+ }
672
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
673
+ const projects = await client2.project.list.query({
674
+ limit: 100,
675
+ offset: 0
676
+ });
677
+ return projects.map((project) => ({
678
+ id: project.id,
679
+ name: project.name
680
+ }));
681
+ }
682
+ async createProject(organizationId, name) {
683
+ try {
684
+ const token = await this.credentialsStore.getValidToken();
685
+ if (!token) {
686
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
687
+ }
688
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
689
+ const created = await client2.project.create.mutate({
690
+ name: name.trim()
691
+ });
692
+ return {
693
+ id: created.id,
694
+ name: String(created.name ?? name.trim())
695
+ };
696
+ } catch (error) {
697
+ const message = error instanceof Error ? error.message : String(error);
698
+ appendGlobalErrorLog({
699
+ source: "wizard.createProject",
700
+ message,
701
+ details: {
702
+ apiUrl: this.apiUrl,
703
+ organizationId,
704
+ projectName: name.trim(),
705
+ cwd: process.cwd()
706
+ }
707
+ });
708
+ throw error;
709
+ }
710
+ }
711
+ canCreateProject(org) {
712
+ const role = String(org?.role ?? "").toLowerCase();
713
+ return role === "owner" || role === "admin";
714
+ }
715
+ attachOrSyncCurrentRepository = /* @__PURE__ */ __name(async (organizationId, projectId, onProgress, _agentType, requestInteraction, onActivity) => {
716
+ const repoPath = process.cwd();
717
+ let args = [];
718
+ let lastOutputLines = [];
719
+ try {
720
+ const remoteUrl = this.execGit(repoPath, [
721
+ "remote",
722
+ "get-url",
723
+ "origin"
724
+ ]);
725
+ const token = await this.credentialsStore.getValidToken();
726
+ if (!token) {
727
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
728
+ }
729
+ const client2 = createApiClient(this.apiUrl, token, organizationId);
730
+ const repos = await client2.gitRepository.list.query({
731
+ projectId,
732
+ limit: 100,
733
+ offset: 0
734
+ });
735
+ const isAlreadyAttached = repos.some((repo) => repo.repositoryUrl === remoteUrl);
736
+ const cliEntry = this.resolveCliEntry();
737
+ if (!cliEntry) {
738
+ throw new Error("Could not resolve CLI entrypoint for repo register.");
739
+ }
740
+ const runAnalyze = !isAlreadyAttached;
741
+ args = isAlreadyAttached ? [
742
+ cliEntry,
743
+ "repo",
744
+ "sync",
745
+ "--project-id",
746
+ projectId,
747
+ "--path",
748
+ repoPath,
749
+ "--api-url",
750
+ this.apiUrl,
751
+ "--no-analyze"
752
+ ] : [
753
+ cliEntry,
754
+ "repo",
755
+ "register",
756
+ "--project-id",
757
+ projectId,
758
+ "--path",
759
+ repoPath,
760
+ "--api-url",
761
+ this.apiUrl,
762
+ "--analyze"
763
+ ];
764
+ if (isAlreadyAttached) {
765
+ onProgress?.("Repository already attached to this project. Syncing metadata only (no analysis)...");
766
+ } else {
767
+ onProgress?.("Repository not attached yet. Registering and running analysis...");
768
+ }
769
+ const runResult = await this.runCliCommand(args.slice(1), {
770
+ cwd: repoPath,
771
+ organizationId,
772
+ onProgress,
773
+ requestInteraction,
774
+ onActivity
775
+ });
776
+ lastOutputLines = runResult.outputLines;
777
+ const exitCode = runResult.exitCode;
778
+ if (exitCode !== 0) {
779
+ appendGlobalErrorLog({
780
+ source: "wizard.registerCurrentRepository",
781
+ message: `Repository registration/analysis failed (exit ${exitCode}).`,
782
+ details: {
783
+ apiUrl: this.apiUrl,
784
+ organizationId,
785
+ projectId,
786
+ repoPath,
787
+ command: process.execPath,
788
+ args,
789
+ lastOutputLines: lastOutputLines.slice(-80)
790
+ }
791
+ });
792
+ throw new Error(`Repository registration/analysis failed (exit ${exitCode}).`);
793
+ }
794
+ if (runAnalyze) {
795
+ persistProjectContext(repoPath, {
796
+ projectId,
797
+ organizationId
798
+ });
799
+ } else {
800
+ persistProjectContextWithoutRepoPath(repoPath, {
801
+ projectId,
802
+ organizationId
803
+ });
804
+ }
805
+ return {
806
+ success: true,
807
+ analyzed: runAnalyze
808
+ };
809
+ } catch (error) {
810
+ const message = error instanceof Error ? error.message : String(error);
811
+ appendGlobalErrorLog({
812
+ source: "wizard.registerCurrentRepository",
813
+ message,
814
+ details: {
815
+ apiUrl: this.apiUrl,
816
+ organizationId,
817
+ projectId,
818
+ repoPath,
819
+ command: process.execPath,
820
+ args,
821
+ lastOutputLines: lastOutputLines.slice(-80)
822
+ }
823
+ });
824
+ throw error;
825
+ }
826
+ }, "attachOrSyncCurrentRepository");
827
+ execGit(repoPath, args) {
828
+ try {
829
+ return execFileSync("git", [
830
+ "-C",
831
+ repoPath,
832
+ ...args
833
+ ], {
834
+ encoding: "utf-8",
835
+ stdio: [
836
+ "pipe",
837
+ "pipe",
838
+ "pipe"
839
+ ]
840
+ }).trim();
841
+ } catch {
842
+ throw new Error("Could not read git metadata. Run TUI from a git repository with an 'origin' remote.");
843
+ }
844
+ }
845
+ extractPermissions(token) {
846
+ const claims = decodeJwtPayload(token);
847
+ return Array.isArray(claims?.permissions) ? claims.permissions.filter((item) => typeof item === "string") : [];
848
+ }
849
+ async loadSpecs(client2, projectId) {
850
+ const specs = await client2.specification.list.query({
851
+ projectId,
852
+ limit: 50,
853
+ offset: 0
854
+ });
855
+ return (Array.isArray(specs) ? specs : []).map((spec) => {
856
+ const frontmatter = spec.frontmatter ?? {};
857
+ const hints = frontmatter.hints ?? {};
858
+ const aiContext = frontmatter.aiContext ?? {};
859
+ const acp = frontmatter.acp ?? {};
860
+ const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags.filter((tag) => typeof tag === "string") : [];
861
+ const aiFocusAreas = Array.isArray(aiContext.focusAreas) ? aiContext.focusAreas.filter((area) => typeof area === "string") : [];
862
+ const acpAllowedAgents = Array.isArray(acp.allowedAgents) ? acp.allowedAgents.filter((agent) => typeof agent === "string") : [];
863
+ const countArray = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.length : 0, "countArray");
864
+ return {
865
+ id: spec.id,
866
+ specRef: typeof frontmatter.specRef === "string" ? frontmatter.specRef : typeof spec.specRef === "string" ? spec.specRef : void 0,
867
+ frontmatter,
868
+ title: spec.title,
869
+ status: spec.status,
870
+ version: spec.version,
871
+ updatedAt: spec.updatedAt,
872
+ type: typeof frontmatter.type === "string" ? frontmatter.type : void 0,
873
+ content: typeof spec.content === "string" ? spec.content : void 0,
874
+ tags: tags.length > 0 ? tags : void 0,
875
+ author: typeof frontmatter.author === "string" ? frontmatter.author : void 0,
876
+ hintCounts: {
877
+ constraints: countArray(hints.constraints),
878
+ requirements: countArray(hints.requirements),
879
+ technical: countArray(hints.technical),
880
+ guidance: countArray(hints.guidance)
881
+ },
882
+ relationCounts: {
883
+ dependsOn: countArray(frontmatter.dependsOn),
884
+ conflictsWith: countArray(frontmatter.conflictsWith),
885
+ compatibleWith: countArray(frontmatter.compatibleWith)
886
+ },
887
+ acpPolicyMode: typeof acp.policyMode === "string" ? acp.policyMode : void 0,
888
+ acpAllowedAgents: acpAllowedAgents.length > 0 ? acpAllowedAgents : void 0,
889
+ aiTokenBudget: typeof aiContext.tokenBudget === "number" ? aiContext.tokenBudget : void 0,
890
+ aiFocusAreas: aiFocusAreas.length > 0 ? aiFocusAreas : void 0
891
+ };
892
+ });
893
+ }
894
+ async updateSpecificationContent(client2, projectId, specificationId, content) {
895
+ await client2.specification.update.mutate({
896
+ projectId,
897
+ id: specificationId,
898
+ data: {
899
+ content,
900
+ changeType: "patch",
901
+ changeDescription: "Edited from TUI editor"
902
+ }
903
+ });
904
+ }
905
+ async loadDecisions(client2, projectId) {
906
+ const result = await client2.decision.getAll.query({
907
+ projectId,
908
+ limit: 50,
909
+ offset: 0
910
+ });
911
+ const decisions = Array.isArray(result?.decisions) ? result.decisions : [];
912
+ return decisions.map((decision) => ({
913
+ id: decision.id,
914
+ title: decision.title,
915
+ status: decision.status,
916
+ decisionType: decision.decisionType,
917
+ specAnchor: decision.specAnchor,
918
+ createdAt: decision.createdAt
919
+ }));
920
+ }
921
+ async loadWorkflowSummary(client2, projectId) {
922
+ const states = await client2.workflowState.listByProject.query({
923
+ projectId
924
+ });
925
+ const first = Array.isArray(states) && states.length > 0 ? states[0] : null;
926
+ const currentPhase = first?.currentPhase ?? null;
927
+ const blockedCount = Array.isArray(states) ? states.filter((state) => state.specificationLockStatus === "locked").length : 0;
928
+ return {
929
+ currentPhase,
930
+ blockedCount,
931
+ hasVerificationEvidence: Boolean(first?.hasVerificationEvidence),
932
+ hasPlanningArtifacts: Boolean(first?.hasPlanningArtifacts)
933
+ };
934
+ }
935
+ async previewExport(client2, projectId, format) {
936
+ const result = await client2.export.preview.query({
937
+ projectId,
938
+ formatId: format
939
+ });
940
+ return {
941
+ content: String(result.content ?? ""),
942
+ anchorCount: Number(result.anchorCount ?? 0),
943
+ specVersion: typeof result.specVersion === "string" ? result.specVersion : void 0,
944
+ warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
945
+ };
946
+ }
947
+ async generateExport(client2, projectId, format) {
948
+ const result = await client2.export.generate.mutate({
949
+ projectId,
950
+ formatId: format
951
+ });
952
+ return {
953
+ content: String(result.content ?? ""),
954
+ anchorCount: Number(result.anchorCount ?? 0),
955
+ specVersion: typeof result.specVersion === "string" ? result.specVersion : void 0,
956
+ warnings: Array.isArray(result.warnings) ? result.warnings.filter((warning) => typeof warning === "string") : void 0
957
+ };
958
+ }
959
+ async loadBridgeSummary(client2) {
960
+ const [flag, devices, metrics] = await Promise.all([
961
+ client2.bridge.getFeatureFlag.query().catch(() => ({
962
+ enabled: false
963
+ })),
964
+ client2.bridge.listDevices.query().catch(() => []),
965
+ client2.bridge.getMetrics.query().catch(() => ({
966
+ connectedDevices: 0,
967
+ authFailures: 0
968
+ }))
969
+ ]);
970
+ return {
971
+ featureEnabled: Boolean(flag.enabled),
972
+ devices: Array.isArray(devices) ? devices.map((device) => ({
973
+ id: device.id,
974
+ name: device.name,
975
+ status: device.status,
976
+ isDefault: Boolean(device.isDefault),
977
+ lastSeenAt: device.lastSeenAt
978
+ })) : [],
979
+ connectedDevices: Number(metrics.connectedDevices ?? 0),
980
+ authFailures: Number(metrics.authFailures ?? 0)
981
+ };
982
+ }
983
+ async loadLocalBridgeSummary() {
984
+ const config = loadLocalBridgeConfig();
985
+ let running = false;
986
+ let uptimeSec;
987
+ try {
988
+ const response = await fetch(`http://127.0.0.1:${config.port}/health`);
989
+ if (response.ok) {
990
+ const payload = await response.json();
991
+ running = true;
992
+ uptimeSec = Number(payload.uptime ?? 0);
993
+ }
994
+ } catch {
995
+ running = false;
996
+ }
997
+ return {
998
+ paired: config.pairing !== null,
999
+ deviceId: config.pairing?.deviceId,
1000
+ deviceName: config.pairing?.deviceName,
1001
+ port: config.port,
1002
+ running,
1003
+ uptimeSec
1004
+ };
1005
+ }
1006
+ startLocalBridgeDetached() {
1007
+ const cliEntry = this.resolveCliEntry();
1008
+ if (!cliEntry) return;
1009
+ const args = [
1010
+ cliEntry,
1011
+ "bridge",
1012
+ "start"
1013
+ ];
1014
+ const child = spawn(process.execPath, args, {
1015
+ detached: true,
1016
+ stdio: "ignore"
1017
+ });
1018
+ child.unref();
1019
+ }
1020
+ async stopLocalBridge(configPort) {
1021
+ const port = configPort ?? loadLocalBridgeConfig().port;
1022
+ try {
1023
+ await fetch(`http://127.0.0.1:${port}/shutdown`, {
1024
+ method: "POST"
1025
+ });
1026
+ } catch {
1027
+ }
1028
+ }
1029
+ async loadBridgeLogs(port, since) {
1030
+ const p = port ?? loadLocalBridgeConfig().port;
1031
+ try {
1032
+ const url = since ? `http://127.0.0.1:${p}/logs?since=${since}` : `http://127.0.0.1:${p}/logs`;
1033
+ const res = await fetch(url);
1034
+ if (!res.ok) return [];
1035
+ const data = await res.json();
1036
+ return data.logs;
1037
+ } catch {
1038
+ return [];
1039
+ }
1040
+ }
1041
+ persistContext(organizationId, projectId) {
1042
+ persistSelectedProjectContext({
1043
+ organizationId,
1044
+ projectId
1045
+ });
1046
+ }
1047
+ async detachContextViaCli(_projectId, repoPath = process.cwd()) {
1048
+ const result = await this.runCliCommand([
1049
+ "repo",
1050
+ "detach",
1051
+ "--path",
1052
+ repoPath
1053
+ ], {
1054
+ cwd: repoPath,
1055
+ includeAuthToken: false
1056
+ });
1057
+ return {
1058
+ success: result.success,
1059
+ output: result.output || result.error || "Unknown detach error"
1060
+ };
1061
+ }
1062
+ async syncRepositoryViaCli(organizationId, projectId, repoPathInput, options) {
1063
+ const repoPath = path3.resolve(repoPathInput || process.cwd());
1064
+ if (!this.resolveCliEntry()) {
1065
+ return {
1066
+ success: false,
1067
+ output: "Could not resolve CLI entrypoint.",
1068
+ exitCode: 1
1069
+ };
1070
+ }
1071
+ const token = await this.credentialsStore.getValidToken();
1072
+ if (!token) {
1073
+ return {
1074
+ success: false,
1075
+ output: "No valid credentials. Run `spekn auth login` first.",
1076
+ exitCode: 1
1077
+ };
1078
+ }
1079
+ const args = [
1080
+ "repo",
1081
+ "sync",
1082
+ "--project-id",
1083
+ projectId,
1084
+ "--path",
1085
+ repoPath,
1086
+ "--api-url",
1087
+ this.apiUrl
1088
+ ];
1089
+ if (options?.analyze === false) {
1090
+ args.push("--no-analyze");
1091
+ }
1092
+ if (options?.importToProject) {
1093
+ args.push("--import-to-project");
1094
+ }
1095
+ if (typeof options?.maxFiles === "number" && Number.isFinite(options.maxFiles)) {
1096
+ args.push("--max-files", String(Math.max(1, Math.floor(options.maxFiles))));
1097
+ }
1098
+ if (options?.analysisEngine) {
1099
+ args.push("--analysis-engine", options.analysisEngine);
1100
+ }
1101
+ if (options?.agent && options.agent.trim().length > 0) {
1102
+ args.push("--agent", options.agent.trim());
1103
+ }
1104
+ try {
1105
+ const runResult = await this.runCliCommand(args, {
1106
+ cwd: repoPath,
1107
+ organizationId,
1108
+ onProgress: options?.onProgress,
1109
+ requestInteraction: options?.requestInteraction,
1110
+ onActivity: options?.onActivity
1111
+ });
1112
+ return {
1113
+ success: runResult.success,
1114
+ output: runResult.output,
1115
+ exitCode: runResult.exitCode
1116
+ };
1117
+ } catch (error) {
1118
+ const message = error instanceof Error ? error.message : String(error);
1119
+ return {
1120
+ success: false,
1121
+ output: message,
1122
+ exitCode: 1
1123
+ };
1124
+ }
1125
+ }
1126
+ async discoverExportCapabilities(projectId, organizationId) {
1127
+ const fallback = {
1128
+ plan: "free",
1129
+ modes: [
1130
+ "global"
1131
+ ],
1132
+ formats: [
1133
+ {
1134
+ id: "agents-md"
1135
+ },
1136
+ {
1137
+ id: "claude-md"
1138
+ },
1139
+ {
1140
+ id: "cursorrules"
1141
+ },
1142
+ {
1143
+ id: "gemini-md"
1144
+ }
1145
+ ]
1146
+ };
1147
+ const cliResult = await this.runCliJson([
1148
+ "export",
1149
+ "discover",
1150
+ "--project",
1151
+ projectId,
1152
+ "--api-url",
1153
+ this.apiUrl,
1154
+ "--json"
1155
+ ], void 0, organizationId);
1156
+ if (!cliResult.ok) {
1157
+ return fallback;
1158
+ }
1159
+ const result = cliResult.value;
1160
+ const modes = Array.isArray(result?.modes) ? result.modes.filter((mode) => mode === "global" || mode === "scoped") : fallback.modes;
1161
+ const formats = Array.isArray(result?.formats) ? result.formats.map((format) => {
1162
+ if (format?.id !== "agents-md" && format?.id !== "claude-md" && format?.id !== "cursorrules" && format?.id !== "gemini-md") {
1163
+ return null;
1164
+ }
1165
+ const formatModes = Array.isArray(format?.modes) ? format.modes.filter((mode) => mode === "global" || mode === "scoped") : void 0;
1166
+ return {
1167
+ id: format.id,
1168
+ name: typeof format?.name === "string" ? format.name : void 0,
1169
+ filename: typeof format?.filename === "string" ? format.filename : void 0,
1170
+ modes: formatModes
1171
+ };
1172
+ }).filter((format) => format !== null) : fallback.formats;
1173
+ return {
1174
+ plan: result?.plan === "pro" || result?.plan === "team" || result?.plan === "enterprise" ? result.plan : "free",
1175
+ modes: modes.length > 0 ? modes : fallback.modes,
1176
+ formats: formats.length > 0 ? formats : fallback.formats
1177
+ };
1178
+ }
1179
+ async exportStatus(projectId, format, options) {
1180
+ const args = [
1181
+ "export",
1182
+ "status",
1183
+ "--project",
1184
+ projectId,
1185
+ "--format",
1186
+ format,
1187
+ "--api-url",
1188
+ this.apiUrl,
1189
+ "--json"
1190
+ ];
1191
+ if (options?.mode) args.push("--mode", options.mode);
1192
+ if (options?.scopePath) args.push("--scope", options.scopePath);
1193
+ const cliResult = await this.runCliJson(args, void 0, options?.organizationId);
1194
+ if (!cliResult.ok) {
1195
+ return {
1196
+ overall: "missing",
1197
+ targets: []
1198
+ };
1199
+ }
1200
+ const result = cliResult.value;
1201
+ const overall = result?.overall === "diverged" || result?.overall === "outdated" || result?.overall === "up-to-date" ? result.overall : "missing";
1202
+ const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1203
+ const status = target?.status === "diverged" || target?.status === "outdated" || target?.status === "up-to-date" ? target.status : "missing";
1204
+ const kind = target?.kind === "canonical" ? "canonical" : "entrypoint";
1205
+ if (typeof target?.path !== "string") return null;
1206
+ return {
1207
+ path: target.path,
1208
+ kind,
1209
+ status
1210
+ };
1211
+ }).filter((target) => target !== null) : [];
1212
+ return {
1213
+ overall,
1214
+ targets
1215
+ };
1216
+ }
1217
+ async deliverExport(projectId, format, delivery, options) {
1218
+ const args = [
1219
+ "export",
1220
+ "--project",
1221
+ projectId,
1222
+ "--format",
1223
+ format,
1224
+ "--delivery",
1225
+ delivery,
1226
+ "--api-url",
1227
+ this.apiUrl,
1228
+ "--json"
1229
+ ];
1230
+ if (options?.mode) args.push("--mode", options.mode);
1231
+ if (options?.scopePath) args.push("--scope", options.scopePath);
1232
+ const exportCwd = delivery === "download" ? resolveContextWorkspaceRoot({
1233
+ projectId,
1234
+ fallbackDir: process.cwd()
1235
+ }) : process.cwd();
1236
+ const cliResult = await this.runCliJson(args, exportCwd, options?.organizationId);
1237
+ if (!cliResult.ok) {
1238
+ throw new Error(cliResult.error);
1239
+ }
1240
+ const result = cliResult.value;
1241
+ if (delivery === "commit") {
1242
+ return {
1243
+ message: typeof result?.commitSha === "string" ? `Committed to ${result.branch ?? "branch"}: ${result.commitSha}` : "Export commit completed."
1244
+ };
1245
+ }
1246
+ if (delivery === "pr") {
1247
+ return {
1248
+ message: typeof result?.prUrl === "string" ? `PR #${result.prNumber ?? "?"}: ${result.prUrl}` : "Export PR created."
1249
+ };
1250
+ }
1251
+ if (delivery === "download") {
1252
+ const targets = Array.isArray(result?.targets) ? result.targets.map((target) => {
1253
+ if (typeof target?.path !== "string") return null;
1254
+ return {
1255
+ path: target.path,
1256
+ kind: target?.kind === "canonical" ? "canonical" : "entrypoint",
1257
+ status: "up-to-date"
1258
+ };
1259
+ }).filter((target) => target !== null) : [];
1260
+ const count = targets.length;
1261
+ return {
1262
+ message: `Wrote ${count} export file(s) to ${exportCwd}.`,
1263
+ localStatus: {
1264
+ overall: "up-to-date",
1265
+ targets
1266
+ }
1267
+ };
1268
+ }
1269
+ return {
1270
+ message: "Export copy payload generated."
1271
+ };
1272
+ }
1273
+ async updateSpecificationStatus(client2, projectId, specificationId, status) {
1274
+ await client2.specification.update.mutate({
1275
+ projectId,
1276
+ id: specificationId,
1277
+ data: {
1278
+ status,
1279
+ changeType: "metadata",
1280
+ changeDescription: `Status changed to ${status} from TUI`
1281
+ }
1282
+ });
1283
+ }
1284
+ async deleteSpecification(client2, projectId, specificationId, mode = "archive") {
1285
+ const deleteMutation = client2?.specification?.delete?.mutate;
1286
+ if (typeof deleteMutation !== "function") {
1287
+ throw new Error("Specification delete route is unavailable.");
1288
+ }
1289
+ await deleteMutation({
1290
+ projectId,
1291
+ id: specificationId,
1292
+ mode
1293
+ });
1294
+ }
1295
+ async resolveDecision(client2, projectId, decisionId, status, reason, existingRationale) {
1296
+ await client2.decision.update.mutate({
1297
+ projectId,
1298
+ id: decisionId,
1299
+ data: {
1300
+ status,
1301
+ rationale: reason || existingRationale
1302
+ }
1303
+ });
1304
+ }
1305
+ async deleteDecision(client2, projectId, decisionId, mode = "archive") {
1306
+ const deleteMutation = client2?.decision?.delete?.mutate;
1307
+ if (typeof deleteMutation !== "function") {
1308
+ throw new Error("Decision delete route is unavailable.");
1309
+ }
1310
+ await deleteMutation({
1311
+ projectId,
1312
+ id: decisionId,
1313
+ mode
1314
+ });
1315
+ }
1316
+ async refineSpecificationWithAi(client2, input) {
1317
+ const refineMutation = client2?.specification?.refine?.mutate;
1318
+ if (typeof refineMutation !== "function") {
1319
+ throw new Error("Specification refine route is unavailable.");
1320
+ }
1321
+ const result = await refineMutation({
1322
+ projectId: input.projectId,
1323
+ specificationContent: input.specContent,
1324
+ userMessage: input.userMessage,
1325
+ agentType: input.agentType
1326
+ });
1327
+ if (typeof result?.content !== "string") {
1328
+ throw new Error("AI refinement response was missing content.");
1329
+ }
1330
+ return result.content;
1331
+ }
1332
+ async getAuthedClient() {
1333
+ const token = await this.credentialsStore.getValidToken();
1334
+ if (!token) {
1335
+ throw new Error("No valid credentials. Run `spekn auth login` first.");
1336
+ }
1337
+ const stored = this.credentialsStore.load();
1338
+ const organizationId = stored?.organizationId ?? process.env.SPEKN_ORGANIZATION_ID ?? "";
1339
+ return createApiClient(this.apiUrl, token, organizationId);
1340
+ }
1341
+ buildCliEnv(options) {
1342
+ const env = {
1343
+ ...process.env
1344
+ };
1345
+ delete env.SPEKN_ORGANIZATION_ID;
1346
+ if (options?.organizationId) {
1347
+ env.SPEKN_ORGANIZATION_ID = options.organizationId;
1348
+ }
1349
+ if (options?.interactionEnabled) {
1350
+ env.SPEKN_INTERACTION_MODE = "json-stdio";
1351
+ } else {
1352
+ delete env.SPEKN_INTERACTION_MODE;
1353
+ }
1354
+ return env;
1355
+ }
1356
+ async respondToInteraction(child, request, onProgress, requestInteraction) {
1357
+ const requestPromise = requestInteraction?.(request);
1358
+ const value = await Promise.race([
1359
+ requestPromise,
1360
+ new Promise((resolve) => setTimeout(() => resolve(void 0), 12e4))
1361
+ ]);
1362
+ if (!child.stdin || child.stdin.destroyed) return;
1363
+ if (value === "skip") {
1364
+ child.stdin.write(`${JSON.stringify({
1365
+ id: request.id,
1366
+ skip: true
1367
+ })}
1368
+ `);
1369
+ return;
1370
+ }
1371
+ const allowed = new Set(request.options.map((option) => option?.value).filter((optionValue) => typeof optionValue === "string"));
1372
+ if (typeof value === "string" && allowed.has(value)) {
1373
+ child.stdin.write(`${JSON.stringify({
1374
+ id: request.id,
1375
+ value
1376
+ })}
1377
+ `);
1378
+ return;
1379
+ }
1380
+ const fallbackValue = request.options[0]?.value;
1381
+ if (typeof fallbackValue === "string") {
1382
+ onProgress?.(`[interaction] Auto-selecting default: ${fallbackValue}`);
1383
+ child.stdin.write(`${JSON.stringify({
1384
+ id: request.id,
1385
+ value: fallbackValue
1386
+ })}
1387
+ `);
1388
+ return;
1389
+ }
1390
+ child.stdin.write(`${JSON.stringify({
1391
+ id: request.id
1392
+ })}
1393
+ `);
1394
+ }
1395
+ async runCliCommand(args, options) {
1396
+ const cliEntry = this.resolveCliEntry();
1397
+ if (!cliEntry) {
1398
+ return {
1399
+ success: false,
1400
+ exitCode: 1,
1401
+ stdoutLines: [],
1402
+ stderrLines: [],
1403
+ outputLines: [],
1404
+ output: "Could not resolve CLI entrypoint.",
1405
+ error: "Could not resolve CLI entrypoint."
1406
+ };
1407
+ }
1408
+ const includeAuthToken = options?.includeAuthToken !== false;
1409
+ const token = includeAuthToken ? await this.credentialsStore.getValidToken().catch(() => null) : null;
1410
+ const env = this.buildCliEnv({
1411
+ organizationId: options?.organizationId,
1412
+ interactionEnabled: Boolean(options?.requestInteraction)
1413
+ });
1414
+ if (includeAuthToken && token) {
1415
+ env.SPEKN_AUTH_TOKEN = token;
1416
+ } else if (!includeAuthToken) {
1417
+ delete env.SPEKN_AUTH_TOKEN;
1418
+ }
1419
+ const finalArgs = [
1420
+ cliEntry,
1421
+ ...args
1422
+ ];
1423
+ const stdoutLines = [];
1424
+ const stderrLines = [];
1425
+ const outputLines = [];
1426
+ const maxLines = options?.maxOutputLines ?? 250;
1427
+ let stdoutBuffer = "";
1428
+ let stderrBuffer = "";
1429
+ const pushLine = /* @__PURE__ */ __name((line, stream) => {
1430
+ const target = stream === "stdout" ? stdoutLines : stderrLines;
1431
+ target.push(line);
1432
+ outputLines.push(line);
1433
+ if (target.length > maxLines) target.shift();
1434
+ if (outputLines.length > maxLines) outputLines.shift();
1435
+ options?.onProgress?.(line);
1436
+ }, "pushLine");
1437
+ const processLine = /* @__PURE__ */ __name((line, stream, child) => {
1438
+ const trimmed = line.trim();
1439
+ if (!trimmed) return;
1440
+ const activityMarker = "[spekn-activity] ";
1441
+ const activityIdx = trimmed.indexOf(activityMarker);
1442
+ if (activityIdx >= 0) {
1443
+ try {
1444
+ const parsed = JSON.parse(trimmed.slice(activityIdx + activityMarker.length));
1445
+ if (parsed.type === "spekn.activity") {
1446
+ options?.onActivity?.(parsed);
1447
+ return;
1448
+ }
1449
+ } catch {
1450
+ }
1451
+ }
1452
+ const marker = "[spekn-interaction] ";
1453
+ const markerIndex = trimmed.indexOf(marker);
1454
+ if (options?.requestInteraction && markerIndex >= 0) {
1455
+ const payloadRaw = trimmed.slice(markerIndex + marker.length);
1456
+ let payload = null;
1457
+ try {
1458
+ payload = JSON.parse(payloadRaw);
1459
+ } catch {
1460
+ payload = null;
1461
+ }
1462
+ if (payload?.type === "spekn.interaction.request" && typeof payload.id === "string" && Array.isArray(payload.options)) {
1463
+ options.onProgress?.(`[interaction] ${payload.title ?? "Selection required"}`);
1464
+ const request = {
1465
+ id: payload.id,
1466
+ title: payload.title ?? "Selection required",
1467
+ message: payload.message ?? "Choose an option",
1468
+ options: payload.options,
1469
+ allowSkip: payload.allowSkip === true
1470
+ };
1471
+ void this.respondToInteraction(child, request, options.onProgress, options.requestInteraction).catch(() => {
1472
+ if (!child.stdin || child.stdin.destroyed) return;
1473
+ child.stdin.write(`${JSON.stringify({
1474
+ id: request.id
1475
+ })}
1476
+ `);
1477
+ });
1478
+ return;
1479
+ }
1480
+ }
1481
+ pushLine(trimmed, stream);
1482
+ }, "processLine");
1483
+ try {
1484
+ const child = spawn(process.execPath, finalArgs, {
1485
+ cwd: options?.cwd ?? process.cwd(),
1486
+ env,
1487
+ stdio: [
1488
+ "pipe",
1489
+ "pipe",
1490
+ "pipe"
1491
+ ]
1492
+ });
1493
+ const onData = /* @__PURE__ */ __name((stream, data) => {
1494
+ const chunk = String(data);
1495
+ if (stream === "stdout") {
1496
+ stdoutBuffer += chunk;
1497
+ } else {
1498
+ stderrBuffer += chunk;
1499
+ }
1500
+ const buffer = stream === "stdout" ? stdoutBuffer : stderrBuffer;
1501
+ const lines = buffer.split(/\r?\n|\r/);
1502
+ const remainder = lines.pop() ?? "";
1503
+ if (stream === "stdout") {
1504
+ stdoutBuffer = remainder;
1505
+ } else {
1506
+ stderrBuffer = remainder;
1507
+ }
1508
+ for (const line of lines) {
1509
+ processLine(line, stream, child);
1510
+ }
1511
+ }, "onData");
1512
+ child.stdout?.on("data", (data) => onData("stdout", data));
1513
+ child.stderr?.on("data", (data) => onData("stderr", data));
1514
+ const exitCode = await new Promise((resolve, reject) => {
1515
+ child.on("error", reject);
1516
+ child.on("close", (code) => resolve(code ?? 1));
1517
+ });
1518
+ if (stdoutBuffer.trim().length > 0) {
1519
+ processLine(stdoutBuffer, "stdout", child);
1520
+ }
1521
+ if (stderrBuffer.trim().length > 0) {
1522
+ processLine(stderrBuffer, "stderr", child);
1523
+ }
1524
+ return {
1525
+ success: exitCode === 0,
1526
+ exitCode,
1527
+ stdoutLines,
1528
+ stderrLines,
1529
+ outputLines,
1530
+ output: outputLines.join("\n")
1531
+ };
1532
+ } catch (error) {
1533
+ const message = error instanceof Error ? error.message : String(error);
1534
+ return {
1535
+ success: false,
1536
+ exitCode: 1,
1537
+ stdoutLines,
1538
+ stderrLines,
1539
+ outputLines,
1540
+ output: message,
1541
+ error: message
1542
+ };
1543
+ }
1544
+ }
1545
+ async runCliJson(args, cwd, organizationId) {
1546
+ const result = await this.runCliCommand(args, {
1547
+ cwd,
1548
+ organizationId,
1549
+ includeAuthToken: true
1550
+ });
1551
+ if (!result.success && result.output.trim().length === 0) {
1552
+ return {
1553
+ ok: false,
1554
+ error: result.error ?? "CLI command failed."
1555
+ };
1556
+ }
1557
+ const output = result.stdoutLines.join("\n").trim() || result.output.trim();
1558
+ const jsonStart = output.indexOf("{");
1559
+ if (jsonStart === -1) {
1560
+ return {
1561
+ ok: false,
1562
+ error: output || "Command produced no JSON output."
1563
+ };
1564
+ }
1565
+ try {
1566
+ const parsed = JSON.parse(output.slice(jsonStart));
1567
+ return {
1568
+ ok: true,
1569
+ value: parsed
1570
+ };
1571
+ } catch (error) {
1572
+ const message = error instanceof Error ? error.message : String(error);
1573
+ return {
1574
+ ok: false,
1575
+ error: message
1576
+ };
1577
+ }
1578
+ }
1579
+ resolveCliEntry() {
1580
+ const cliEntry = process.argv[1];
1581
+ return typeof cliEntry === "string" && cliEntry.length > 0 ? cliEntry : null;
1582
+ }
1583
+ };
1584
+
1585
+ // src/store/service-bridge.ts
1586
+ var service = null;
1587
+ var client = null;
1588
+ function initServiceBridge(apiUrl) {
1589
+ if (!service) {
1590
+ service = new TuiContextService(apiUrl);
1591
+ }
1592
+ return service;
1593
+ }
1594
+ __name(initServiceBridge, "initServiceBridge");
1595
+ function getService() {
1596
+ if (!service) {
1597
+ throw new Error("Service bridge not initialized. Call initServiceBridge() first.");
1598
+ }
1599
+ return service;
1600
+ }
1601
+ __name(getService, "getService");
1602
+ function getClient() {
1603
+ return client;
1604
+ }
1605
+ __name(getClient, "getClient");
1606
+ function setClient(c) {
1607
+ client = c;
1608
+ }
1609
+ __name(setClient, "setClient");
1610
+
1611
+ // src/store/use-tui-ui-store.ts
1612
+ import { create } from "zustand";
1613
+ import { subscribeWithSelector } from "zustand/middleware";
1614
+ var _initialScreen = "home";
1615
+ function setInitialScreen(screen) {
1616
+ _initialScreen = screen;
1617
+ }
1618
+ __name(setInitialScreen, "setInitialScreen");
1619
+ var initialState = {
1620
+ screen: _initialScreen,
1621
+ showHelp: false,
1622
+ commandMode: false,
1623
+ searchQuery: "",
1624
+ navMode: "content",
1625
+ cursorSpec: null,
1626
+ cursorDecision: null,
1627
+ openedSpecId: void 0,
1628
+ editorMenuOpen: false,
1629
+ statusMenuOpen: false,
1630
+ aiRefineMenuOpen: false,
1631
+ editorLaunching: false,
1632
+ selectedEditor: "",
1633
+ selectedOrganizationIndex: void 0,
1634
+ selectedProjectIndex: void 0,
1635
+ newProjectName: void 0,
1636
+ selectedAnalysisAgent: "auto"
1637
+ };
1638
+ var useTuiUiStore = create()(subscribeWithSelector((set) => ({
1639
+ ...initialState,
1640
+ screen: _initialScreen,
1641
+ setScreen: /* @__PURE__ */ __name((screen) => set({
1642
+ screen
1643
+ }), "setScreen"),
1644
+ toggleHelp: /* @__PURE__ */ __name(() => set((prev) => ({
1645
+ showHelp: !prev.showHelp
1646
+ })), "toggleHelp"),
1647
+ setShowHelp: /* @__PURE__ */ __name((show) => set({
1648
+ showHelp: show
1649
+ }), "setShowHelp"),
1650
+ setCommandMode: /* @__PURE__ */ __name((enabled) => set({
1651
+ commandMode: enabled
1652
+ }), "setCommandMode"),
1653
+ setSearchQuery: /* @__PURE__ */ __name((query) => set({
1654
+ searchQuery: query
1655
+ }), "setSearchQuery"),
1656
+ setNavMode: /* @__PURE__ */ __name((mode) => set({
1657
+ navMode: mode
1658
+ }), "setNavMode"),
1659
+ setCursorSpec: /* @__PURE__ */ __name((spec) => set({
1660
+ cursorSpec: spec
1661
+ }), "setCursorSpec"),
1662
+ setCursorDecision: /* @__PURE__ */ __name((decision) => set({
1663
+ cursorDecision: decision
1664
+ }), "setCursorDecision"),
1665
+ setOpenedSpecId: /* @__PURE__ */ __name((specId) => set({
1666
+ openedSpecId: specId
1667
+ }), "setOpenedSpecId"),
1668
+ setSelectedEditor: /* @__PURE__ */ __name((editor) => set({
1669
+ selectedEditor: editor
1670
+ }), "setSelectedEditor"),
1671
+ setEditorMenuOpen: /* @__PURE__ */ __name((open) => set({
1672
+ editorMenuOpen: open
1673
+ }), "setEditorMenuOpen"),
1674
+ setStatusMenuOpen: /* @__PURE__ */ __name((open) => set({
1675
+ statusMenuOpen: open
1676
+ }), "setStatusMenuOpen"),
1677
+ setAiRefineMenuOpen: /* @__PURE__ */ __name((open) => set({
1678
+ aiRefineMenuOpen: open
1679
+ }), "setAiRefineMenuOpen"),
1680
+ setEditorLaunching: /* @__PURE__ */ __name((launching) => set({
1681
+ editorLaunching: launching
1682
+ }), "setEditorLaunching"),
1683
+ openEditorMenuForSpec: /* @__PURE__ */ __name((specId, editor) => set({
1684
+ openedSpecId: specId,
1685
+ selectedEditor: editor,
1686
+ editorMenuOpen: true
1687
+ }), "openEditorMenuForSpec"),
1688
+ resetSpecsUi: /* @__PURE__ */ __name(() => set({
1689
+ openedSpecId: void 0,
1690
+ cursorSpec: null,
1691
+ editorMenuOpen: false,
1692
+ statusMenuOpen: false,
1693
+ aiRefineMenuOpen: false,
1694
+ editorLaunching: false
1695
+ }), "resetSpecsUi"),
1696
+ setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
1697
+ selectedOrganizationIndex: index
1698
+ }), "setSelectedOrganizationIndex"),
1699
+ setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
1700
+ selectedProjectIndex: index
1701
+ }), "setSelectedProjectIndex"),
1702
+ setNewProjectName: /* @__PURE__ */ __name((name) => set({
1703
+ newProjectName: name
1704
+ }), "setNewProjectName"),
1705
+ setSelectedAnalysisAgent: /* @__PURE__ */ __name((agent) => set({
1706
+ selectedAnalysisAgent: agent
1707
+ }), "setSelectedAnalysisAgent"),
1708
+ resetOnboardingUi: /* @__PURE__ */ __name(() => set({
1709
+ selectedOrganizationIndex: void 0,
1710
+ selectedProjectIndex: void 0,
1711
+ newProjectName: void 0,
1712
+ selectedAnalysisAgent: "auto"
1713
+ }), "resetOnboardingUi"),
1714
+ showTooltip: /* @__PURE__ */ __name((message, duration = 3e3) => set((state) => {
1715
+ if (state.tooltipTimeout) {
1716
+ clearTimeout(state.tooltipTimeout);
1717
+ }
1718
+ const timeout = setTimeout(() => {
1719
+ useTuiUiStore.getState().clearTooltip();
1720
+ }, duration);
1721
+ return {
1722
+ tooltip: message,
1723
+ tooltipTimeout: timeout
1724
+ };
1725
+ }), "showTooltip"),
1726
+ clearTooltip: /* @__PURE__ */ __name(() => set((state) => {
1727
+ if (state.tooltipTimeout) {
1728
+ clearTimeout(state.tooltipTimeout);
1729
+ }
1730
+ return {
1731
+ tooltip: void 0,
1732
+ tooltipTimeout: void 0
1733
+ };
1734
+ }), "clearTooltip")
1735
+ })));
1736
+
1737
+ // src/capabilities/policy.ts
1738
+ var TIER_ORDER = {
1739
+ [OrganizationPlan.FREE]: 0,
1740
+ [OrganizationPlan.PRO]: 1,
1741
+ [OrganizationPlan.TEAM]: 2,
1742
+ [OrganizationPlan.ENTERPRISE]: 3
1743
+ };
1744
+ var NAV_DEFINITIONS = [
1745
+ {
1746
+ id: "home",
1747
+ label: "Home",
1748
+ description: "Next actions and workflow pulse",
1749
+ requiredPlan: OrganizationPlan.FREE
1750
+ },
1751
+ {
1752
+ id: "specs",
1753
+ label: "Specs",
1754
+ description: "Manage governed specifications",
1755
+ requiredPlan: OrganizationPlan.FREE
1756
+ },
1757
+ {
1758
+ id: "decisions",
1759
+ label: "Decision Log",
1760
+ description: "Review decisions and rationale",
1761
+ requiredPlan: OrganizationPlan.FREE
1762
+ },
1763
+ {
1764
+ id: "export",
1765
+ label: "Export",
1766
+ description: "Generate AGENTS.md / CLAUDE.md / .cursorrules",
1767
+ requiredPlan: OrganizationPlan.FREE
1768
+ },
1769
+ {
1770
+ id: "bridge",
1771
+ label: "Local Bridge",
1772
+ description: "Bridge status and controls",
1773
+ requiredPlan: OrganizationPlan.FREE
1774
+ },
1775
+ {
1776
+ id: "active-runs",
1777
+ label: "Active Runs",
1778
+ description: "Realtime orchestration dashboard",
1779
+ requiredPlan: OrganizationPlan.TEAM
1780
+ },
1781
+ {
1782
+ id: "phase-gates",
1783
+ label: "Phase Gates",
1784
+ description: "Approve and unblock workflow phases",
1785
+ requiredPlan: OrganizationPlan.TEAM
1786
+ },
1787
+ {
1788
+ id: "skills-marketplace",
1789
+ label: "Skills Marketplace",
1790
+ description: "Manage shared managed skills",
1791
+ requiredPlan: OrganizationPlan.TEAM
1792
+ },
1793
+ {
1794
+ id: "org-governance",
1795
+ label: "Org Governance",
1796
+ description: "Compliance, policy, deployment gates",
1797
+ requiredPlan: OrganizationPlan.ENTERPRISE
1798
+ }
1799
+ ];
1800
+ var GATE_DISABLED_PHASES = [
1801
+ WorkflowPhase.SPECIFY,
1802
+ WorkflowPhase.CLARIFY
1803
+ ];
1804
+ function meetsMinimumTier(current, required) {
1805
+ return TIER_ORDER[current] >= TIER_ORDER[required];
1806
+ }
1807
+ __name(meetsMinimumTier, "meetsMinimumTier");
1808
+ function resolveNavPolicy(ctx) {
1809
+ return NAV_DEFINITIONS.map((item) => {
1810
+ if (!meetsMinimumTier(ctx.plan, item.requiredPlan)) {
1811
+ return {
1812
+ ...item,
1813
+ state: "locked",
1814
+ reason: `Requires ${item.requiredPlan.toUpperCase()} tier`
1815
+ };
1816
+ }
1817
+ if (item.id === "phase-gates" && ctx.role === "viewer") {
1818
+ return {
1819
+ ...item,
1820
+ state: "disabled",
1821
+ reason: "Viewer role cannot approve gates"
1822
+ };
1823
+ }
1824
+ if (item.id === "phase-gates" && ctx.workflowPhase && GATE_DISABLED_PHASES.includes(ctx.workflowPhase)) {
1825
+ return {
1826
+ ...item,
1827
+ state: "disabled",
1828
+ reason: `Gate approvals are unavailable in ${ctx.workflowPhase} phase`
1829
+ };
1830
+ }
1831
+ return {
1832
+ ...item,
1833
+ state: "enabled"
1834
+ };
1835
+ });
1836
+ }
1837
+ __name(resolveNavPolicy, "resolveNavPolicy");
1838
+
1839
+ // src/state/onboarding-utils.ts
1840
+ function logOnboardingAttachResult(appendLog, result) {
1841
+ if (result.warning) {
1842
+ appendLog(`[warn] ${result.warning}`);
1843
+ }
1844
+ if (result.analyzed) {
1845
+ appendLog("[setup] Repository attached and analysis complete.");
1846
+ } else if (result.warning) {
1847
+ appendLog("[setup] Repository attached; analysis did not fully complete.");
1848
+ } else {
1849
+ appendLog("[setup] Repository already attached. Metadata sync complete (analysis skipped).");
1850
+ }
1851
+ }
1852
+ __name(logOnboardingAttachResult, "logOnboardingAttachResult");
1853
+
1854
+ // src/store/windows/use-onboarding-window.ts
1855
+ import { create as create2 } from "zustand";
1856
+ import { subscribeWithSelector as subscribeWithSelector2 } from "zustand/middleware";
1857
+ var useOnboardingWindow = create2()(subscribeWithSelector2((set) => ({
1858
+ mode: "initial-setup",
1859
+ step: "organization",
1860
+ attachCurrentFolder: true,
1861
+ runLines: [],
1862
+ runStatus: "running",
1863
+ availableAgents: [],
1864
+ canCreateProject: false,
1865
+ toolCalls: {},
1866
+ setMode: /* @__PURE__ */ __name((mode) => set({
1867
+ mode
1868
+ }), "setMode"),
1869
+ setStep: /* @__PURE__ */ __name((step) => set({
1870
+ step
1871
+ }), "setStep"),
1872
+ setSelectedOrganizationIndex: /* @__PURE__ */ __name((index) => set({
1873
+ selectedOrganizationIndex: index
1874
+ }), "setSelectedOrganizationIndex"),
1875
+ setSelectedProjectIndex: /* @__PURE__ */ __name((index) => set({
1876
+ selectedProjectIndex: index
1877
+ }), "setSelectedProjectIndex"),
1878
+ setNewProjectName: /* @__PURE__ */ __name((name) => set({
1879
+ newProjectName: name
1880
+ }), "setNewProjectName"),
1881
+ setAttachCurrentFolder: /* @__PURE__ */ __name((attach) => set({
1882
+ attachCurrentFolder: attach
1883
+ }), "setAttachCurrentFolder"),
1884
+ setRunLines: /* @__PURE__ */ __name((lines) => set({
1885
+ runLines: lines
1886
+ }), "setRunLines"),
1887
+ addRunLine: /* @__PURE__ */ __name((line) => set((state) => ({
1888
+ runLines: [
1889
+ ...state.runLines,
1890
+ line
1891
+ ].slice(-400)
1892
+ })), "addRunLine"),
1893
+ setRunStatus: /* @__PURE__ */ __name((status) => set({
1894
+ runStatus: status
1895
+ }), "setRunStatus"),
1896
+ setInteraction: /* @__PURE__ */ __name((interaction) => set({
1897
+ interaction
1898
+ }), "setInteraction"),
1899
+ setError: /* @__PURE__ */ __name((error) => set({
1900
+ error
1901
+ }), "setError"),
1902
+ setSelectedOrganizationId: /* @__PURE__ */ __name((id) => set({
1903
+ selectedOrganizationId: id
1904
+ }), "setSelectedOrganizationId"),
1905
+ setSelectedProjectId: /* @__PURE__ */ __name((id) => set({
1906
+ selectedProjectId: id
1907
+ }), "setSelectedProjectId"),
1908
+ setAvailableAgents: /* @__PURE__ */ __name((agents) => set({
1909
+ availableAgents: agents
1910
+ }), "setAvailableAgents"),
1911
+ setCanCreateProject: /* @__PURE__ */ __name((canCreate) => set({
1912
+ canCreateProject: canCreate
1913
+ }), "setCanCreateProject"),
1914
+ upsertToolCall: /* @__PURE__ */ __name((event) => set((state) => {
1915
+ const id = event.toolCallId ?? `tc-${Date.now()}`;
1916
+ const existing = state.toolCalls[id];
1917
+ const updated = existing ? {
1918
+ ...existing,
1919
+ status: event.status ?? existing.status,
1920
+ title: event.title ?? existing.title,
1921
+ locations: event.locations ?? existing.locations,
1922
+ completedAt: event.status === "completed" || event.status === "failed" ? Date.now() : existing.completedAt
1923
+ } : {
1924
+ toolCallId: id,
1925
+ title: event.title ?? event.toolName ?? "Tool call",
1926
+ toolName: event.toolName,
1927
+ kind: event.kind ?? "other",
1928
+ status: event.status ?? "in_progress",
1929
+ locations: event.locations ?? [],
1930
+ startedAt: Date.now()
1931
+ };
1932
+ return {
1933
+ toolCalls: {
1934
+ ...state.toolCalls,
1935
+ [id]: updated
1936
+ }
1937
+ };
1938
+ }), "upsertToolCall"),
1939
+ setActiveThought: /* @__PURE__ */ __name((text) => set({
1940
+ activeThought: text
1941
+ }), "setActiveThought"),
1942
+ reset: /* @__PURE__ */ __name(() => set({
1943
+ mode: "initial-setup",
1944
+ step: "organization",
1945
+ selectedOrganizationIndex: void 0,
1946
+ selectedProjectIndex: void 0,
1947
+ newProjectName: void 0,
1948
+ attachCurrentFolder: true,
1949
+ runLines: [],
1950
+ runStatus: "running",
1951
+ interaction: void 0,
1952
+ error: void 0,
1953
+ selectedOrganizationId: void 0,
1954
+ selectedProjectId: void 0,
1955
+ availableAgents: [],
1956
+ canCreateProject: false,
1957
+ toolCalls: {},
1958
+ activeThought: void 0
1959
+ }), "reset")
1960
+ })));
1961
+
1962
+ // src/store/auth-utils.ts
1963
+ function isAuthenticationError(message) {
1964
+ const normalized = message.toLowerCase();
1965
+ return normalized.includes("authentication required") || normalized.includes("no valid credentials") || normalized.includes("unauthorized") || normalized.includes("forbidden") || normalized.includes("invalid token") || normalized.includes("token expired") || normalized.includes("auth");
1966
+ }
1967
+ __name(isAuthenticationError, "isAuthenticationError");
1968
+
1969
+ // src/store/use-project-data-store.ts
1970
+ import { create as create3 } from "zustand";
1971
+ import { subscribeWithSelector as subscribeWithSelector3 } from "zustand/middleware";
1972
+ var EMPTY_WORKFLOW = {
1973
+ currentPhase: null,
1974
+ blockedCount: 0,
1975
+ hasPlanningArtifacts: false,
1976
+ hasVerificationEvidence: false
1977
+ };
1978
+ var useProjectDataStore = create3()(subscribeWithSelector3((set, get) => ({
1979
+ specs: [],
1980
+ decisions: [],
1981
+ workflow: EMPTY_WORKFLOW,
1982
+ navPolicy: [],
1983
+ setProjectData: /* @__PURE__ */ __name((specs, decisions, workflow, navPolicy) => set({
1984
+ specs,
1985
+ decisions,
1986
+ workflow,
1987
+ navPolicy
1988
+ }), "setProjectData"),
1989
+ setPollingData: /* @__PURE__ */ __name((workflow, navPolicy) => set({
1990
+ workflow,
1991
+ navPolicy
1992
+ }), "setPollingData"),
1993
+ clearProjectData: /* @__PURE__ */ __name(() => set({
1994
+ specs: [],
1995
+ decisions: [],
1996
+ workflow: EMPTY_WORKFLOW,
1997
+ navPolicy: []
1998
+ }), "clearProjectData"),
1999
+ updateSpecificationContent: /* @__PURE__ */ __name(async (specificationId, content) => {
2000
+ const client2 = getClient();
2001
+ const boot = getBootContext();
2002
+ if (!client2 || !boot) return;
2003
+ await withSessionFeedback({
2004
+ statusLine: "Saving specification...",
2005
+ action: /* @__PURE__ */ __name(() => getService().updateSpecificationContent(client2, boot.projectId, specificationId, content), "action"),
2006
+ successLog: "[specs] saved specification changes",
2007
+ failureLog: "[error] save failed",
2008
+ failureStatusLine: "Save failed"
2009
+ });
2010
+ }, "updateSpecificationContent"),
2011
+ updateSpecificationStatus: /* @__PURE__ */ __name(async (specificationId, status, options) => {
2012
+ const client2 = getClient();
2013
+ const boot = getBootContext();
2014
+ if (!client2 || !boot) return;
2015
+ setSessionStatusLine(`Updating status to ${status}...`);
2016
+ try {
2017
+ await getService().updateSpecificationStatus(client2, boot.projectId, specificationId, status);
2018
+ appendSessionLog(`[specs] status updated to ${status}`);
2019
+ if (options?.refresh !== false) {
2020
+ const { useSessionStore: useSessionStore2 } = await import("./use-session-store-IJE5KVOC.mjs");
2021
+ await useSessionStore2.getState().refresh();
2022
+ }
2023
+ } catch (error) {
2024
+ const message = error instanceof Error ? error.message : String(error);
2025
+ appendSessionLog(`[error] status update failed: ${message}`);
2026
+ setSessionStatusLine("Status update failed");
2027
+ refreshOnAuthenticationError(message);
2028
+ }
2029
+ }, "updateSpecificationStatus"),
2030
+ deleteSpecification: /* @__PURE__ */ __name(async (specificationId, mode = "archive", options) => {
2031
+ const client2 = getClient();
2032
+ const boot = getBootContext();
2033
+ if (!client2 || !boot) return;
2034
+ setSessionStatusLine(mode === "delete" ? "Deleting specification permanently..." : "Archiving specification...");
2035
+ try {
2036
+ await getService().deleteSpecification(client2, boot.projectId, specificationId, mode);
2037
+ appendSessionLog(mode === "delete" ? "[specs] specification deleted permanently" : "[specs] specification archived");
2038
+ if (options?.refresh !== false) {
2039
+ const { useSessionStore: useSessionStore2 } = await import("./use-session-store-IJE5KVOC.mjs");
2040
+ await useSessionStore2.getState().refresh();
2041
+ }
2042
+ } catch (error) {
2043
+ const message = error instanceof Error ? error.message : String(error);
2044
+ appendSessionLog(`[error] specification ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2045
+ setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2046
+ refreshOnAuthenticationError(message);
2047
+ }
2048
+ }, "deleteSpecification"),
2049
+ refineSpecificationWithAi: /* @__PURE__ */ __name(async (specificationId, userMessage) => {
2050
+ const client2 = getClient();
2051
+ const boot = getBootContext();
2052
+ const { specs } = get();
2053
+ if (!client2 || !boot) return;
2054
+ const spec = specs.find((item) => item.id === specificationId);
2055
+ if (!spec) {
2056
+ appendSessionLog("[error] refine failed: specification not found in current list");
2057
+ setSessionStatusLine("Refinement failed");
2058
+ return;
2059
+ }
2060
+ const specContent = (spec.content ?? "").trim();
2061
+ if (!specContent) {
2062
+ appendSessionLog("[error] refine failed: selected specification has no content");
2063
+ setSessionStatusLine("Refinement failed");
2064
+ return;
2065
+ }
2066
+ setSessionStatusLine("Refining specification with AI...");
2067
+ const service2 = getService();
2068
+ try {
2069
+ const refinedContent = await service2.refineSpecificationWithAi(client2, {
2070
+ projectId: boot.projectId,
2071
+ specContent,
2072
+ userMessage,
2073
+ agentType: "codex"
2074
+ });
2075
+ await service2.updateSpecificationContent(client2, boot.projectId, specificationId, refinedContent);
2076
+ appendSessionLog("[specs] AI refinement applied and saved");
2077
+ const { useSessionStore: useSessionStore2 } = await import("./use-session-store-IJE5KVOC.mjs");
2078
+ await useSessionStore2.getState().refresh();
2079
+ } catch (error) {
2080
+ const message = error instanceof Error ? error.message : String(error);
2081
+ appendSessionLog(`[error] AI refinement failed: ${message}`);
2082
+ setSessionStatusLine("AI refinement failed");
2083
+ refreshOnAuthenticationError(message);
2084
+ }
2085
+ }, "refineSpecificationWithAi"),
2086
+ resolveDecision: /* @__PURE__ */ __name(async (decisionId, status, reason, existingRationale, options) => {
2087
+ const client2 = getClient();
2088
+ const boot = getBootContext();
2089
+ if (!client2 || !boot) {
2090
+ throw new Error("Decision update unavailable: project context is not initialized.");
2091
+ }
2092
+ setSessionStatusLine(`Resolving decision as ${status}...`);
2093
+ try {
2094
+ await getService().resolveDecision(client2, boot.projectId, decisionId, status, reason, existingRationale);
2095
+ appendSessionLog(`[decisions] ${decisionId} -> ${status}`);
2096
+ if (options?.refresh !== false) {
2097
+ const { useSessionStore: useSessionStore2 } = await import("./use-session-store-IJE5KVOC.mjs");
2098
+ await useSessionStore2.getState().refresh();
2099
+ }
2100
+ } catch (error) {
2101
+ const message = error instanceof Error ? error.message : String(error);
2102
+ appendSessionLog(`[error] decision resolution failed: ${message}`);
2103
+ setSessionStatusLine("Decision resolution failed");
2104
+ refreshOnAuthenticationError(message);
2105
+ throw error;
2106
+ }
2107
+ }, "resolveDecision"),
2108
+ deleteDecision: /* @__PURE__ */ __name(async (decisionId, mode = "archive", options) => {
2109
+ const client2 = getClient();
2110
+ const boot = getBootContext();
2111
+ if (!client2 || !boot) {
2112
+ throw new Error("Decision delete unavailable: project context is not initialized.");
2113
+ }
2114
+ setSessionStatusLine(mode === "delete" ? "Deleting decision permanently..." : "Archiving decision...");
2115
+ try {
2116
+ await getService().deleteDecision(client2, boot.projectId, decisionId, mode);
2117
+ appendSessionLog(mode === "delete" ? `[decisions] ${decisionId} deleted permanently` : `[decisions] ${decisionId} archived`);
2118
+ if (options?.refresh !== false) {
2119
+ const { useSessionStore: useSessionStore2 } = await import("./use-session-store-IJE5KVOC.mjs");
2120
+ await useSessionStore2.getState().refresh();
2121
+ }
2122
+ } catch (error) {
2123
+ const message = error instanceof Error ? error.message : String(error);
2124
+ appendSessionLog(`[error] decision ${mode === "delete" ? "delete" : "archive"} failed: ${message}`);
2125
+ setSessionStatusLine(mode === "delete" ? "Permanent delete failed" : "Archive failed");
2126
+ refreshOnAuthenticationError(message);
2127
+ throw error;
2128
+ }
2129
+ }, "deleteDecision")
2130
+ })));
2131
+
2132
+ // src/store/use-export-store.ts
2133
+ import { create as create4 } from "zustand";
2134
+ import { subscribeWithSelector as subscribeWithSelector4 } from "zustand/middleware";
2135
+
2136
+ // src/utils/clipboard.ts
2137
+ import { spawnSync } from "child_process";
2138
+ function clipboardAttempts() {
2139
+ if (process.platform === "darwin") {
2140
+ return [
2141
+ {
2142
+ cmd: "pbcopy",
2143
+ args: []
2144
+ }
2145
+ ];
2146
+ }
2147
+ if (process.platform === "win32") {
2148
+ return [
2149
+ {
2150
+ cmd: "clip",
2151
+ args: []
2152
+ }
2153
+ ];
2154
+ }
2155
+ return [
2156
+ {
2157
+ cmd: "wl-copy",
2158
+ args: []
2159
+ },
2160
+ {
2161
+ cmd: "xclip",
2162
+ args: [
2163
+ "-selection",
2164
+ "clipboard"
2165
+ ]
2166
+ },
2167
+ {
2168
+ cmd: "xsel",
2169
+ args: [
2170
+ "--clipboard",
2171
+ "--input"
2172
+ ]
2173
+ }
2174
+ ];
2175
+ }
2176
+ __name(clipboardAttempts, "clipboardAttempts");
2177
+ function copyTextToClipboard(text) {
2178
+ const attempts = clipboardAttempts();
2179
+ let lastError = "No clipboard command available.";
2180
+ for (const attempt of attempts) {
2181
+ const result = spawnSync(attempt.cmd, attempt.args, {
2182
+ input: text,
2183
+ encoding: "utf8",
2184
+ stdio: [
2185
+ "pipe",
2186
+ "ignore",
2187
+ "pipe"
2188
+ ]
2189
+ });
2190
+ if (!result.error && result.status === 0) {
2191
+ return {
2192
+ ok: true
2193
+ };
2194
+ }
2195
+ lastError = (result.error?.message ?? result.stderr?.trim()) || `${attempt.cmd} exited with status ${result.status}`;
2196
+ }
2197
+ return {
2198
+ ok: false,
2199
+ error: lastError
2200
+ };
2201
+ }
2202
+ __name(copyTextToClipboard, "copyTextToClipboard");
2203
+
2204
+ // src/store/use-export-store.ts
2205
+ var EMPTY_EXPORT_JOB = {
2206
+ action: null,
2207
+ status: "idle"
2208
+ };
2209
+ async function runExport(action) {
2210
+ const state = useExportStore.getState();
2211
+ const boot = getBootContext();
2212
+ if (!boot) return;
2213
+ if (state.exportInFlight) {
2214
+ appendSessionLog("[warn] Export already in progress");
2215
+ return;
2216
+ }
2217
+ const format = state.exportFormat;
2218
+ useExportStore.setState({
2219
+ exportInFlight: true,
2220
+ exportJob: {
2221
+ action,
2222
+ status: "running",
2223
+ format
2224
+ }
2225
+ });
2226
+ setSessionStatusLine(action === "preview" ? "Previewing export..." : "Generating export...");
2227
+ const service2 = getService();
2228
+ const client2 = getClient();
2229
+ try {
2230
+ if (action === "status") {
2231
+ const status = await service2.exportStatus(boot.projectId, format, {
2232
+ mode: state.exportMode,
2233
+ scopePath: state.exportScopePath || void 0,
2234
+ organizationId: boot.organizationId
2235
+ });
2236
+ useExportStore.setState({
2237
+ exportStatus: status,
2238
+ exportJob: {
2239
+ action,
2240
+ status: "success",
2241
+ format
2242
+ }
2243
+ });
2244
+ setSessionStatusLine(`Export status: ${status.overall}`);
2245
+ appendSessionLog(`[export] Status ${format}: ${status.overall}`);
2246
+ return;
2247
+ }
2248
+ if (action === "commit" || action === "pr") {
2249
+ const delivery = action === "commit" ? "commit" : "pr";
2250
+ const result = await service2.deliverExport(boot.projectId, format, delivery, {
2251
+ mode: state.exportMode,
2252
+ scopePath: state.exportScopePath || void 0,
2253
+ organizationId: boot.organizationId
2254
+ });
2255
+ useExportStore.setState({
2256
+ exportJob: {
2257
+ action,
2258
+ status: "success",
2259
+ format
2260
+ }
2261
+ });
2262
+ setSessionStatusLine(result.message);
2263
+ appendSessionLog(`[export] ${result.message}`);
2264
+ return;
2265
+ }
2266
+ const output = action === "preview" ? await service2.previewExport(client2, boot.projectId, format) : await service2.generateExport(client2, boot.projectId, format);
2267
+ useExportStore.setState({
2268
+ exportPreview: output,
2269
+ exportJob: {
2270
+ action,
2271
+ status: "success",
2272
+ format
2273
+ }
2274
+ });
2275
+ setSessionStatusLine(action === "preview" ? "Export preview ready" : "Export generated");
2276
+ const verb = action === "preview" ? "Previewed" : "Generated";
2277
+ appendSessionLog(`[export] ${verb} ${format} (${output.anchorCount} anchors)`);
2278
+ } catch (error) {
2279
+ const message = error instanceof Error ? error.message : String(error);
2280
+ useExportStore.setState({
2281
+ exportJob: {
2282
+ action,
2283
+ status: "error",
2284
+ format,
2285
+ error: message
2286
+ }
2287
+ });
2288
+ setSessionStatusLine(action === "preview" ? "Export preview failed" : "Export generation failed");
2289
+ appendSessionLog(`[error] Export ${action} failed: ${message}`);
2290
+ refreshOnAuthenticationError(message);
2291
+ } finally {
2292
+ useExportStore.setState({
2293
+ exportInFlight: false
2294
+ });
2295
+ }
2296
+ }
2297
+ __name(runExport, "runExport");
2298
+ var useExportStore = create4()(subscribeWithSelector4((set, get) => ({
2299
+ exportFormat: "agents-md",
2300
+ exportMode: "global",
2301
+ exportScopePath: "",
2302
+ exportDelivery: "download",
2303
+ exportCapabilities: null,
2304
+ exportPreview: null,
2305
+ exportStatus: null,
2306
+ exportValidation: {
2307
+ open: false
2308
+ },
2309
+ exportJob: EMPTY_EXPORT_JOB,
2310
+ exportInFlight: false,
2311
+ setCapabilities: /* @__PURE__ */ __name((capabilities) => {
2312
+ set((prev) => {
2313
+ const discoveredFormats = capabilities?.formats?.map((f) => f.id) ?? [];
2314
+ const discoveredModes = capabilities?.modes ?? [];
2315
+ const resolvedFormat = discoveredFormats.length > 0 ? discoveredFormats.includes(prev.exportFormat) ? prev.exportFormat : discoveredFormats[0] : prev.exportFormat;
2316
+ const resolvedMode = discoveredModes.length > 0 ? discoveredModes.includes(prev.exportMode) ? prev.exportMode : discoveredModes[0] : prev.exportMode;
2317
+ return {
2318
+ exportCapabilities: capabilities,
2319
+ exportFormat: resolvedFormat,
2320
+ exportMode: resolvedMode
2321
+ };
2322
+ });
2323
+ }, "setCapabilities"),
2324
+ setExportFormat: /* @__PURE__ */ __name((format) => {
2325
+ set((prev) => {
2326
+ const allowedFormats = prev.exportCapabilities?.formats.map((f) => f.id) ?? [];
2327
+ if (allowedFormats.length > 0 && !allowedFormats.includes(format)) {
2328
+ setSessionStatusLine(`Export format unavailable: ${format}`);
2329
+ return prev;
2330
+ }
2331
+ if (prev.exportFormat === format) return prev;
2332
+ setSessionStatusLine(`Export format set to ${format}`);
2333
+ return {
2334
+ exportFormat: format,
2335
+ exportPreview: null,
2336
+ exportStatus: null,
2337
+ exportValidation: {
2338
+ open: false
2339
+ },
2340
+ exportJob: EMPTY_EXPORT_JOB
2341
+ };
2342
+ });
2343
+ }, "setExportFormat"),
2344
+ setExportMode: /* @__PURE__ */ __name((mode) => {
2345
+ set((prev) => {
2346
+ const allowedModes = prev.exportCapabilities?.modes ?? [];
2347
+ if (allowedModes.length > 0 && !allowedModes.includes(mode)) {
2348
+ setSessionStatusLine(`Export mode unavailable: ${mode}`);
2349
+ return prev;
2350
+ }
2351
+ setSessionStatusLine(`Export mode set to ${mode}`);
2352
+ return {
2353
+ exportMode: mode
2354
+ };
2355
+ });
2356
+ }, "setExportMode"),
2357
+ setExportScopePath: /* @__PURE__ */ __name((scopePath) => {
2358
+ setSessionStatusLine("Updated export scope path");
2359
+ set({
2360
+ exportScopePath: scopePath
2361
+ });
2362
+ }, "setExportScopePath"),
2363
+ setExportDelivery: /* @__PURE__ */ __name((delivery) => {
2364
+ setSessionStatusLine(`Export delivery set to ${delivery}`);
2365
+ set({
2366
+ exportDelivery: delivery
2367
+ });
2368
+ }, "setExportDelivery"),
2369
+ previewExport: /* @__PURE__ */ __name(async () => {
2370
+ await runExport("preview");
2371
+ }, "previewExport"),
2372
+ generateExport: /* @__PURE__ */ __name(async () => {
2373
+ setSessionStatusLine("Confirm export validation to write files to disk");
2374
+ set({
2375
+ exportValidation: {
2376
+ open: true
2377
+ }
2378
+ });
2379
+ }, "generateExport"),
2380
+ validateAndWriteExport: /* @__PURE__ */ __name(async () => {
2381
+ const state = get();
2382
+ const boot = getBootContext();
2383
+ if (!boot) return;
2384
+ if (state.exportInFlight) {
2385
+ appendSessionLog("[warn] Export already in progress");
2386
+ return;
2387
+ }
2388
+ const format = state.exportFormat;
2389
+ set({
2390
+ exportInFlight: true,
2391
+ exportValidation: {
2392
+ open: false
2393
+ },
2394
+ exportJob: {
2395
+ action: "generate",
2396
+ status: "running",
2397
+ format
2398
+ }
2399
+ });
2400
+ setSessionStatusLine("Validating export and writing files...");
2401
+ const service2 = getService();
2402
+ try {
2403
+ const result = await service2.deliverExport(boot.projectId, format, "download", {
2404
+ mode: state.exportMode,
2405
+ scopePath: state.exportScopePath || void 0,
2406
+ organizationId: boot.organizationId
2407
+ });
2408
+ set((prev) => ({
2409
+ exportStatus: result.localStatus ?? prev.exportStatus,
2410
+ exportJob: {
2411
+ action: "generate",
2412
+ status: "success",
2413
+ format
2414
+ }
2415
+ }));
2416
+ setSessionStatusLine(result.message);
2417
+ appendSessionLog(`[export] ${result.message}`);
2418
+ } catch (error) {
2419
+ const message = error instanceof Error ? error.message : String(error);
2420
+ set({
2421
+ exportJob: {
2422
+ action: "generate",
2423
+ status: "error",
2424
+ format,
2425
+ error: message
2426
+ }
2427
+ });
2428
+ setSessionStatusLine("Export validation/write failed");
2429
+ appendSessionLog(`[error] Export validate/write failed: ${message}`);
2430
+ refreshOnAuthenticationError(message);
2431
+ } finally {
2432
+ set({
2433
+ exportInFlight: false
2434
+ });
2435
+ }
2436
+ }, "validateAndWriteExport"),
2437
+ cancelExportValidation: /* @__PURE__ */ __name(() => {
2438
+ setSessionStatusLine("Export validation cancelled");
2439
+ set({
2440
+ exportValidation: {
2441
+ open: false
2442
+ }
2443
+ });
2444
+ }, "cancelExportValidation"),
2445
+ statusExport: /* @__PURE__ */ __name(async () => {
2446
+ await runExport("status");
2447
+ }, "statusExport"),
2448
+ commitExport: /* @__PURE__ */ __name(async () => {
2449
+ await runExport("commit");
2450
+ }, "commitExport"),
2451
+ createPrExport: /* @__PURE__ */ __name(async () => {
2452
+ await runExport("pr");
2453
+ }, "createPrExport"),
2454
+ copyExportPreview: /* @__PURE__ */ __name(() => {
2455
+ const { exportPreview, exportJob } = get();
2456
+ const hasGeneratedPreview = exportJob.status === "success" && (exportJob.action === "preview" || exportJob.action === "generate");
2457
+ if (!exportPreview?.content || !hasGeneratedPreview) {
2458
+ setSessionStatusLine("No generated preview to copy. Run p or g first.");
2459
+ appendSessionLog("[warn] export copy requested before preview/generate completed");
2460
+ return;
2461
+ }
2462
+ const copied = copyTextToClipboard(exportPreview.content);
2463
+ if (copied.ok) {
2464
+ setSessionStatusLine("Copied preview to clipboard");
2465
+ appendSessionLog("[export] copied preview to clipboard");
2466
+ return;
2467
+ }
2468
+ setSessionStatusLine("Clipboard copy failed");
2469
+ appendSessionLog(`[error] clipboard copy failed: ${copied.error}`);
2470
+ }, "copyExportPreview")
2471
+ })));
2472
+
2473
+ // src/store/use-bridge-store.ts
2474
+ import { create as create5 } from "zustand";
2475
+ import { subscribeWithSelector as subscribeWithSelector5 } from "zustand/middleware";
2476
+ var useBridgeStore = create5()(subscribeWithSelector5((set, get) => ({
2477
+ bridge: null,
2478
+ localBridge: null,
2479
+ bridgeLogs: [],
2480
+ bridgeLogsSince: 0,
2481
+ startedByTui: false,
2482
+ setBridgeData: /* @__PURE__ */ __name((bridge, localBridge) => set({
2483
+ bridge,
2484
+ localBridge
2485
+ }), "setBridgeData"),
2486
+ setLocalBridge: /* @__PURE__ */ __name((localBridge) => set({
2487
+ localBridge
2488
+ }), "setLocalBridge"),
2489
+ setBridgeLogs: /* @__PURE__ */ __name((logs) => {
2490
+ if (logs.length === 0) return;
2491
+ const lastTimestamp = logs[logs.length - 1].timestamp;
2492
+ set((prev) => ({
2493
+ bridgeLogs: [
2494
+ ...prev.bridgeLogs,
2495
+ ...logs
2496
+ ].slice(-200),
2497
+ bridgeLogsSince: lastTimestamp
2498
+ }));
2499
+ }, "setBridgeLogs"),
2500
+ clearBridgeLogs: /* @__PURE__ */ __name(() => set({
2501
+ bridgeLogs: []
2502
+ }), "clearBridgeLogs"),
2503
+ bridgeStart: /* @__PURE__ */ __name(() => {
2504
+ const service2 = getService();
2505
+ service2.startLocalBridgeDetached();
2506
+ set({
2507
+ startedByTui: true
2508
+ });
2509
+ appendSessionLog("[bridge] Started local bridge process (detached)");
2510
+ setSessionStatusLine("Bridge start triggered (detached)");
2511
+ }, "bridgeStart"),
2512
+ bridgeStop: /* @__PURE__ */ __name(async () => {
2513
+ const service2 = getService();
2514
+ const { localBridge } = get();
2515
+ await service2.stopLocalBridge(localBridge?.port);
2516
+ appendSessionLog("[bridge] Stop signal sent");
2517
+ setSessionStatusLine("Bridge stop signal sent");
2518
+ }, "bridgeStop")
2519
+ })));
2520
+
2521
+ // src/store/store-effects.ts
2522
+ function dispatchRefreshComplete(data) {
2523
+ useProjectDataStore.getState().setProjectData(data.specs, data.decisions, data.workflow, data.navPolicy);
2524
+ useExportStore.getState().setCapabilities(data.exportCapabilities);
2525
+ useBridgeStore.getState().setBridgeData(data.bridge, data.localBridge);
2526
+ }
2527
+ __name(dispatchRefreshComplete, "dispatchRefreshComplete");
2528
+ function dispatchClearProjectData() {
2529
+ useProjectDataStore.getState().clearProjectData();
2530
+ }
2531
+ __name(dispatchClearProjectData, "dispatchClearProjectData");
2532
+ function refreshOnAuthenticationError(message) {
2533
+ if (!isAuthenticationError(message)) return;
2534
+ const { appendLog, refresh } = useSessionStore.getState();
2535
+ useSessionStore.setState({
2536
+ statusLine: "Authentication required. Refreshing context..."
2537
+ });
2538
+ appendLog("[auth] action requires authentication, refreshing context");
2539
+ void refresh();
2540
+ }
2541
+ __name(refreshOnAuthenticationError, "refreshOnAuthenticationError");
2542
+ async function withSessionFeedback(opts) {
2543
+ const { appendLog, refresh } = useSessionStore.getState();
2544
+ useSessionStore.setState({
2545
+ statusLine: opts.statusLine
2546
+ });
2547
+ try {
2548
+ const result = await opts.action();
2549
+ appendLog(opts.successLog);
2550
+ if (opts.refresh !== false) {
2551
+ await refresh();
2552
+ }
2553
+ return result;
2554
+ } catch (error) {
2555
+ const message = error instanceof Error ? error.message : String(error);
2556
+ appendLog(`${opts.failureLog}: ${message}`);
2557
+ useSessionStore.setState({
2558
+ statusLine: opts.failureStatusLine
2559
+ });
2560
+ refreshOnAuthenticationError(message);
2561
+ throw error;
2562
+ }
2563
+ }
2564
+ __name(withSessionFeedback, "withSessionFeedback");
2565
+ function getBootContext() {
2566
+ return useSessionStore.getState().boot;
2567
+ }
2568
+ __name(getBootContext, "getBootContext");
2569
+ function setSessionStatusLine(line) {
2570
+ useSessionStore.setState({
2571
+ statusLine: line
2572
+ });
2573
+ }
2574
+ __name(setSessionStatusLine, "setSessionStatusLine");
2575
+ function appendSessionLog(entry) {
2576
+ useSessionStore.getState().appendLog(entry);
2577
+ }
2578
+ __name(appendSessionLog, "appendSessionLog");
2579
+
2580
+ // src/store/use-session-store.ts
2581
+ var onboardingInteractionResolver = null;
2582
+ function requestOnboardingInteraction(request) {
2583
+ return new Promise((resolve) => {
2584
+ onboardingInteractionResolver = resolve;
2585
+ useSessionStore.setState((prev) => ({
2586
+ onboarding: prev.onboarding ? {
2587
+ ...prev.onboarding,
2588
+ interaction: request
2589
+ } : prev.onboarding
2590
+ }));
2591
+ });
2592
+ }
2593
+ __name(requestOnboardingInteraction, "requestOnboardingInteraction");
2594
+ function refreshOnAuthenticationError2(message) {
2595
+ if (!isAuthenticationError(message)) return;
2596
+ const { appendLog, refresh } = useSessionStore.getState();
2597
+ useSessionStore.setState({
2598
+ statusLine: "Authentication required. Refreshing context..."
2599
+ });
2600
+ appendLog("[auth] action requires authentication, refreshing context");
2601
+ void refresh();
2602
+ }
2603
+ __name(refreshOnAuthenticationError2, "refreshOnAuthenticationError");
2604
+ async function buildOnboardingState(mode) {
2605
+ const service2 = getService();
2606
+ const boot = useSessionStore.getState().boot;
2607
+ const organizations = await service2.listOrganizations();
2608
+ if (organizations.length === 0) {
2609
+ return {
2610
+ mode,
2611
+ step: "create-organization",
2612
+ attachCurrentFolder: mode === "initial-setup",
2613
+ organizations: [],
2614
+ projects: [],
2615
+ availableAgents: [],
2616
+ canCreateProject: false,
2617
+ error: void 0
2618
+ };
2619
+ }
2620
+ const preferredOrganizationId = boot?.organizationId;
2621
+ const selectedOrganization = organizations.find((org) => org.id === preferredOrganizationId) ?? organizations[0];
2622
+ const projects = await service2.listProjects(selectedOrganization.id);
2623
+ return {
2624
+ mode,
2625
+ step: organizations.length === 1 ? "project" : "organization",
2626
+ attachCurrentFolder: mode === "initial-setup",
2627
+ organizations,
2628
+ projects,
2629
+ availableAgents: [],
2630
+ canCreateProject: service2.canCreateProject(selectedOrganization),
2631
+ selectedOrganizationId: selectedOrganization.id,
2632
+ interaction: void 0,
2633
+ error: void 0
2634
+ };
2635
+ }
2636
+ __name(buildOnboardingState, "buildOnboardingState");
2637
+ var useSessionStore = create6()(subscribeWithSelector6((set, get) => ({
2638
+ boot: null,
2639
+ auth: null,
2640
+ onboarding: null,
2641
+ loading: true,
2642
+ error: null,
2643
+ statusLine: "Bootstrapping...",
2644
+ logs: [],
2645
+ appendLog: /* @__PURE__ */ __name((entry) => {
2646
+ const screen = useTuiUiStore.getState().screen;
2647
+ const level = entry.startsWith("[error]") ? "error" : entry.startsWith("[warn]") ? "warn" : "info";
2648
+ appendGlobalStructuredLog({
2649
+ source: "tui.event-log",
2650
+ level,
2651
+ message: entry,
2652
+ details: {
2653
+ screen
2654
+ }
2655
+ });
2656
+ set((prev) => ({
2657
+ logs: [
2658
+ entry,
2659
+ ...prev.logs
2660
+ ].slice(0, 40)
2661
+ }));
2662
+ }, "appendLog"),
2663
+ setStatusLine: /* @__PURE__ */ __name((line) => set({
2664
+ statusLine: line
2665
+ }), "setStatusLine"),
2666
+ setLoading: /* @__PURE__ */ __name((loading) => set({
2667
+ loading
2668
+ }), "setLoading"),
2669
+ setError: /* @__PURE__ */ __name((error) => set({
2670
+ error
2671
+ }), "setError"),
2672
+ authenticate: /* @__PURE__ */ __name(async () => {
2673
+ const { appendLog } = get();
2674
+ const service2 = getService();
2675
+ set({
2676
+ loading: false,
2677
+ auth: {
2678
+ status: "authenticating"
2679
+ },
2680
+ statusLine: "Starting browser login flow..."
2681
+ });
2682
+ appendLog("[auth] starting login flow");
2683
+ const ok = await service2.authenticateViaCli((line) => {
2684
+ appendLog(`[auth] ${line}`);
2685
+ });
2686
+ if (!ok) {
2687
+ set({
2688
+ auth: {
2689
+ status: "auth_failed",
2690
+ error: "Authentication failed. Check logs and try again."
2691
+ },
2692
+ statusLine: "Authentication failed"
2693
+ });
2694
+ appendLog("[auth] login flow failed");
2695
+ return;
2696
+ }
2697
+ appendLog("[auth] login flow completed");
2698
+ await get().refresh();
2699
+ }, "authenticate"),
2700
+ refresh: /* @__PURE__ */ __name(async (projectId) => {
2701
+ const service2 = getService();
2702
+ set((prev) => ({
2703
+ loading: prev.boot ? false : true,
2704
+ statusLine: "Loading context..."
2705
+ }));
2706
+ try {
2707
+ const token = await service2.checkAuthentication();
2708
+ if (!token) {
2709
+ set({
2710
+ loading: false,
2711
+ error: null,
2712
+ auth: {
2713
+ status: "unauthenticated",
2714
+ error: "No valid credentials. Please run `spekn auth login` to authenticate."
2715
+ },
2716
+ statusLine: "Authentication required"
2717
+ });
2718
+ return;
2719
+ }
2720
+ set({
2721
+ auth: {
2722
+ status: "authenticated",
2723
+ userEmail: service2.extractUserEmail(token),
2724
+ tokenExpiresAt: service2.extractTokenExpiry(token)
2725
+ }
2726
+ });
2727
+ if (!service2.hasDeclaredProjectContext(projectId)) {
2728
+ const onboarding = await buildOnboardingState("initial-setup");
2729
+ set({
2730
+ loading: false,
2731
+ error: null,
2732
+ onboarding,
2733
+ statusLine: "Project setup required"
2734
+ });
2735
+ return;
2736
+ }
2737
+ let bootstrapResult;
2738
+ try {
2739
+ bootstrapResult = await service2.bootstrap(projectId);
2740
+ } catch (bootstrapError) {
2741
+ if (bootstrapError instanceof Error && bootstrapError.message === "ONBOARDING_REQUIRED") {
2742
+ const onboarding = await buildOnboardingState("initial-setup");
2743
+ set({
2744
+ loading: false,
2745
+ error: null,
2746
+ onboarding,
2747
+ statusLine: "Project setup required"
2748
+ });
2749
+ return;
2750
+ }
2751
+ throw bootstrapError;
2752
+ }
2753
+ const { boot, client: client2 } = bootstrapResult;
2754
+ setClient(client2);
2755
+ const [specs, decisions, workflow, bridge, localBridge, exportCapabilities] = await Promise.all([
2756
+ service2.loadSpecs(client2, boot.projectId),
2757
+ service2.loadDecisions(client2, boot.projectId),
2758
+ service2.loadWorkflowSummary(client2, boot.projectId),
2759
+ service2.loadBridgeSummary(client2),
2760
+ service2.loadLocalBridgeSummary(),
2761
+ service2.discoverExportCapabilities(boot.projectId, boot.organizationId).catch(() => null)
2762
+ ]);
2763
+ const capabilityContext = {
2764
+ plan: boot.plan,
2765
+ role: boot.role,
2766
+ workflowPhase: workflow.currentPhase,
2767
+ permissions: boot.permissions
2768
+ };
2769
+ const navPolicy = resolveNavPolicy(capabilityContext);
2770
+ dispatchRefreshComplete({
2771
+ specs,
2772
+ decisions,
2773
+ workflow,
2774
+ navPolicy,
2775
+ exportCapabilities,
2776
+ bridge,
2777
+ localBridge
2778
+ });
2779
+ set({
2780
+ boot,
2781
+ loading: false,
2782
+ error: null,
2783
+ onboarding: null,
2784
+ statusLine: "Ready"
2785
+ });
2786
+ } catch (error) {
2787
+ const message = error instanceof Error ? error.message : String(error);
2788
+ let authStatus = null;
2789
+ if (message.includes("credentials") || message.includes("auth") || message.includes("token")) {
2790
+ authStatus = {
2791
+ status: "auth_failed",
2792
+ error: message
2793
+ };
2794
+ }
2795
+ set((prev) => ({
2796
+ loading: false,
2797
+ error: message,
2798
+ auth: authStatus || prev.auth,
2799
+ statusLine: "Error"
2800
+ }));
2801
+ get().appendLog(`[error] ${message}`);
2802
+ }
2803
+ }, "refresh"),
2804
+ switchContext: /* @__PURE__ */ __name(async () => {
2805
+ const { appendLog } = get();
2806
+ set({
2807
+ loading: true,
2808
+ error: null,
2809
+ statusLine: "Loading organizations..."
2810
+ });
2811
+ try {
2812
+ const onboarding = await buildOnboardingState("switch-context");
2813
+ set({
2814
+ loading: false,
2815
+ onboarding,
2816
+ statusLine: "Switch organization/project"
2817
+ });
2818
+ appendLog("[context] switch mode opened");
2819
+ } catch (error) {
2820
+ const message = error instanceof Error ? error.message : String(error);
2821
+ set({
2822
+ loading: false,
2823
+ statusLine: "Context switch failed",
2824
+ error: message
2825
+ });
2826
+ appendLog(`[error] context switch failed: ${message}`);
2827
+ refreshOnAuthenticationError2(message);
2828
+ }
2829
+ }, "switchContext"),
2830
+ detachRepoContext: /* @__PURE__ */ __name(async () => {
2831
+ const { boot, appendLog, refresh } = get();
2832
+ const service2 = getService();
2833
+ const result = await service2.detachContextViaCli(boot?.projectId, process.cwd());
2834
+ if (!result.success) {
2835
+ appendLog(`[error] Failed to detach context: ${result.output}`);
2836
+ set({
2837
+ statusLine: "Context detach failed"
2838
+ });
2839
+ return;
2840
+ }
2841
+ if (result.output) {
2842
+ appendLog(`[context] ${result.output}`);
2843
+ }
2844
+ appendLog("[context] Detached repository from local project context");
2845
+ set({
2846
+ boot: null,
2847
+ statusLine: "Repository detached. Select a project to attach."
2848
+ });
2849
+ dispatchClearProjectData();
2850
+ await refresh();
2851
+ }, "detachRepoContext"),
2852
+ syncRepository: /* @__PURE__ */ __name(async (options) => {
2853
+ const { boot, appendLog, refresh } = get();
2854
+ const service2 = getService();
2855
+ if (!boot) {
2856
+ appendLog("[error] repository sync unavailable: no active project context");
2857
+ set({
2858
+ statusLine: "Repository sync unavailable"
2859
+ });
2860
+ return false;
2861
+ }
2862
+ appendLog("[repo] running sync (metadata + drift analysis)");
2863
+ set({
2864
+ statusLine: "Syncing repository..."
2865
+ });
2866
+ const result = await service2.syncRepositoryViaCli(boot.organizationId, boot.projectId, boot.repoPath, {
2867
+ analyze: options?.analyze ?? true,
2868
+ importToProject: options?.importToProject,
2869
+ maxFiles: options?.maxFiles,
2870
+ analysisEngine: options?.analysisEngine,
2871
+ agent: options?.agent,
2872
+ requestInteraction: options?.requestInteraction,
2873
+ onProgress: /* @__PURE__ */ __name((line) => {
2874
+ appendLog(`[repo] ${line}`);
2875
+ options?.onProgress?.(line);
2876
+ }, "onProgress")
2877
+ });
2878
+ if (!result.success) {
2879
+ appendLog(`[error] repository sync failed (exit ${result.exitCode})`);
2880
+ set({
2881
+ statusLine: "Repository sync failed"
2882
+ });
2883
+ refreshOnAuthenticationError2(result.output);
2884
+ return false;
2885
+ }
2886
+ appendLog("[repo] sync completed");
2887
+ set({
2888
+ statusLine: "Repository sync completed"
2889
+ });
2890
+ await refresh();
2891
+ return true;
2892
+ }, "syncRepository"),
2893
+ // Onboarding actions
2894
+ selectOnboardingOrganization: /* @__PURE__ */ __name(async (index) => {
2895
+ const { onboarding, appendLog } = get();
2896
+ const service2 = getService();
2897
+ if (!onboarding) return;
2898
+ if (index < 0 || index >= onboarding.organizations.length) {
2899
+ set((prev) => ({
2900
+ onboarding: prev.onboarding ? {
2901
+ ...prev.onboarding,
2902
+ error: `Invalid organization index: ${index + 1}`
2903
+ } : prev.onboarding
2904
+ }));
2905
+ return;
2906
+ }
2907
+ const selectedOrganization = onboarding.organizations[index];
2908
+ set((prev) => ({
2909
+ loading: true,
2910
+ statusLine: "Loading projects...",
2911
+ onboarding: prev.onboarding ? {
2912
+ ...prev.onboarding,
2913
+ selectedOrganizationId: selectedOrganization.id,
2914
+ error: void 0
2915
+ } : prev.onboarding
2916
+ }));
2917
+ try {
2918
+ const projects = await service2.listProjects(selectedOrganization.id);
2919
+ set((prev) => ({
2920
+ loading: false,
2921
+ statusLine: "Select a project",
2922
+ onboarding: prev.onboarding ? {
2923
+ ...prev.onboarding,
2924
+ step: "project",
2925
+ attachCurrentFolder: prev.onboarding.attachCurrentFolder,
2926
+ projects,
2927
+ availableAgents: prev.onboarding?.availableAgents ?? [],
2928
+ canCreateProject: service2.canCreateProject(selectedOrganization),
2929
+ selectedOrganizationId: selectedOrganization.id,
2930
+ interaction: void 0,
2931
+ error: projects.length === 0 ? "No projects found in selected organization." : void 0
2932
+ } : prev.onboarding
2933
+ }));
2934
+ } catch (error) {
2935
+ const message = error instanceof Error ? error.message : String(error);
2936
+ set((prev) => ({
2937
+ loading: false,
2938
+ statusLine: "Setup error",
2939
+ onboarding: prev.onboarding ? {
2940
+ ...prev.onboarding,
2941
+ error: message
2942
+ } : prev.onboarding
2943
+ }));
2944
+ }
2945
+ }, "selectOnboardingOrganization"),
2946
+ registerOnboardingProject: /* @__PURE__ */ __name(async (index) => {
2947
+ const { onboarding, appendLog, refresh } = get();
2948
+ const service2 = getService();
2949
+ if (!onboarding || !onboarding.selectedOrganizationId) return;
2950
+ if (index < 0 || index >= onboarding.projects.length) {
2951
+ set((prev) => ({
2952
+ onboarding: prev.onboarding ? {
2953
+ ...prev.onboarding,
2954
+ error: `Invalid project index: ${index + 1}`
2955
+ } : prev.onboarding
2956
+ }));
2957
+ return;
2958
+ }
2959
+ const selectedProject = onboarding.projects[index];
2960
+ if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
2961
+ set((prev) => ({
2962
+ loading: true,
2963
+ statusLine: "Switching context...",
2964
+ onboarding: prev.onboarding ? {
2965
+ ...prev.onboarding,
2966
+ error: void 0
2967
+ } : prev.onboarding
2968
+ }));
2969
+ try {
2970
+ service2.persistContext(onboarding.selectedOrganizationId, selectedProject.id);
2971
+ appendLog(`[context] switched to ${selectedProject.name}`);
2972
+ await refresh();
2973
+ } catch (error) {
2974
+ const message = error instanceof Error ? error.message : String(error);
2975
+ set((prev) => ({
2976
+ loading: false,
2977
+ statusLine: "Context switch failed",
2978
+ onboarding: prev.onboarding ? {
2979
+ ...prev.onboarding,
2980
+ step: "project",
2981
+ error: message
2982
+ } : prev.onboarding
2983
+ }));
2984
+ }
2985
+ return;
2986
+ }
2987
+ set((prev) => ({
2988
+ loading: true,
2989
+ statusLine: "Registering repository...",
2990
+ onboarding: prev.onboarding ? {
2991
+ ...prev.onboarding,
2992
+ step: "registering",
2993
+ availableAgents: prev.onboarding?.availableAgents ?? [],
2994
+ selectedProjectId: selectedProject.id,
2995
+ runLines: [],
2996
+ runStatus: "running",
2997
+ interaction: void 0,
2998
+ error: void 0
2999
+ } : prev.onboarding
3000
+ }));
3001
+ try {
3002
+ await attachRepositoryFromOnboardingZustand({
3003
+ organizationId: onboarding.selectedOrganizationId,
3004
+ projectId: selectedProject.id
3005
+ });
3006
+ await refresh();
3007
+ } catch (error) {
3008
+ const message = error instanceof Error ? error.message : String(error);
3009
+ set((prev) => ({
3010
+ loading: false,
3011
+ statusLine: "Setup error",
3012
+ onboarding: prev.onboarding ? {
3013
+ ...prev.onboarding,
3014
+ step: "project",
3015
+ error: message
3016
+ } : prev.onboarding
3017
+ }));
3018
+ }
3019
+ }, "registerOnboardingProject"),
3020
+ createOnboardingProject: /* @__PURE__ */ __name(async (name) => {
3021
+ const { onboarding, appendLog, refresh } = get();
3022
+ const service2 = getService();
3023
+ if (!onboarding || !onboarding.selectedOrganizationId) return;
3024
+ const trimmed = name.trim();
3025
+ if (!onboarding.canCreateProject) {
3026
+ set((prev) => ({
3027
+ onboarding: prev.onboarding ? {
3028
+ ...prev.onboarding,
3029
+ error: "You are not authorized to create projects in this organization."
3030
+ } : prev.onboarding
3031
+ }));
3032
+ return;
3033
+ }
3034
+ if (trimmed.length < 2) {
3035
+ set((prev) => ({
3036
+ onboarding: prev.onboarding ? {
3037
+ ...prev.onboarding,
3038
+ error: "Project name must be at least 2 characters."
3039
+ } : prev.onboarding
3040
+ }));
3041
+ return;
3042
+ }
3043
+ set((prev) => ({
3044
+ loading: true,
3045
+ statusLine: "Creating project...",
3046
+ onboarding: prev.onboarding ? {
3047
+ ...prev.onboarding,
3048
+ error: void 0
3049
+ } : prev.onboarding
3050
+ }));
3051
+ try {
3052
+ const created = await service2.createProject(onboarding.selectedOrganizationId, trimmed);
3053
+ appendLog(`[setup] Created project "${created.name}"`);
3054
+ if (onboarding.mode === "switch-context" || !onboarding.attachCurrentFolder) {
3055
+ service2.persistContext(onboarding.selectedOrganizationId, created.id);
3056
+ appendLog(`[context] switched to ${created.name}`);
3057
+ await refresh();
3058
+ return;
3059
+ }
3060
+ set((prev) => ({
3061
+ loading: true,
3062
+ statusLine: "Registering repository...",
3063
+ onboarding: prev.onboarding ? {
3064
+ ...prev.onboarding,
3065
+ step: "registering",
3066
+ availableAgents: prev.onboarding?.availableAgents ?? [],
3067
+ selectedProjectId: created.id,
3068
+ runLines: [],
3069
+ runStatus: "running",
3070
+ interaction: void 0,
3071
+ error: void 0
3072
+ } : prev.onboarding
3073
+ }));
3074
+ await attachRepositoryFromOnboardingZustand({
3075
+ organizationId: onboarding.selectedOrganizationId,
3076
+ projectId: created.id
3077
+ });
3078
+ await refresh();
3079
+ } catch (error) {
3080
+ const message = error instanceof Error ? error.message : String(error);
3081
+ set((prev) => ({
3082
+ loading: false,
3083
+ statusLine: "Setup error",
3084
+ onboarding: prev.onboarding ? {
3085
+ ...prev.onboarding,
3086
+ error: message
3087
+ } : prev.onboarding
3088
+ }));
3089
+ }
3090
+ }, "createOnboardingProject"),
3091
+ resolveOnboardingInteraction: /* @__PURE__ */ __name((value) => {
3092
+ const resolver = onboardingInteractionResolver;
3093
+ onboardingInteractionResolver = null;
3094
+ set((prev) => ({
3095
+ onboarding: prev.onboarding ? {
3096
+ ...prev.onboarding,
3097
+ interaction: void 0
3098
+ } : prev.onboarding
3099
+ }));
3100
+ if (resolver) resolver(value);
3101
+ }, "resolveOnboardingInteraction"),
3102
+ setOnboardingAttachCurrentFolder: /* @__PURE__ */ __name((attach) => {
3103
+ set((prev) => ({
3104
+ onboarding: prev.onboarding ? prev.onboarding.attachCurrentFolder === attach ? prev.onboarding : {
3105
+ ...prev.onboarding,
3106
+ attachCurrentFolder: attach
3107
+ } : prev.onboarding
3108
+ }));
3109
+ }, "setOnboardingAttachCurrentFolder")
3110
+ })));
3111
+ async function attachRepositoryFromOnboardingZustand(input) {
3112
+ const service2 = getService();
3113
+ const { appendLog } = useSessionStore.getState();
3114
+ const result = await service2.attachOrSyncCurrentRepository(input.organizationId, input.projectId, (line) => {
3115
+ appendLog(`[setup] ${line}`);
3116
+ useSessionStore.setState((prev) => ({
3117
+ statusLine: line.slice(0, 100),
3118
+ onboarding: prev.onboarding ? {
3119
+ ...prev.onboarding,
3120
+ runLines: [
3121
+ ...prev.onboarding.runLines ?? [],
3122
+ line
3123
+ ].slice(-400)
3124
+ } : prev.onboarding
3125
+ }));
3126
+ }, void 0, requestOnboardingInteraction, (event) => {
3127
+ const { upsertToolCall, setActiveThought } = useOnboardingWindow.getState();
3128
+ if (event.event === "tool_call" || event.event === "tool_call_update") {
3129
+ upsertToolCall(event);
3130
+ } else if (event.event === "agent_thought") {
3131
+ setActiveThought(event.text);
3132
+ }
3133
+ });
3134
+ useSessionStore.setState((prev) => ({
3135
+ onboarding: prev.onboarding ? {
3136
+ ...prev.onboarding,
3137
+ runStatus: result.warning ? "error" : "success"
3138
+ } : prev.onboarding
3139
+ }));
3140
+ logOnboardingAttachResult(appendLog, result);
3141
+ }
3142
+ __name(attachRepositoryFromOnboardingZustand, "attachRepositoryFromOnboardingZustand");
3143
+
3144
+ export {
3145
+ __name,
3146
+ appendGlobalStructuredLog,
3147
+ initServiceBridge,
3148
+ getService,
3149
+ getClient,
3150
+ setInitialScreen,
3151
+ useTuiUiStore,
3152
+ resolveNavPolicy,
3153
+ useOnboardingWindow,
3154
+ useProjectDataStore,
3155
+ useExportStore,
3156
+ useBridgeStore,
3157
+ buildOnboardingState,
3158
+ useSessionStore
3159
+ };