fixate-on 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2797 @@
1
+ // @bun
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
12
+ };
13
+
14
+ // src/tui-components.ts
15
+ function formatNumber(n) {
16
+ return n.toLocaleString("en-US");
17
+ }
18
+ function formatRelativeTime(timestamp, now = Date.now()) {
19
+ const diff = now - timestamp;
20
+ if (diff < 60000)
21
+ return "just now";
22
+ const minutes = Math.floor(diff / 60000);
23
+ if (minutes < 60)
24
+ return `${minutes}m ago`;
25
+ const hours = Math.floor(minutes / 60);
26
+ if (hours < 24)
27
+ return `${hours}h ago`;
28
+ const days = Math.floor(hours / 24);
29
+ return `${days}d ago`;
30
+ }
31
+ var PRODUCT_DISPLAY_NAME = "Fixate";
32
+
33
+ // src/accounting.ts
34
+ function chargedTokens(usage) {
35
+ if (!usage)
36
+ return 0;
37
+ return toNonNegativeInteger(usage.input) + toNonNegativeInteger(usage.cacheWrite) + toNonNegativeInteger(usage.output) + toNonNegativeInteger(usage.reasoning);
38
+ }
39
+ function emptyUsage() {
40
+ return {
41
+ input: 0,
42
+ output: 0,
43
+ reasoning: 0,
44
+ cacheRead: 0,
45
+ cacheWrite: 0,
46
+ cost: 0,
47
+ costKnown: false
48
+ };
49
+ }
50
+ function normalizeUsage(value) {
51
+ const source = typeof value === "object" && value !== null ? value : {};
52
+ const usage = emptyUsage();
53
+ for (const field of USAGE_TOKEN_FIELDS) {
54
+ usage[field] = toNonNegativeInteger(source[field]);
55
+ }
56
+ const rawCost = source.cost;
57
+ usage.cost = Number.isFinite(Number(rawCost)) && Number(rawCost) >= 0 ? Number(rawCost) : 0;
58
+ usage.costKnown = source.costKnown === true || usage.cost > 0;
59
+ return usage;
60
+ }
61
+ function normalizeMessageUsage(message) {
62
+ const msg = message;
63
+ const info = msg?.info;
64
+ const tokens = info?.tokens ?? msg?.tokens ?? msg?.usage ?? {};
65
+ const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
66
+ const rawCost = info?.cost ?? msg?.cost ?? tokens.cost;
67
+ return {
68
+ input: toNonNegativeInteger(tokens.input ?? tokens.input_tokens ?? tokens.prompt_tokens),
69
+ output: toNonNegativeInteger(tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens),
70
+ reasoning: toNonNegativeInteger(tokens.reasoning ?? tokens.reasoning_tokens),
71
+ cacheRead: toNonNegativeInteger(cache.read ?? tokens.cacheRead ?? tokens.cache_read),
72
+ cacheWrite: toNonNegativeInteger(cache.write ?? tokens.cacheWrite ?? tokens.cache_write),
73
+ cost: Number.isFinite(Number(rawCost)) && Number(rawCost) >= 0 ? Number(rawCost) : 0,
74
+ costKnown: rawCost != null && Number.isFinite(Number(rawCost)) && Number(rawCost) >= 0
75
+ };
76
+ }
77
+ function addToUsageField(total, field, delta) {
78
+ const next = normalizeUsage(total);
79
+ const current = next[field];
80
+ if (typeof current === "number") {
81
+ next[field] = current + delta;
82
+ }
83
+ return next;
84
+ }
85
+ function addUsageDelta(total, current, previous, isNewStep = false) {
86
+ const next = normalizeUsage(total);
87
+ const cur = normalizeUsage(current);
88
+ const prev = normalizeUsage(previous);
89
+ const costIncreased = prev.cost > 0 && cur.cost > prev.cost;
90
+ const anyTokenFieldDecreased = STEP_DETECTION_FIELDS.some((field) => cur[field] < prev[field]);
91
+ const completedAnotherStep = isNewStep || costIncreased || anyTokenFieldDecreased;
92
+ for (const field of USAGE_TOKEN_FIELDS) {
93
+ next[field] += completedAnotherStep ? cur[field] : Math.max(0, cur[field] - prev[field]);
94
+ }
95
+ next.cost += Math.max(0, cur.cost - prev.cost);
96
+ next.costKnown ||= cur.costKnown;
97
+ return next;
98
+ }
99
+ function totalTokensForMessage(message) {
100
+ const msg = message;
101
+ const info = msg?.info;
102
+ const tokens = info?.tokens ?? msg?.tokens ?? msg?.usage ?? {};
103
+ const reportedTotal = toNonNegativeInteger(tokens.total);
104
+ if (reportedTotal > 0)
105
+ return reportedTotal;
106
+ return toNonNegativeInteger(tokens.input ?? tokens.input_tokens ?? tokens.prompt_tokens) + toNonNegativeInteger(tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens) + toNonNegativeInteger(tokens.reasoning ?? tokens.reasoning_tokens) + cacheTokensForMessage(tokens);
107
+ }
108
+ function outputTokensForMessage(message) {
109
+ const msg = message;
110
+ const info = msg?.info;
111
+ const tokens = info?.tokens ?? msg?.tokens ?? msg?.usage ?? {};
112
+ const outputRaw = tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens;
113
+ const output = toNonNegativeInteger(outputRaw);
114
+ if (outputRaw === undefined && (info?.tokens === undefined || info?.tokens === null) && (msg?.tokens === undefined || msg?.tokens === null) && (msg?.usage === undefined || msg?.usage === null))
115
+ return null;
116
+ return output;
117
+ }
118
+ function cacheTokensForMessage(tokens) {
119
+ const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
120
+ return toNonNegativeInteger(cache.read ?? tokens.cacheRead ?? tokens.cache_read) + toNonNegativeInteger(cache.write ?? tokens.cacheWrite ?? tokens.cache_write);
121
+ }
122
+ function toNonNegativeInteger(value, fallback = 0) {
123
+ if (value === null || value === undefined)
124
+ return fallback;
125
+ const parsed = Number(value);
126
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : fallback;
127
+ }
128
+ var USAGE_TOKEN_FIELDS, STEP_DETECTION_FIELDS;
129
+ var init_accounting = __esm(() => {
130
+ USAGE_TOKEN_FIELDS = [
131
+ "input",
132
+ "output",
133
+ "reasoning",
134
+ "cacheRead",
135
+ "cacheWrite"
136
+ ];
137
+ STEP_DETECTION_FIELDS = [
138
+ "input",
139
+ "output",
140
+ "reasoning",
141
+ "cacheWrite"
142
+ ];
143
+ });
144
+
145
+ // src/tui-analytics.ts
146
+ function computeAnalytics(goal) {
147
+ const charged = chargedTokens(goal.usage);
148
+ const tokenBudget = goal.tokenBudget ?? null;
149
+ const budgetPercentage = tokenBudget !== null && tokenBudget > 0 ? Math.round(charged / tokenBudget * 100) : null;
150
+ const tokensPerTurn = goal.turnCount > 0 ? Math.round(charged / goal.turnCount) : 0;
151
+ const projectedTotalTokens = goal.turnCount > 0 && goal.maxTurns > 0 ? tokensPerTurn * goal.maxTurns : null;
152
+ const turnsRemaining = tokenBudget !== null && tokensPerTurn > 0 ? Math.max(0, Math.floor((tokenBudget - charged) / tokensPerTurn)) : null;
153
+ const costPerTurn = goal.usage.costKnown && goal.turnCount > 0 ? goal.usage.cost / goal.turnCount : 0;
154
+ const projectedTotalCost = goal.usage.costKnown && goal.turnCount > 0 ? costPerTurn * goal.maxTurns : null;
155
+ const elapsedMs = Date.now() - goal.createdAt;
156
+ const burnRate = elapsedMs >= 1000 ? Math.round(charged / (elapsedMs / 1000)) : 0;
157
+ return {
158
+ chargedTokens: charged,
159
+ tokenBudget,
160
+ budgetPercentage,
161
+ tokensPerTurn,
162
+ projectedTotalTokens,
163
+ turnsRemaining,
164
+ costPerTurn,
165
+ projectedTotalCost,
166
+ burnRate
167
+ };
168
+ }
169
+ function formatAnalyticsSummary(analytics) {
170
+ const parts = [];
171
+ parts.push(`Charged: ${formatNumber(analytics.chargedTokens)}`);
172
+ if (analytics.budgetPercentage !== null) {
173
+ parts.push(`Budget: ${analytics.budgetPercentage}%`);
174
+ }
175
+ if (analytics.tokensPerTurn > 0) {
176
+ parts.push(`${formatNumber(analytics.tokensPerTurn)}/turn`);
177
+ }
178
+ if (analytics.turnsRemaining !== null) {
179
+ parts.push(`${analytics.turnsRemaining} turns left`);
180
+ }
181
+ if (analytics.costPerTurn > 0) {
182
+ parts.push(`$${analytics.costPerTurn.toFixed(4)}/turn`);
183
+ }
184
+ if (analytics.burnRate > 0) {
185
+ parts.push(`${formatNumber(analytics.burnRate)} tok/s`);
186
+ }
187
+ return parts.join(" | ");
188
+ }
189
+ function formatBudgetWarning(analytics) {
190
+ if (analytics.budgetPercentage === null)
191
+ return null;
192
+ if (analytics.budgetPercentage < 80)
193
+ return null;
194
+ if (analytics.budgetPercentage >= 100) {
195
+ return `Budget ${analytics.budgetPercentage}% consumed - limit reached`;
196
+ }
197
+ if (analytics.projectedTotalTokens !== null && analytics.tokenBudget !== null && analytics.projectedTotalTokens > analytics.tokenBudget) {
198
+ return `Projected to exceed budget at current rate (${analytics.budgetPercentage}% used, ${analytics.turnsRemaining} turns left)`;
199
+ }
200
+ return `Budget at ${analytics.budgetPercentage}% - approaching limit`;
201
+ }
202
+ var init_tui_analytics = __esm(() => {
203
+ init_accounting();
204
+ });
205
+
206
+ // src/brake-format.ts
207
+ function brakeCeiling(limit) {
208
+ return limit > 0 ? limit : UNLIMITED;
209
+ }
210
+ function brakeCeilingFormatted(limit, format) {
211
+ return limit > 0 ? format(limit) : UNLIMITED;
212
+ }
213
+ var UNLIMITED = "unlimited";
214
+
215
+ // src/status-label.ts
216
+ function isYieldPastPromise(stoppedAt, now, promiseMs = YIELD_PROMISE_MS, updatedAt) {
217
+ const since = stoppedAt && stoppedAt > 0 ? stoppedAt : updatedAt;
218
+ if (!since || since <= 0)
219
+ return false;
220
+ if (since > now)
221
+ return true;
222
+ return now - since >= promiseMs;
223
+ }
224
+ function isSelfResolvingStop(status, stopReason, stoppedAt, now = Date.now(), updatedAt) {
225
+ if (status !== "paused")
226
+ return false;
227
+ if (!SELF_RESOLVING_STOP_REASONS.has(stopReason ?? ""))
228
+ return false;
229
+ if (stopReason === USER_INTERVENTION_STOP_REASON && isYieldPastPromise(stoppedAt, now, YIELD_PROMISE_MS, updatedAt))
230
+ return false;
231
+ return true;
232
+ }
233
+ function isYieldingPause(status, stopReason) {
234
+ return status === "paused" && stopReason === USER_INTERVENTION_STOP_REASON;
235
+ }
236
+ function isLiveYield(status, stopReason, stoppedAt, now, updatedAt) {
237
+ if (!isYieldingPause(status, stopReason))
238
+ return false;
239
+ return !isYieldPastPromise(stoppedAt, now ?? Date.now(), YIELD_PROMISE_MS, updatedAt);
240
+ }
241
+ function statusTag(status, stopReason, stoppedAt, now, updatedAt) {
242
+ return isLiveYield(status, stopReason, stoppedAt, now, updatedAt) ? "paused: yielding" : status;
243
+ }
244
+ function stopReasonLabel(stopReason, status, stoppedAt, now, updatedAt) {
245
+ if (stopReason !== USER_INTERVENTION_STOP_REASON)
246
+ return stopReason;
247
+ if (status !== undefined && !isLiveYield(status, stopReason, stoppedAt, now, updatedAt)) {
248
+ return "yielding to your message; did not re-arm";
249
+ }
250
+ return "yielding to your message; re-arms automatically";
251
+ }
252
+ var USER_INTERVENTION_STOP_REASON = "user intervention", SELF_RESOLVING_STOP_REASONS, YIELD_PROMISE_MS;
253
+ var init_status_label = __esm(() => {
254
+ SELF_RESOLVING_STOP_REASONS = new Set([
255
+ "recovery",
256
+ "user intervention",
257
+ "queued"
258
+ ]);
259
+ YIELD_PROMISE_MS = 15 * 60000;
260
+ });
261
+
262
+ // src/tui-views.ts
263
+ function wrapText(text, width, continuationIndent = "") {
264
+ const words = text.split(/\s+/).filter(Boolean);
265
+ if (words.length === 0)
266
+ return [text];
267
+ const lines = [];
268
+ let current = "";
269
+ for (const word of words) {
270
+ const candidate = current ? `${current} ${word}` : word;
271
+ if (current && candidate.length > width) {
272
+ lines.push(current);
273
+ current = continuationIndent + word;
274
+ } else {
275
+ current = candidate;
276
+ }
277
+ }
278
+ if (current)
279
+ lines.push(current);
280
+ return lines;
281
+ }
282
+ function isForeignGoal(goal, activeSessionID) {
283
+ return activeSessionID !== null && goal.sessionID !== activeSessionID;
284
+ }
285
+ function foreignSessionLabel(goal) {
286
+ return goal.sessionID;
287
+ }
288
+ function fallbackNotice(goals, activeSessionID) {
289
+ if (activeSessionID === null)
290
+ return null;
291
+ const foreign = goals.filter((g) => isForeignGoal(g, activeSessionID));
292
+ if (foreign.length === 0)
293
+ return null;
294
+ const mine = goals.length - foreign.length;
295
+ return mine === 0 ? `This session has no goals. Showing ${foreign.length} from other sessions.` : `Showing ${foreign.length} from other sessions alongside this session's ${mine}.`;
296
+ }
297
+ function goalListRow(goal, index, activeSessionID) {
298
+ const foreign = isForeignGoal(goal, activeSessionID);
299
+ return {
300
+ title: `${index + 1}. [${statusTag(goal.status, goal.stopReason, goal.stoppedAt, undefined, goal.updatedAt)}] ${goal.condition.substring(0, 60)}`,
301
+ description: (foreign ? `Another session (${foreignSessionLabel(goal)}) | ` : "") + `Tokens: ${goal.totalTokens}/${brakeCeiling(goal.maxTokens)} Turns: ${goal.turnCount}/${brakeCeiling(goal.maxTurns)}`
302
+ };
303
+ }
304
+ function dashboardGoalActions(store, targetSessionID, send) {
305
+ const withTarget = (verb) => () => {
306
+ const id = resolveFocusedGoalId(store, targetSessionID());
307
+ if (id)
308
+ send(`${verb} ${id}`);
309
+ };
310
+ return {
311
+ onPause: withTarget("pause"),
312
+ onResume: withTarget("resume"),
313
+ onClear: withTarget("clear")
314
+ };
315
+ }
316
+ function dashboardFooterText(targetGoalId, dashboardChord, pauseChord, resumeChord, clearChord, escLabel) {
317
+ const nav = `${dashboardChord} dashboard | ${escLabel} home`;
318
+ if (!targetGoalId)
319
+ return nav;
320
+ return `${pauseChord} pause | ${resumeChord} resume | ${clearChord} clear | ${nav}`;
321
+ }
322
+ function resolveFocusedGoalId(store, sessionID) {
323
+ if (sessionID === null)
324
+ return null;
325
+ const focused = store.getFocused(sessionID);
326
+ if (focused)
327
+ return focused.goalId;
328
+ const mine = store.getAllSnapshots().filter((g) => !isForeignGoal(g, sessionID));
329
+ return mine.length > 0 ? mine[mine.length - 1].goalId : null;
330
+ }
331
+ function goalCardLines(goal, activeSessionID) {
332
+ const lines = [];
333
+ lines.push({ text: `Objective: ${goal.condition}` });
334
+ lines.push({ text: ` Status: ${goal.status}` });
335
+ if (isForeignGoal(goal, activeSessionID)) {
336
+ lines.push({
337
+ subdued: true,
338
+ text: ` Session: ${foreignSessionLabel(goal)} (another session)`
339
+ });
340
+ }
341
+ if (goal.stopReason) {
342
+ lines.push({
343
+ subdued: true,
344
+ text: ` Stop: ${stopReasonLabel(goal.stopReason, goal.status, goal.stoppedAt, undefined, goal.updatedAt)}`
345
+ });
346
+ }
347
+ lines.push({ text: ` ${tokenGauge(goal.totalTokens, goal.maxTokens)}` });
348
+ lines.push({
349
+ text: ` Turns: ${goal.turnCount}/${brakeCeiling(goal.maxTurns)}`
350
+ });
351
+ return lines;
352
+ }
353
+ function tokenGauge(used, max) {
354
+ const pct = max > 0 ? Math.round(used / max * 100) : 0;
355
+ const compact = (n) => n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
356
+ return `Tokens: ${pct}% ${compact(used)} / ${brakeCeilingFormatted(max, compact)}`;
357
+ }
358
+ function formatGoalStatusDashboard(goals, activeSessionID = null) {
359
+ if (goals.length === 0) {
360
+ return [
361
+ {
362
+ title: PRODUCT_DISPLAY_NAME,
363
+ text: "No active goals. Use /goal <condition> to set one."
364
+ }
365
+ ];
366
+ }
367
+ const sections = [];
368
+ const notice = fallbackNotice(goals, activeSessionID);
369
+ if (notice) {
370
+ sections.push({ title: "Sessions shown", text: notice });
371
+ }
372
+ for (const goal of goals) {
373
+ const lines = [];
374
+ lines.push(...wrapText(` Objective: ${goal.condition}`, 96, " "));
375
+ lines.push(` Status: ${goal.status}`);
376
+ if (isForeignGoal(goal, activeSessionID)) {
377
+ lines.push(` Session: ${foreignSessionLabel(goal)} (another session)`);
378
+ }
379
+ if (goal.stopReason) {
380
+ lines.push(` Stop: ${stopReasonLabel(goal.stopReason, goal.status, goal.stoppedAt, undefined, goal.updatedAt)}`);
381
+ }
382
+ if (goal.blockedReason) {
383
+ lines.push(` Blocked: ${goal.blockedReason}`);
384
+ }
385
+ lines.push("");
386
+ lines.push(formatTokenGauge(goal.totalTokens, goal.maxTokens));
387
+ lines.push(` Turns: ${goal.turnCount} / ${brakeCeiling(goal.maxTurns)}`);
388
+ if (goal.usage.costKnown && goal.usage.cost > 0) {
389
+ lines.push(` Cost: $${goal.usage.cost.toFixed(4)}`);
390
+ }
391
+ const analytics = computeAnalytics(goal);
392
+ const analyticsLine = formatAnalyticsSummary(analytics);
393
+ if (analyticsLine) {
394
+ lines.push(` Analytics: ${analyticsLine}`);
395
+ }
396
+ const warning = formatBudgetWarning(analytics);
397
+ if (warning) {
398
+ lines.push(` ${warning}`);
399
+ }
400
+ if (goal.lastCheckpoint) {
401
+ lines.push("");
402
+ lines.push(` Checkpoint: ${goal.lastCheckpoint.summary}`);
403
+ lines.push(` ${formatRelativeTime(goal.lastCheckpoint.timestamp)}`);
404
+ }
405
+ if (goal.history.length > 0) {
406
+ lines.push("");
407
+ lines.push(formatHistoryList(goal.history));
408
+ }
409
+ sections.push({
410
+ title: `Goal: ${goal.goalId.substring(0, 8)}`,
411
+ text: lines.join(`
412
+ `)
413
+ });
414
+ }
415
+ return sections;
416
+ }
417
+ function formatTokenGauge(used, max) {
418
+ const percentage = max > 0 ? used / max * 100 : 0;
419
+ const maxLabel = max > 0 ? formatNumber(max) : "unlimited";
420
+ return ` Tokens: ${Math.round(percentage)}% ${formatNumber(used)} / ${maxLabel}`;
421
+ }
422
+ function isSignalHistoryEntry(entry) {
423
+ if (entry.type === "tracking")
424
+ return false;
425
+ if (entry.type !== "mutation")
426
+ return true;
427
+ return MUTATION_SIGNAL_PREFIXES.some((prefix) => entry.detail.startsWith(prefix));
428
+ }
429
+ function formatHistoryList(history) {
430
+ const signals = history.filter(isSignalHistoryEntry);
431
+ if (signals.length === 0) {
432
+ return " History: (no lifecycle events)";
433
+ }
434
+ const lines = [" History:"];
435
+ for (const entry of signals) {
436
+ const time = formatRelativeTime(entry.timestamp);
437
+ lines.push(` [${entry.type}] ${entry.detail} (${time})`);
438
+ }
439
+ return lines.join(`
440
+ `);
441
+ }
442
+ var MUTATION_SIGNAL_PREFIXES;
443
+ var init_tui_views = __esm(() => {
444
+ init_tui_analytics();
445
+ init_status_label();
446
+ MUTATION_SIGNAL_PREFIXES = [
447
+ "User ",
448
+ "Human ",
449
+ "Accepted proposal",
450
+ "Rejected proposal",
451
+ "Proposed term changes",
452
+ "Recorded claim",
453
+ "Loaded from persisted state",
454
+ "Paused because",
455
+ "Backgrounded",
456
+ "Queued goal",
457
+ "Started an ordered sequence",
458
+ "Pressure rung"
459
+ ];
460
+ });
461
+
462
+ // src/tui-state.ts
463
+ var GOAL_TUI_EVENT_TITLE = "fixate-on";
464
+ var VALID_GOAL_STATUSES = new Set([
465
+ "active",
466
+ "paused",
467
+ "blocked",
468
+ "budgetLimited",
469
+ "finalizing",
470
+ "complete"
471
+ ]);
472
+ var memoHistoryRef = null;
473
+ var memoHistoryLen = -1;
474
+ var memoHistoryFrozen = [];
475
+ function frozenHistory(history) {
476
+ if (history === memoHistoryRef && history.length === memoHistoryLen) {
477
+ return memoHistoryFrozen;
478
+ }
479
+ memoHistoryRef = history;
480
+ memoHistoryLen = history.length;
481
+ memoHistoryFrozen = deepFreeze(history.map((h) => ({
482
+ type: h.type,
483
+ detail: h.detail,
484
+ timestamp: h.timestamp
485
+ })));
486
+ return memoHistoryFrozen;
487
+ }
488
+ function serializeGoalForTui(state) {
489
+ const snapshot = {
490
+ goalId: state.goalId,
491
+ sessionID: state.sessionID,
492
+ condition: state.condition,
493
+ artifactPointers: state.artifactPointers ? [...state.artifactPointers] : [],
494
+ pendingProposal: state.pendingProposal ? { ...state.pendingProposal } : null,
495
+ claims: state.claims ? state.claims.map((c) => ({ ...c })) : [],
496
+ lastClaim: state.lastClaim ? { ...state.lastClaim } : null,
497
+ status: state.status,
498
+ revision: state.revision,
499
+ turnCount: state.turnCount,
500
+ totalTokens: state.totalTokens,
501
+ maxTokens: state.maxTokens,
502
+ maxTurns: state.maxTurns,
503
+ tokenBudget: state.tokenBudget,
504
+ usage: {
505
+ input: state.usage.input,
506
+ output: state.usage.output,
507
+ reasoning: state.usage.reasoning,
508
+ cacheRead: state.usage.cacheRead,
509
+ cacheWrite: state.usage.cacheWrite,
510
+ cost: state.usage.cost,
511
+ costKnown: state.usage.costKnown
512
+ },
513
+ stopReason: state.stopReason,
514
+ blockedReason: state.blockedReason,
515
+ pausedAt: state.pausedAt,
516
+ stoppedAt: state.stoppedAt,
517
+ createdAt: state.createdAt,
518
+ updatedAt: state.updatedAt,
519
+ finishedAt: state.finishedAt,
520
+ lastCheckpoint: state.lastCheckpoint ? {
521
+ summary: state.lastCheckpoint.summary,
522
+ timestamp: state.lastCheckpoint.timestamp
523
+ } : null,
524
+ history: frozenHistory(state.history)
525
+ };
526
+ return deepFreeze(snapshot);
527
+ }
528
+ function parseTuiSyncEvent(raw) {
529
+ if (!raw || typeof raw !== "string")
530
+ return null;
531
+ let parsed;
532
+ try {
533
+ parsed = JSON.parse(raw);
534
+ } catch {
535
+ return null;
536
+ }
537
+ return validateTuiEvent(parsed);
538
+ }
539
+ function validateTuiEvent(value) {
540
+ if (!value || typeof value !== "object")
541
+ return null;
542
+ const obj = value;
543
+ if (obj.title === GOAL_TUI_EVENT_TITLE && obj.payload && typeof obj.payload === "object") {
544
+ return validateTuiEvent(obj.payload);
545
+ }
546
+ const kind = obj.kind;
547
+ if (kind !== "create" && kind !== "transition" && kind !== "usage" && kind !== "remove") {
548
+ return null;
549
+ }
550
+ const sessionID = obj.sessionID;
551
+ if (typeof sessionID !== "string" || sessionID.length === 0)
552
+ return null;
553
+ const timestamp = obj.timestamp;
554
+ if (typeof timestamp !== "number" || !Number.isFinite(timestamp))
555
+ return null;
556
+ if (kind === "remove") {
557
+ const goalId = obj.goalId;
558
+ if (typeof goalId !== "string" || goalId.length === 0)
559
+ return null;
560
+ return { kind, sessionID, timestamp, goalId };
561
+ }
562
+ const snapshot = validateSnapshot(obj.snapshot);
563
+ if (!snapshot)
564
+ return null;
565
+ if (snapshot.sessionID !== sessionID)
566
+ return null;
567
+ if (kind === "transition") {
568
+ const transition = validateTransition(obj.transition);
569
+ if (!transition)
570
+ return null;
571
+ return { kind, sessionID, timestamp, snapshot, transition };
572
+ }
573
+ return { kind, sessionID, timestamp, snapshot };
574
+ }
575
+ function validateSnapshot(value) {
576
+ if (!value || typeof value !== "object")
577
+ return null;
578
+ const s = value;
579
+ if (typeof s.goalId !== "string" || typeof s.sessionID !== "string" || typeof s.condition !== "string" || typeof s.status !== "string" || !VALID_GOAL_STATUSES.has(s.status) || typeof s.revision !== "number" || typeof s.turnCount !== "number" || typeof s.totalTokens !== "number" || typeof s.maxTokens !== "number" || typeof s.maxTurns !== "number" || s.tokenBudget !== null && typeof s.tokenBudget !== "number" || typeof s.stopReason !== "string" || typeof s.pausedAt !== "number" || !Number.isFinite(s.pausedAt) || s.pausedAt < 0 || typeof s.stoppedAt !== "number" || !Number.isFinite(s.stoppedAt) || s.stoppedAt < 0 || typeof s.blockedReason !== "string" || typeof s.createdAt !== "number" || typeof s.updatedAt !== "number") {
580
+ return null;
581
+ }
582
+ if (s.finishedAt !== null && typeof s.finishedAt !== "number")
583
+ return null;
584
+ const usage = validateUsage(s.usage);
585
+ if (!usage)
586
+ return null;
587
+ const history = validateHistory(s.history);
588
+ if (history === null)
589
+ return null;
590
+ const checkpoint = validateCheckpoint(s.lastCheckpoint);
591
+ if (checkpoint === INVALID_CHECKPOINT)
592
+ return null;
593
+ const snapshot = {
594
+ goalId: s.goalId,
595
+ sessionID: s.sessionID,
596
+ condition: s.condition,
597
+ status: s.status,
598
+ revision: s.revision,
599
+ turnCount: s.turnCount,
600
+ totalTokens: s.totalTokens,
601
+ maxTokens: s.maxTokens,
602
+ maxTurns: s.maxTurns,
603
+ tokenBudget: s.tokenBudget === null ? null : s.tokenBudget,
604
+ usage,
605
+ stopReason: s.stopReason,
606
+ blockedReason: s.blockedReason,
607
+ pausedAt: s.pausedAt,
608
+ stoppedAt: s.stoppedAt,
609
+ createdAt: s.createdAt,
610
+ updatedAt: s.updatedAt,
611
+ finishedAt: s.finishedAt === null ? null : s.finishedAt,
612
+ lastCheckpoint: checkpoint,
613
+ history
614
+ };
615
+ return deepFreeze(snapshot);
616
+ }
617
+ function validateUsage(value) {
618
+ if (!value || typeof value !== "object")
619
+ return null;
620
+ const u = value;
621
+ if (typeof u.input !== "number" || typeof u.output !== "number" || typeof u.reasoning !== "number" || typeof u.cacheRead !== "number" || typeof u.cacheWrite !== "number" || typeof u.cost !== "number" || typeof u.costKnown !== "boolean") {
622
+ return null;
623
+ }
624
+ return {
625
+ input: u.input,
626
+ output: u.output,
627
+ reasoning: u.reasoning,
628
+ cacheRead: u.cacheRead,
629
+ cacheWrite: u.cacheWrite,
630
+ cost: u.cost,
631
+ costKnown: u.costKnown
632
+ };
633
+ }
634
+ function validateHistory(value) {
635
+ if (!Array.isArray(value))
636
+ return null;
637
+ const result = [];
638
+ for (const entry of value) {
639
+ if (!entry || typeof entry !== "object")
640
+ return null;
641
+ const e = entry;
642
+ if (typeof e.type !== "string" || typeof e.detail !== "string" || typeof e.timestamp !== "number") {
643
+ return null;
644
+ }
645
+ result.push({ type: e.type, detail: e.detail, timestamp: e.timestamp });
646
+ }
647
+ return result;
648
+ }
649
+ var INVALID_CHECKPOINT = Object.freeze({ summary: "", timestamp: -1 });
650
+ function validateCheckpoint(value) {
651
+ if (value === null)
652
+ return null;
653
+ if (!value || typeof value !== "object")
654
+ return INVALID_CHECKPOINT;
655
+ const c = value;
656
+ if (typeof c.summary !== "string" || typeof c.timestamp !== "number")
657
+ return INVALID_CHECKPOINT;
658
+ return { summary: c.summary, timestamp: c.timestamp };
659
+ }
660
+ function validateTransition(value) {
661
+ if (!value || typeof value !== "object")
662
+ return null;
663
+ const t = value;
664
+ if (typeof t.source !== "string" || typeof t.from !== "string" || typeof t.to !== "string" || typeof t.detail !== "string") {
665
+ return null;
666
+ }
667
+ return {
668
+ source: t.source,
669
+ from: t.from,
670
+ to: t.to,
671
+ detail: t.detail
672
+ };
673
+ }
674
+ function createSessionStore() {
675
+ return { goals: new Map, focusedId: null, order: [] };
676
+ }
677
+ function createTuiStateStore() {
678
+ const sessions = new Map;
679
+ const subscribers = new Set;
680
+ function getOrCreateSession(sessionID) {
681
+ let s = sessions.get(sessionID);
682
+ if (!s) {
683
+ s = createSessionStore();
684
+ sessions.set(sessionID, s);
685
+ }
686
+ return s;
687
+ }
688
+ function notify(event) {
689
+ for (const sub of subscribers) {
690
+ try {
691
+ sub(event);
692
+ } catch {}
693
+ }
694
+ }
695
+ function applyEvent(event) {
696
+ if (event.kind === "remove") {
697
+ const session = sessions.get(event.sessionID);
698
+ if (session && event.goalId) {
699
+ session.goals.delete(event.goalId);
700
+ session.order = session.order.filter((id) => id !== event.goalId);
701
+ if (session.focusedId === event.goalId) {
702
+ session.focusedId = session.order[session.order.length - 1] ?? null;
703
+ }
704
+ }
705
+ notify(event);
706
+ return;
707
+ }
708
+ if (!event.snapshot)
709
+ return;
710
+ const snapshot = deepFreeze(event.snapshot);
711
+ const session = getOrCreateSession(event.sessionID);
712
+ const existing = session.goals.get(snapshot.goalId);
713
+ if (existing && snapshot.revision < existing.revision) {
714
+ return;
715
+ }
716
+ if (!existing) {
717
+ session.order.push(snapshot.goalId);
718
+ }
719
+ session.goals.set(snapshot.goalId, snapshot);
720
+ session.focusedId = snapshot.goalId;
721
+ notify(event);
722
+ }
723
+ function getSnapshots(sessionID) {
724
+ const session = sessions.get(sessionID);
725
+ if (!session)
726
+ return [];
727
+ return session.order.map((id) => session.goals.get(id)).filter((s) => !!s);
728
+ }
729
+ function getAllSnapshots() {
730
+ const all = [];
731
+ for (const session of sessions.values()) {
732
+ for (const id of session.order) {
733
+ const snap = session.goals.get(id);
734
+ if (snap)
735
+ all.push(snap);
736
+ }
737
+ }
738
+ return all;
739
+ }
740
+ function getSnapshot(sessionID, goalId) {
741
+ const session = sessions.get(sessionID);
742
+ if (!session)
743
+ return;
744
+ return session.goals.get(goalId);
745
+ }
746
+ function getFocused(sessionID) {
747
+ const session = sessions.get(sessionID);
748
+ if (!session || !session.focusedId)
749
+ return;
750
+ return session.goals.get(session.focusedId);
751
+ }
752
+ function subscribe(fn) {
753
+ subscribers.add(fn);
754
+ return () => subscribers.delete(fn);
755
+ }
756
+ function clear() {
757
+ sessions.clear();
758
+ subscribers.clear();
759
+ }
760
+ return {
761
+ applyEvent,
762
+ getSnapshots,
763
+ getAllSnapshots,
764
+ getSnapshot,
765
+ getFocused,
766
+ subscribe,
767
+ clear
768
+ };
769
+ }
770
+ function createGoalBroadcaster(config) {
771
+ const { publish, onDeliveryFailure } = config;
772
+ async function emit(snapshot, kind, transition) {
773
+ const event = {
774
+ kind,
775
+ sessionID: snapshot.sessionID,
776
+ timestamp: Date.now(),
777
+ snapshot: serializeGoalForTui(snapshot),
778
+ ...transition ? { transition, previousStatus: transition.from } : {}
779
+ };
780
+ try {
781
+ await publish(snapshot.sessionID, event);
782
+ } catch (error) {
783
+ try {
784
+ onDeliveryFailure?.({
785
+ kind,
786
+ sessionID: snapshot.sessionID,
787
+ goalId: snapshot.goalId,
788
+ error
789
+ });
790
+ } catch {}
791
+ }
792
+ }
793
+ return {
794
+ onCommit: async (snapshot, transition) => {
795
+ await emit(snapshot, "transition", transition);
796
+ },
797
+ emitCreate: async (snapshot) => {
798
+ await emit(snapshot, "create");
799
+ },
800
+ emitRemove: async (sessionID, goalId) => {
801
+ const event = {
802
+ kind: "remove",
803
+ sessionID,
804
+ goalId,
805
+ timestamp: Date.now()
806
+ };
807
+ try {
808
+ await publish(sessionID, event);
809
+ } catch (error) {
810
+ try {
811
+ onDeliveryFailure?.({ kind: "remove", sessionID, goalId, error });
812
+ } catch {}
813
+ }
814
+ },
815
+ emitUsage: async (snapshot) => {
816
+ await emit(snapshot, "usage");
817
+ }
818
+ };
819
+ }
820
+ var BUFFER_MAX_EVENTS = 64;
821
+ var GOAL_TUI_METADATA_KEY = "fixate-on";
822
+ function createBufferingTransport() {
823
+ const buffers = new Map;
824
+ function get(sessionID) {
825
+ let buf = buffers.get(sessionID);
826
+ if (!buf) {
827
+ buf = [];
828
+ buffers.set(sessionID, buf);
829
+ }
830
+ return buf;
831
+ }
832
+ return {
833
+ publish: (_sessionID, event) => {
834
+ const sessionID = event.sessionID;
835
+ if (!sessionID)
836
+ return;
837
+ const buf = get(sessionID);
838
+ buf.push(event);
839
+ if (buf.length > BUFFER_MAX_EVENTS) {
840
+ buf.splice(0, buf.length - BUFFER_MAX_EVENTS);
841
+ }
842
+ },
843
+ drain: (sessionID) => {
844
+ const buf = buffers.get(sessionID);
845
+ if (!buf || buf.length === 0)
846
+ return [];
847
+ return buf.splice(0, buf.length);
848
+ },
849
+ peek: (sessionID) => {
850
+ const buf = buffers.get(sessionID);
851
+ return buf ? buf.slice() : [];
852
+ },
853
+ clear: () => {
854
+ buffers.clear();
855
+ }
856
+ };
857
+ }
858
+ function encodeGoalToolMetadata(events) {
859
+ if (!events || events.length === 0)
860
+ return;
861
+ return { [GOAL_TUI_METADATA_KEY]: { events } };
862
+ }
863
+ function decodeGoalToolMetadata(metadata) {
864
+ if (!metadata || typeof metadata !== "object")
865
+ return null;
866
+ const envelope = metadata[GOAL_TUI_METADATA_KEY];
867
+ if (!envelope || typeof envelope !== "object")
868
+ return null;
869
+ const events = envelope.events;
870
+ if (!Array.isArray(events))
871
+ return null;
872
+ const valid = [];
873
+ for (const raw of events) {
874
+ const event = validateTuiEvent(raw);
875
+ if (event)
876
+ valid.push(event);
877
+ }
878
+ return valid.length > 0 ? valid : null;
879
+ }
880
+ function deepFreeze(value) {
881
+ if (value === null || typeof value !== "object")
882
+ return value;
883
+ if (Object.isFrozen(value))
884
+ return value;
885
+ if (Array.isArray(value)) {
886
+ for (const item of value)
887
+ deepFreeze(item);
888
+ return Object.freeze(value);
889
+ }
890
+ for (const key of Object.keys(value)) {
891
+ deepFreeze(value[key]);
892
+ }
893
+ return Object.freeze(value);
894
+ }
895
+ // src/tui-disk-state.ts
896
+ import { resolve as resolve2 } from "path";
897
+
898
+ // src/fs-portable.ts
899
+ import {
900
+ lstat as fsLstat,
901
+ mkdir as fsMkdir,
902
+ rename as fsRename,
903
+ unlink as fsUnlink
904
+ } from "fs/promises";
905
+ var MAX_STATE_FILE_BYTES = 16 * 1024 * 1024;
906
+ async function portableReadBounded(filePath, maxBytes = MAX_STATE_FILE_BYTES) {
907
+ const { open } = await import("fs/promises");
908
+ const info = await fsLstat(filePath).catch(() => null);
909
+ if (!info || info.isSymbolicLink() || !info.isFile()) {
910
+ throw new Error(`refusing to read non-regular file: ${filePath}`);
911
+ }
912
+ const handle = await open(filePath, "r");
913
+ try {
914
+ const opened = await handle.stat();
915
+ const buf = Buffer.alloc(Math.min(opened.size, maxBytes));
916
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
917
+ return {
918
+ text: buf.subarray(0, bytesRead).toString("utf8"),
919
+ truncated: opened.size > maxBytes
920
+ };
921
+ } finally {
922
+ await handle.close();
923
+ }
924
+ }
925
+ async function portableWriteFile(filePath, data, mode = 384) {
926
+ const { dirname } = await import("path");
927
+ const { open } = await import("fs/promises");
928
+ const { randomUUID } = await import("crypto");
929
+ const { constants } = await import("fs");
930
+ await fsMkdir(dirname(filePath), { recursive: true, mode: 448 });
931
+ const temporaryPath = `${filePath}.tmp-${randomUUID()}`;
932
+ let installed = false;
933
+ let ownsTemporary = false;
934
+ let backupPath = null;
935
+ try {
936
+ const handle = await open(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
937
+ ownsTemporary = true;
938
+ try {
939
+ await handle.writeFile(data, "utf8");
940
+ await handle.chmod(mode);
941
+ await handle.sync();
942
+ } finally {
943
+ await handle.close();
944
+ }
945
+ const existing = await fsLstat(filePath).catch(() => {
946
+ return;
947
+ });
948
+ if (existing?.isSymbolicLink()) {
949
+ throw new Error(`refusing to replace symlinked state file: ${filePath}`);
950
+ }
951
+ if (existing && !existing.isFile()) {
952
+ throw new Error(`refusing to replace non-regular state file: ${filePath}`);
953
+ }
954
+ try {
955
+ await fsRename(temporaryPath, filePath);
956
+ installed = true;
957
+ } catch (renameError) {
958
+ if (!existing)
959
+ throw renameError;
960
+ backupPath = `${filePath}.bak-${randomUUID()}`;
961
+ await fsRename(filePath, backupPath);
962
+ try {
963
+ await fsRename(temporaryPath, filePath);
964
+ installed = true;
965
+ } catch (fallbackError) {
966
+ try {
967
+ await fsRename(backupPath, filePath);
968
+ } catch (restoreError) {
969
+ throw new Error(`snapshot replacement failed and prior snapshot restore failed; prior snapshot preserved at ${backupPath}: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, { cause: fallbackError });
970
+ }
971
+ throw fallbackError;
972
+ }
973
+ await fsUnlink(backupPath).catch(() => {});
974
+ }
975
+ try {
976
+ const directory = await open(dirname(filePath), constants.O_RDONLY);
977
+ try {
978
+ await directory.sync();
979
+ } finally {
980
+ await directory.close();
981
+ }
982
+ } catch {}
983
+ installed = true;
984
+ } finally {
985
+ if (ownsTemporary && !installed) {
986
+ await fsUnlink(temporaryPath).catch(() => {});
987
+ }
988
+ }
989
+ }
990
+ async function portableFileExists(filePath) {
991
+ try {
992
+ const info = await fsLstat(filePath);
993
+ return info.isFile();
994
+ } catch {
995
+ return false;
996
+ }
997
+ }
998
+ async function portableFileSize(filePath) {
999
+ try {
1000
+ const info = await fsLstat(filePath);
1001
+ return info.isFile() ? info.size : -1;
1002
+ } catch {
1003
+ return -1;
1004
+ }
1005
+ }
1006
+
1007
+ // src/session-paths.ts
1008
+ import { lstatSync } from "fs";
1009
+ import { dirname, join, relative, resolve, sep } from "path";
1010
+ var SESSIONS_DIRNAME = "sessions";
1011
+ var DEFAULT_STATE_ROOT = ".opencode/goals";
1012
+ var STATE_FILENAME = "state.json";
1013
+ var LEDGER_SUFFIX = ".ledger.jsonl";
1014
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
1015
+ function assertSafeSessionID(sessionID) {
1016
+ if (typeof sessionID !== "string" || !SESSION_ID_PATTERN.test(sessionID)) {
1017
+ const shown = typeof sessionID === "string" ? sessionID.slice(0, 64) : String(sessionID);
1018
+ throw new Error(`refusing to use ${JSON.stringify(shown)} as a session directory name: a session id must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'`);
1019
+ }
1020
+ return sessionID;
1021
+ }
1022
+ function sessionStatePaths(stateRoot, sessionID) {
1023
+ const sessionDir = join(stateRoot, SESSIONS_DIRNAME, assertSafeSessionID(sessionID));
1024
+ const statePath = join(sessionDir, STATE_FILENAME);
1025
+ return { sessionDir, statePath, ledgerPath: `${statePath}${LEDGER_SUFFIX}` };
1026
+ }
1027
+ function assertContainedInStateRoot(stateRoot, target) {
1028
+ const root = resolve(stateRoot);
1029
+ const rel = relative(root, target);
1030
+ if (rel.startsWith("..")) {
1031
+ throw new Error(`goal persistence path escapes the state root and is refused: ${target}`);
1032
+ }
1033
+ const rootParent = dirname(root);
1034
+ if (root !== rootParent) {
1035
+ let rootIsSymlink = false;
1036
+ try {
1037
+ rootIsSymlink = lstatSync(root).isSymbolicLink();
1038
+ } catch {}
1039
+ if (rootIsSymlink) {
1040
+ throw new Error(`refusing goal persistence: the state root itself is a symlink (${root}), so goal state would ` + "be written outside it. Point `stateRoot` at a real directory.");
1041
+ }
1042
+ }
1043
+ if (rel === "")
1044
+ return;
1045
+ let cursor = root;
1046
+ for (const segment of rel.split(sep).filter((s) => s.length > 0)) {
1047
+ cursor = join(cursor, segment);
1048
+ let info;
1049
+ try {
1050
+ info = lstatSync(cursor);
1051
+ } catch {
1052
+ break;
1053
+ }
1054
+ if (info.isSymbolicLink()) {
1055
+ throw new Error(`refusing goal persistence through a symlinked path segment: ${cursor}`);
1056
+ }
1057
+ }
1058
+ }
1059
+ async function ensureSessionDir(stateRoot, sessionID) {
1060
+ const { mkdir } = await import("fs/promises");
1061
+ const { sessionDir } = sessionStatePaths(stateRoot, sessionID);
1062
+ assertContainedInStateRoot(stateRoot, sessionDir);
1063
+ await mkdir(sessionDir, { recursive: true, mode: 448 });
1064
+ return sessionDir;
1065
+ }
1066
+ async function listSessionIDs(stateRoot) {
1067
+ let entries;
1068
+ try {
1069
+ const { readdir } = await import("fs/promises");
1070
+ entries = await readdir(join(stateRoot, SESSIONS_DIRNAME), {
1071
+ withFileTypes: true
1072
+ });
1073
+ } catch {
1074
+ return [];
1075
+ }
1076
+ return entries.filter((entry) => entry.isDirectory() && SESSION_ID_PATTERN.test(entry.name)).map((entry) => entry.name).sort();
1077
+ }
1078
+
1079
+ // src/tui-disk-state.ts
1080
+ function resolveStateRoot(directory, stateRoot) {
1081
+ const configured = stateRoot ?? process.env.FIXATE_ON_STATE_ROOT;
1082
+ return resolve2(directory ? resolve2(directory) : process.cwd(), configured ?? DEFAULT_STATE_ROOT);
1083
+ }
1084
+ function sessionIDFromStatePath(path) {
1085
+ const parts = path.split(/[\\/]/);
1086
+ const idx = parts.lastIndexOf(SESSIONS_DIRNAME);
1087
+ if (idx < 0 || idx + 1 >= parts.length - 1)
1088
+ return;
1089
+ return parts[idx + 1];
1090
+ }
1091
+ async function discoverStateFiles(directory, explicitPath, stateRoot) {
1092
+ const { readdir, stat } = await import("fs/promises");
1093
+ const { join } = await import("path");
1094
+ if (explicitPath) {
1095
+ const direct = resolve2(explicitPath);
1096
+ try {
1097
+ return (await stat(direct)).isFile() ? [direct] : [];
1098
+ } catch {
1099
+ return [];
1100
+ }
1101
+ }
1102
+ const sessionsRoot = join(resolveStateRoot(directory, stateRoot), SESSIONS_DIRNAME);
1103
+ try {
1104
+ const entries = await readdir(sessionsRoot, { withFileTypes: true });
1105
+ return entries.filter((entry) => entry.isDirectory() && SESSION_ID_PATTERN.test(entry.name)).map((entry) => join(sessionsRoot, entry.name, STATE_FILENAME)).sort();
1106
+ } catch {
1107
+ return [];
1108
+ }
1109
+ }
1110
+ async function hydrateStoreFromDisk(store, directory, explicitPath, stateRoot) {
1111
+ const foundPaths = await discoverStateFiles(directory, explicitPath, stateRoot);
1112
+ let hydratedCount = 0;
1113
+ for (const foundPath of foundPaths) {
1114
+ const count = await hydrateFromStateFile(store, foundPath);
1115
+ hydratedCount += count;
1116
+ }
1117
+ return { hydratedCount };
1118
+ }
1119
+ async function hydrateFromStateFile(store, filePath) {
1120
+ try {
1121
+ const { text, truncated } = await portableReadBounded(filePath);
1122
+ if (truncated)
1123
+ return 0;
1124
+ if (!text.trim())
1125
+ return 0;
1126
+ const parsed = parseStateJson(text);
1127
+ if (!parsed)
1128
+ return 0;
1129
+ const snapshots = snapshotsFromParsed(parsed, sessionIDFromStatePath(filePath));
1130
+ for (const snapshot of snapshots) {
1131
+ store.applyEvent({
1132
+ kind: "create",
1133
+ sessionID: snapshot.sessionID,
1134
+ goalId: snapshot.goalId,
1135
+ snapshot: { ...snapshot, origin: "disk" },
1136
+ timestamp: Date.now()
1137
+ });
1138
+ }
1139
+ return snapshots.length;
1140
+ } catch {
1141
+ return 0;
1142
+ }
1143
+ }
1144
+ function parseStateJson(content) {
1145
+ try {
1146
+ return JSON.parse(content);
1147
+ } catch {
1148
+ return null;
1149
+ }
1150
+ }
1151
+ function snapshotsFromParsed(parsed, originSessionID) {
1152
+ const rawGoals = Array.isArray(parsed?.goals) ? parsed.goals : [];
1153
+ const out = [];
1154
+ for (const g of rawGoals) {
1155
+ if (!g || typeof g !== "object" || !g.goalId || !g.sessionID)
1156
+ continue;
1157
+ const r = g;
1158
+ if (originSessionID !== undefined && String(r.sessionID) !== originSessionID)
1159
+ continue;
1160
+ out.push({
1161
+ goalId: String(r.goalId),
1162
+ sessionID: String(r.sessionID),
1163
+ condition: String(r.condition ?? ""),
1164
+ artifactPointers: Array.isArray(r.artifactPointers) ? [...r.artifactPointers] : [],
1165
+ pendingProposal: r.pendingProposal ? {
1166
+ ...r.pendingProposal
1167
+ } : null,
1168
+ claims: Array.isArray(r.claims) ? r.claims.map((c) => ({
1169
+ ...c
1170
+ })) : [],
1171
+ lastClaim: r.lastClaim ? { ...r.lastClaim } : null,
1172
+ status: VALID_GOAL_STATUSES.has(String(r.status)) ? r.status : "active",
1173
+ revision: typeof r.revision === "number" ? r.revision : 0,
1174
+ turnCount: typeof r.turnCount === "number" ? r.turnCount : 0,
1175
+ totalTokens: typeof r.totalTokens === "number" ? r.totalTokens : 0,
1176
+ maxTokens: typeof r.maxTokens === "number" ? r.maxTokens : 1e6,
1177
+ maxTurns: typeof r.maxTurns === "number" ? r.maxTurns : 0,
1178
+ tokenBudget: typeof r.tokenBudget === "number" ? r.tokenBudget : null,
1179
+ usage: r.usage ?? {
1180
+ input: 0,
1181
+ output: 0,
1182
+ reasoning: 0,
1183
+ cacheRead: 0,
1184
+ cacheWrite: 0,
1185
+ cost: 0,
1186
+ costKnown: false
1187
+ },
1188
+ stopReason: String(r.stopReason ?? ""),
1189
+ blockedReason: String(r.blockedReason ?? ""),
1190
+ pausedAt: typeof r.pausedAt === "number" && Number.isFinite(r.pausedAt) && r.pausedAt > 0 ? r.pausedAt : 0,
1191
+ stoppedAt: typeof r.stoppedAt === "number" && Number.isFinite(r.stoppedAt) && r.stoppedAt > 0 ? r.stoppedAt : 0,
1192
+ createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),
1193
+ updatedAt: typeof r.updatedAt === "number" ? r.updatedAt : Date.now(),
1194
+ finishedAt: typeof r.finishedAt === "number" ? r.finishedAt : null,
1195
+ lastCheckpoint: r.lastCheckpoint ? {
1196
+ summary: String(r.lastCheckpoint.summary),
1197
+ timestamp: Number(r.lastCheckpoint.timestamp)
1198
+ } : null,
1199
+ history: Array.isArray(r.history) ? r.history.map((h) => ({
1200
+ type: String(h.type ?? ""),
1201
+ detail: String(h.detail ?? ""),
1202
+ timestamp: Number(h.timestamp ?? 0)
1203
+ })) : []
1204
+ });
1205
+ }
1206
+ return out;
1207
+ }
1208
+ async function readDiskGoalSnapshots(directory, explicitPath, stateRoot) {
1209
+ const { join } = await import("path");
1210
+ const foundPaths = await discoverStateFiles(directory, explicitPath, stateRoot);
1211
+ const out = [];
1212
+ const readableSessions = new Set;
1213
+ let filesRead = 0;
1214
+ for (const p of foundPaths) {
1215
+ try {
1216
+ const { text, truncated } = await portableReadBounded(p);
1217
+ if (truncated)
1218
+ continue;
1219
+ if (!text.trim())
1220
+ continue;
1221
+ const parsed = parseStateJson(text);
1222
+ if (!parsed)
1223
+ continue;
1224
+ filesRead += 1;
1225
+ const pathSession = sessionIDFromStatePath(p);
1226
+ if (pathSession)
1227
+ readableSessions.add(pathSession);
1228
+ const snaps = snapshotsFromParsed(parsed, pathSession);
1229
+ for (const s of snaps)
1230
+ readableSessions.add(s.sessionID);
1231
+ out.push(...snaps);
1232
+ } catch {}
1233
+ }
1234
+ let stateDirMissing = false;
1235
+ try {
1236
+ const { stat } = await import("fs/promises");
1237
+ if (explicitPath) {
1238
+ stateDirMissing = false;
1239
+ } else {
1240
+ await stat(join(resolveStateRoot(directory, stateRoot), SESSIONS_DIRNAME));
1241
+ }
1242
+ } catch {
1243
+ stateDirMissing = true;
1244
+ }
1245
+ return { snapshots: out, filesRead, stateDirMissing, readableSessions };
1246
+ }
1247
+
1248
+ // src/tui-v2.ts
1249
+ init_tui_views();
1250
+
1251
+ // src/tui-action-labels.ts
1252
+ var MUTATING_ROOTS = new Set([
1253
+ "pause",
1254
+ "resume",
1255
+ "clear",
1256
+ "edit",
1257
+ "checkpoint",
1258
+ "focus",
1259
+ "add",
1260
+ "sequence",
1261
+ "accept",
1262
+ "reject",
1263
+ "handback",
1264
+ "review-payload"
1265
+ ]);
1266
+ function isMutatingGoalCommand(command) {
1267
+ const root = command.trim().split(/\s+/)[0];
1268
+ return MUTATING_ROOTS.has(root);
1269
+ }
1270
+ function outcomeNeutralLabel(command) {
1271
+ const root = command.trim().split(/\s+/)[0];
1272
+ return `Goal requested: ${root}`;
1273
+ }
1274
+ function watchdogTimeoutMessage(host, command, timeoutMs) {
1275
+ const seconds = Math.round(timeoutMs / 1000);
1276
+ const shown = seconds < 1 ? "<1s" : `${seconds}s`;
1277
+ const root = command.trim().split(/\s+/)[0];
1278
+ const retry = host === "v1" ? `Retry from the Goal palette or /goal ${root}.` : "Retry from the Goal palette.";
1279
+ return `Goal action "${root}" did not land within ${shown}. ${retry}`;
1280
+ }
1281
+ var DEGRADED_MODE_MESSAGE = `${PRODUCT_DISPLAY_NAME} is not loaded: actions from this palette cannot take effect. ` + "Check the server plugin loaded, then reopen this palette.";
1282
+ function createDegradedModeDetector() {
1283
+ let surfaceAlive = false;
1284
+ let announcedThisEpisode = false;
1285
+ return {
1286
+ noteSurfaceAlive() {
1287
+ surfaceAlive = true;
1288
+ announcedThisEpisode = false;
1289
+ },
1290
+ checkDispatch() {
1291
+ if (surfaceAlive || announcedThisEpisode)
1292
+ return null;
1293
+ announcedThisEpisode = true;
1294
+ return DEGRADED_MODE_MESSAGE;
1295
+ },
1296
+ get isDegraded() {
1297
+ return !surfaceAlive;
1298
+ }
1299
+ };
1300
+ }
1301
+ function createGoalWatchdogs(host, notifyTimeout, defaultTimeoutMs = 15000) {
1302
+ const active = new Map;
1303
+ const keyOf = (sessionID, command) => `${sessionID}:${command.trim().split(/\s+/)[0]}`;
1304
+ return {
1305
+ arm(sessionID, command, timeoutMs = defaultTimeoutMs) {
1306
+ const key = keyOf(sessionID, command);
1307
+ const existing = active.get(key);
1308
+ if (existing)
1309
+ clearTimeout(existing.timer);
1310
+ const timer = setTimeout(() => {
1311
+ active.delete(key);
1312
+ notifyTimeout(watchdogTimeoutMessage(host, command, timeoutMs));
1313
+ }, timeoutMs);
1314
+ active.set(key, { timer, command, sessionID });
1315
+ },
1316
+ disarmSession(sessionID) {
1317
+ for (const [key, w] of active.entries()) {
1318
+ if (w.sessionID === sessionID) {
1319
+ clearTimeout(w.timer);
1320
+ active.delete(key);
1321
+ }
1322
+ }
1323
+ },
1324
+ cancel(sessionID, command) {
1325
+ const key = keyOf(sessionID, command);
1326
+ const w = active.get(key);
1327
+ if (w) {
1328
+ clearTimeout(w.timer);
1329
+ active.delete(key);
1330
+ }
1331
+ },
1332
+ get armedCount() {
1333
+ return active.size;
1334
+ }
1335
+ };
1336
+ }
1337
+
1338
+ // src/tui-dashboard-route.tsx
1339
+ init_tui_views();
1340
+ import { jsx, jsxs } from "@opentui/solid/jsx-runtime";
1341
+ var ATTR_BOLD = 1;
1342
+ var STATUS_LINE = 1;
1343
+ function DashboardRoute(props) {
1344
+ const theme = props.theme ?? {};
1345
+ const snaps = props.snapshots;
1346
+ const focused = props.focusedGoalId;
1347
+ return /* @__PURE__ */ jsxs("box", {
1348
+ flexDirection: "column",
1349
+ width: "100%",
1350
+ height: "100%",
1351
+ backgroundColor: theme.background?.default,
1352
+ children: [
1353
+ /* @__PURE__ */ jsx("box", {
1354
+ flexShrink: 0,
1355
+ paddingLeft: 1,
1356
+ paddingRight: 1,
1357
+ backgroundColor: theme.background?.panel,
1358
+ children: /* @__PURE__ */ jsx("text", {
1359
+ fg: theme.text?.accent?.default ?? theme.text?.default,
1360
+ attributes: ATTR_BOLD,
1361
+ children: PRODUCT_DISPLAY_NAME
1362
+ })
1363
+ }),
1364
+ /* @__PURE__ */ jsxs("scrollbox", {
1365
+ flexGrow: 1,
1366
+ flexDirection: "column",
1367
+ paddingLeft: 1,
1368
+ paddingRight: 1,
1369
+ verticalScrollbarOptions: {
1370
+ visible: true,
1371
+ trackOptions: {
1372
+ backgroundColor: theme.background?.surface?.offset ?? theme.background?.default,
1373
+ foregroundColor: theme.border?.default
1374
+ }
1375
+ },
1376
+ children: [
1377
+ snaps().length === 0 ? /* @__PURE__ */ jsx("box", {
1378
+ paddingLeft: 1,
1379
+ paddingRight: 1,
1380
+ paddingTop: 1,
1381
+ children: /* @__PURE__ */ jsx("text", {
1382
+ fg: theme.text?.subdued,
1383
+ children: props.hydrationText ?? "No active goals. Use /goal <condition> to set one."
1384
+ })
1385
+ }) : snaps().map((snap) => {
1386
+ const isFocused = snap.goalId === focused();
1387
+ return /* @__PURE__ */ jsxs("box", {
1388
+ flexDirection: "column",
1389
+ paddingBottom: 1,
1390
+ backgroundColor: isFocused ? theme.background?.panel ?? theme.background?.default : undefined,
1391
+ borderStyle: isFocused ? "rounded" : undefined,
1392
+ borderColor: isFocused ? theme.border?.active ?? theme.border?.default : undefined,
1393
+ onMouseUp: () => props.onSelectGoal(snap.goalId),
1394
+ children: [
1395
+ /* @__PURE__ */ jsx("box", {
1396
+ paddingLeft: 1,
1397
+ paddingRight: 1,
1398
+ flexDirection: "row",
1399
+ children: /* @__PURE__ */ jsxs("text", {
1400
+ fg: theme.text?.accent?.default ?? theme.text?.default,
1401
+ attributes: ATTR_BOLD,
1402
+ children: [
1403
+ isFocused ? "\u25B8 " : " ",
1404
+ "Goal: ",
1405
+ snap.goalId.substring(0, 8)
1406
+ ]
1407
+ })
1408
+ }),
1409
+ /* @__PURE__ */ jsx("box", {
1410
+ paddingLeft: 1,
1411
+ paddingRight: 1,
1412
+ flexDirection: "column",
1413
+ children: goalCardLines(snap, props.activeSessionID()).map((line, i) => /* @__PURE__ */ jsx("text", {
1414
+ fg: cardLineColor(line, i, snap.status, theme),
1415
+ children: line.text
1416
+ }))
1417
+ })
1418
+ ]
1419
+ });
1420
+ }),
1421
+ props.sections().map((section) => /* @__PURE__ */ jsxs("box", {
1422
+ flexDirection: "column",
1423
+ paddingBottom: 1,
1424
+ children: [
1425
+ /* @__PURE__ */ jsx("box", {
1426
+ backgroundColor: theme.background?.panel ?? theme.background?.default,
1427
+ paddingLeft: 1,
1428
+ paddingRight: 1,
1429
+ children: /* @__PURE__ */ jsx("text", {
1430
+ fg: theme.text?.accent?.default ?? theme.text?.default,
1431
+ children: section.title
1432
+ })
1433
+ }),
1434
+ /* @__PURE__ */ jsx("box", {
1435
+ paddingLeft: 1,
1436
+ paddingRight: 1,
1437
+ flexDirection: "column",
1438
+ children: section.text.split(`
1439
+ `).map((line) => /* @__PURE__ */ jsx("text", {
1440
+ fg: theme.text?.default,
1441
+ children: line
1442
+ }))
1443
+ })
1444
+ ]
1445
+ }))
1446
+ ]
1447
+ }),
1448
+ /* @__PURE__ */ jsx("box", {
1449
+ flexShrink: 0,
1450
+ paddingLeft: 1,
1451
+ paddingRight: 1,
1452
+ backgroundColor: theme.background?.panel,
1453
+ flexDirection: "row",
1454
+ children: /* @__PURE__ */ jsx("text", {
1455
+ fg: theme.text?.subdued,
1456
+ children: props.footer
1457
+ })
1458
+ })
1459
+ ]
1460
+ });
1461
+ }
1462
+ function statusColor(status, theme) {
1463
+ switch (status) {
1464
+ case "active":
1465
+ return theme.text?.success ?? theme.text?.default;
1466
+ case "paused":
1467
+ return theme.text?.warning ?? theme.text?.default;
1468
+ case "blocked":
1469
+ return theme.text?.error ?? theme.text?.default;
1470
+ case "complete":
1471
+ return theme.text?.subdued ?? theme.text?.default;
1472
+ default:
1473
+ return theme.text?.default;
1474
+ }
1475
+ }
1476
+ function cardLineColor(line, index, status, theme) {
1477
+ if (index === STATUS_LINE)
1478
+ return statusColor(status, theme);
1479
+ return line.subdued ? theme.text?.subdued ?? theme.text?.default : theme.text?.default;
1480
+ }
1481
+
1482
+ // src/tui-v2.ts
1483
+ import { createSignal, onCleanup } from "solid-js";
1484
+
1485
+ // src/tui-companion-refresh.ts
1486
+ function keyOf(sessionID, goalId) {
1487
+ return `${sessionID}\x00${goalId}`;
1488
+ }
1489
+ function createDiskRefreshLoop(options) {
1490
+ const { store, onEvent } = options;
1491
+ const intervalMs = options.intervalMs ?? 1000;
1492
+ let timer = null;
1493
+ let ticking = false;
1494
+ let baselined = false;
1495
+ let previous = new Map;
1496
+ function synthesize(current, readableSessions) {
1497
+ const events = [];
1498
+ const seen = new Set;
1499
+ for (const snap of current) {
1500
+ const key = keyOf(snap.sessionID, snap.goalId);
1501
+ seen.add(key);
1502
+ const prev = previous.get(key);
1503
+ if (!prev) {
1504
+ events.push({
1505
+ kind: "create",
1506
+ sessionID: snap.sessionID,
1507
+ timestamp: Date.now(),
1508
+ snapshot: { ...snap, origin: "disk" }
1509
+ });
1510
+ } else if (prev.revision !== snap.revision || prev.status !== snap.status || prev.totalTokens !== snap.totalTokens || prev.turnCount !== snap.turnCount) {
1511
+ events.push({
1512
+ kind: "transition",
1513
+ sessionID: snap.sessionID,
1514
+ timestamp: Date.now(),
1515
+ snapshot: { ...snap, origin: "disk" },
1516
+ previousStatus: prev.status
1517
+ });
1518
+ }
1519
+ }
1520
+ for (const [key, prev] of previous) {
1521
+ if (seen.has(key))
1522
+ continue;
1523
+ if (!readableSessions.has(prev.sessionID))
1524
+ continue;
1525
+ events.push({
1526
+ kind: "remove",
1527
+ sessionID: prev.sessionID,
1528
+ goalId: prev.goalId,
1529
+ timestamp: Date.now()
1530
+ });
1531
+ }
1532
+ return events;
1533
+ }
1534
+ async function tick() {
1535
+ if (ticking)
1536
+ return;
1537
+ ticking = true;
1538
+ try {
1539
+ const read = await readDiskGoalSnapshots(options.directory, options.explicitPath, options.stateRoot);
1540
+ if (!baselined) {
1541
+ if (read.filesRead === 0 && !read.stateDirMissing)
1542
+ return;
1543
+ baselined = true;
1544
+ previous = new Map(read.snapshots.map((s) => [keyOf(s.sessionID, s.goalId), s]));
1545
+ return;
1546
+ }
1547
+ if (read.filesRead === 0 && previous.size > 0)
1548
+ return;
1549
+ for (const event of synthesize(read.snapshots, read.readableSessions)) {
1550
+ if (event.snapshot || event.goalId)
1551
+ store.applyEvent(event);
1552
+ onEvent(event);
1553
+ }
1554
+ const oldPrevious = previous;
1555
+ previous = new Map(read.snapshots.map((s) => [keyOf(s.sessionID, s.goalId), s]));
1556
+ for (const [key, snap] of oldPrevious) {
1557
+ if (!read.readableSessions.has(snap.sessionID) && !previous.has(key)) {
1558
+ previous.set(key, snap);
1559
+ }
1560
+ }
1561
+ } catch {} finally {
1562
+ ticking = false;
1563
+ }
1564
+ }
1565
+ return {
1566
+ tick,
1567
+ seedBaseline(snapshots) {
1568
+ baselined = true;
1569
+ previous = new Map(snapshots.map((s) => [keyOf(s.sessionID, s.goalId), s]));
1570
+ },
1571
+ start() {
1572
+ if (timer)
1573
+ return;
1574
+ if (!baselined)
1575
+ tick();
1576
+ timer = setInterval(() => void tick(), intervalMs);
1577
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
1578
+ timer.unref();
1579
+ }
1580
+ },
1581
+ stop() {
1582
+ if (timer) {
1583
+ clearInterval(timer);
1584
+ timer = null;
1585
+ }
1586
+ }
1587
+ };
1588
+ }
1589
+
1590
+ // src/tui-toast-policy.ts
1591
+ init_status_label();
1592
+ var TOAST_MESSAGE_MAX = 120;
1593
+ var REMEMBERED_LIMIT = 4096;
1594
+ var TOAST_MIN_INTERVAL_MS = 2000;
1595
+ var TOAST_COALESCE_WINDOW_MS = 500;
1596
+ var TOAST_QUEUE_MAX = 3;
1597
+ var BRIEFING_SESSION_KEY = "\x00briefing";
1598
+ function truncateCondition(text, max = 60) {
1599
+ const clean = text.replace(/\s+/g, " ").trim();
1600
+ if (clean.length <= max)
1601
+ return clean;
1602
+ const cut = clean.slice(0, max);
1603
+ const lastSpace = cut.lastIndexOf(" ");
1604
+ return `${(lastSpace > max * 0.5 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
1605
+ }
1606
+ function shouldToast(event) {
1607
+ switch (event.kind) {
1608
+ case "create":
1609
+ return true;
1610
+ case "remove":
1611
+ return true;
1612
+ case "usage":
1613
+ return false;
1614
+ case "transition":
1615
+ return lifecycleSide(event) !== null;
1616
+ default:
1617
+ return false;
1618
+ }
1619
+ }
1620
+ function lifecycleSide(event) {
1621
+ const status = event.snapshot?.status;
1622
+ if (!status)
1623
+ return null;
1624
+ const from = previousStatusOf(event);
1625
+ if (from !== undefined && from === status)
1626
+ return null;
1627
+ if (from === undefined) {
1628
+ return status === "active" || status === "finalizing" ? null : "stop";
1629
+ }
1630
+ if (status === "complete" || status === "blocked")
1631
+ return "stop";
1632
+ if (status === "active")
1633
+ return "start";
1634
+ if (STOPPED_STATUSES.has(status)) {
1635
+ return SELF_RESOLVING_STOP_REASONS.has(event.snapshot?.stopReason ?? "") ? null : "stop";
1636
+ }
1637
+ return null;
1638
+ }
1639
+ function previousStatusOf(event) {
1640
+ return event.previousStatus ?? event.transition?.from;
1641
+ }
1642
+ var STOPPED_STATUSES = new Set([
1643
+ "paused",
1644
+ "blocked",
1645
+ "budgetLimited",
1646
+ "complete"
1647
+ ]);
1648
+ function isLimitOrEscalationPause(stopReason) {
1649
+ return /recovery exhausted|escalated|max turns|max stall|max context tokens|budget/i.test(stopReason);
1650
+ }
1651
+ var LIMIT_PAUSE_PHRASES = [
1652
+ [/max turns/i, "Goal stopped \u2014 it reached its turn limit"],
1653
+ [/max stall/i, "Goal stopped \u2014 it ran for its time limit without finishing"],
1654
+ [/max context tokens/i, "Goal stopped \u2014 it reached its context limit"],
1655
+ [/budget/i, "Goal stopped \u2014 its token budget ran out"],
1656
+ [
1657
+ /recovery exhausted/i,
1658
+ "Goal paused after repeated failures \u2014 review needed"
1659
+ ],
1660
+ [/escalated/i, "Goal escalated \u2014 it needs you to decide how to continue"]
1661
+ ];
1662
+ function limitPausePhrase(stopReason) {
1663
+ for (const [pattern, phrase] of LIMIT_PAUSE_PHRASES) {
1664
+ if (pattern.test(stopReason))
1665
+ return phrase;
1666
+ }
1667
+ return isLimitOrEscalationPause(stopReason) ? "Goal stopped by a limit it reached" : null;
1668
+ }
1669
+ var YIELDING_STOP_REASONS = new Set([
1670
+ USER_INTERVENTION_STOP_REASON
1671
+ ]);
1672
+ var NEEDS_YOU_PHRASES = [
1673
+ [/tool surface unavailable/i, "the goal tools are gone"],
1674
+ [
1675
+ /verifier:\s*(COMPLETE|NEEDS_INPUT|CANCELLED|BLOCKED|WORKING)/i,
1676
+ "a verifier stopped it"
1677
+ ],
1678
+ [
1679
+ /unattested completion asserted repeatedly|no attestation/i,
1680
+ "the claim could not be attested"
1681
+ ],
1682
+ [/judge rejected/i, "the judge rejected the claim"],
1683
+ [/permission rejected/i, "a permission was rejected"],
1684
+ [/session error/i, "a session error"],
1685
+ [/execution (failure|interrupted)|message aborted/i, "an execution error"],
1686
+ [/no tool calls/i, "no tool calls"],
1687
+ [/no progress/i, "no progress"],
1688
+ [/deferred too many times/i, "deferred too many times"],
1689
+ [/compaction loop/i, "the session is stuck compacting"],
1690
+ [/^(paused|explicit pause)$/i, "paused"],
1691
+ [/blocked/i, "blocked"]
1692
+ ];
1693
+ var MACHINE_STRING = /[()]|\w+:|[a-z][A-Z]|_/;
1694
+ function needsYouReason(stopReason) {
1695
+ for (const [pattern, phrase] of NEEDS_YOU_PHRASES) {
1696
+ if (pattern.test(stopReason))
1697
+ return phrase;
1698
+ }
1699
+ const clean = stopReason.trim();
1700
+ if (clean === "" || MACHINE_STRING.test(clean))
1701
+ return "stopped for a reason the plugin did not name";
1702
+ return truncateCondition(clean);
1703
+ }
1704
+ function goalNeedsTheUser(snapshot, now) {
1705
+ const status = snapshot.status;
1706
+ if (status === "active" || status === "finalizing" || status === "complete")
1707
+ return false;
1708
+ if (isSelfResolvingStop(status, snapshot.stopReason, snapshot.stoppedAt, now ?? Date.now(), snapshot.updatedAt))
1709
+ return false;
1710
+ return true;
1711
+ }
1712
+ function reasonForGoal(snapshot, now) {
1713
+ if (snapshot.status === "blocked") {
1714
+ return snapshot.blockedReason ? truncateCondition(snapshot.blockedReason, 40) : "blocked";
1715
+ }
1716
+ if (isYieldingPause(snapshot.status, snapshot.stopReason) && !isLiveYield(snapshot.status, snapshot.stopReason, snapshot.stoppedAt, now ?? Date.now(), snapshot.updatedAt)) {
1717
+ return "it did not pick your message back up";
1718
+ }
1719
+ if (snapshot.status === "budgetLimited" && !snapshot.stopReason)
1720
+ return "the token budget ran out";
1721
+ return needsYouReason(snapshot.stopReason);
1722
+ }
1723
+ function summarizeGoalsNeedingYou(snapshots) {
1724
+ const counts = new Map;
1725
+ let total = 0;
1726
+ for (const snapshot of snapshots) {
1727
+ if (!goalNeedsTheUser(snapshot))
1728
+ continue;
1729
+ const reason = reasonForGoal(snapshot);
1730
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
1731
+ total += 1;
1732
+ }
1733
+ if (total === 0)
1734
+ return null;
1735
+ const ordered = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
1736
+ const goalWord = total === 1 ? "1 goal needs you" : `${total} goals need you`;
1737
+ const budget = TOAST_MESSAGE_MAX - 1;
1738
+ const compose = (parts, dropped) => {
1739
+ const list = parts.map(([reason, count]) => count > 1 ? `${count} ${reason}` : reason).join(", ");
1740
+ const tail = dropped > 0 ? `, +${dropped} more` : "";
1741
+ const text = `${goalWord}: ${list}${tail}`;
1742
+ return text.length <= TOAST_MESSAGE_MAX ? text : `${text.slice(0, TOAST_MESSAGE_MAX - 1)}\u2026`;
1743
+ };
1744
+ let kept = ordered;
1745
+ let dropped = 0;
1746
+ while (kept.length > 1 && compose(kept, 0).length > budget) {
1747
+ const removed = kept[kept.length - 1];
1748
+ dropped += removed[1];
1749
+ kept = kept.slice(0, -1);
1750
+ }
1751
+ return {
1752
+ title: PRODUCT_DISPLAY_NAME,
1753
+ variant: "warning",
1754
+ message: compose(kept, dropped)
1755
+ };
1756
+ }
1757
+ var CLAIM_PLAIN = {
1758
+ "verified-complete": "attested",
1759
+ "unverifiable-claim": "completed, but no attestation could be obtained",
1760
+ "claim-refuted": "claimed done, but the evidence said otherwise",
1761
+ "blocked-acknowledged": "stopped with a known blocker"
1762
+ };
1763
+ function formatCuratedToast(event, startAnnouncement = true) {
1764
+ const condition = truncateCondition(event.snapshot?.condition ?? "goal");
1765
+ switch (event.kind) {
1766
+ case "create":
1767
+ return {
1768
+ title: PRODUCT_DISPLAY_NAME,
1769
+ variant: "info",
1770
+ message: `Goal started: ${condition}`
1771
+ };
1772
+ case "remove":
1773
+ return {
1774
+ title: PRODUCT_DISPLAY_NAME,
1775
+ variant: "info",
1776
+ message: `Goal cleared: ${truncateCondition(event.snapshot?.condition ?? event.goalId ?? "goal")}`
1777
+ };
1778
+ case "transition": {
1779
+ const status = event.snapshot?.status;
1780
+ if (status === "complete") {
1781
+ const outcomeStatus = event.snapshot?.lastClaim?.outcome.status;
1782
+ const suffix = outcomeStatus && outcomeStatus !== "verified-complete" ? ` (${CLAIM_PLAIN[outcomeStatus] ?? outcomeStatus})` : "";
1783
+ return {
1784
+ title: PRODUCT_DISPLAY_NAME,
1785
+ variant: "info",
1786
+ message: `Goal complete: ${condition}${suffix}`
1787
+ };
1788
+ }
1789
+ if (status === "blocked") {
1790
+ const reason = truncateCondition(event.snapshot?.blockedReason ?? "needs your input");
1791
+ return {
1792
+ title: PRODUCT_DISPLAY_NAME,
1793
+ variant: "warning",
1794
+ message: `Paused \u2014 ${reason}`
1795
+ };
1796
+ }
1797
+ const limitPause = limitPausePhrase(event.snapshot?.stopReason ?? "");
1798
+ if (limitPause) {
1799
+ return {
1800
+ title: PRODUCT_DISPLAY_NAME,
1801
+ variant: "error",
1802
+ message: `${limitPause} (${condition})`
1803
+ };
1804
+ }
1805
+ if (status === "active" && startAnnouncement) {
1806
+ return {
1807
+ title: PRODUCT_DISPLAY_NAME,
1808
+ variant: "info",
1809
+ message: `Goal started: ${condition}`
1810
+ };
1811
+ }
1812
+ if (status === "active") {
1813
+ return {
1814
+ title: PRODUCT_DISPLAY_NAME,
1815
+ variant: "info",
1816
+ message: `Goal running again: ${condition}`
1817
+ };
1818
+ }
1819
+ if (status !== undefined && STOPPED_STATUSES.has(status)) {
1820
+ return {
1821
+ title: PRODUCT_DISPLAY_NAME,
1822
+ variant: "warning",
1823
+ message: `Goal stopped \u2014 ${needsYouReason(event.snapshot?.stopReason ?? "")} (${condition})`
1824
+ };
1825
+ }
1826
+ return {
1827
+ title: PRODUCT_DISPLAY_NAME,
1828
+ variant: "info",
1829
+ message: `Goal update: ${condition}`
1830
+ };
1831
+ }
1832
+ default:
1833
+ return {
1834
+ title: PRODUCT_DISPLAY_NAME,
1835
+ variant: "info",
1836
+ message: `Goal update: ${condition}`
1837
+ };
1838
+ }
1839
+ }
1840
+
1841
+ class ToastCoalescer {
1842
+ emit;
1843
+ now;
1844
+ autoFlushMs;
1845
+ queues = new Map;
1846
+ lastEmittedAt = new Map;
1847
+ lastMessageBySession = new Map;
1848
+ announced = new Set;
1849
+ yielding = new Set;
1850
+ pumpTimer = null;
1851
+ constructor(emit, now = Date.now, autoFlushMs = null) {
1852
+ this.emit = emit;
1853
+ this.now = now;
1854
+ this.autoFlushMs = autoFlushMs;
1855
+ }
1856
+ get queuedCount() {
1857
+ let total = 0;
1858
+ for (const queue of this.queues.values())
1859
+ total += queue.length;
1860
+ return total;
1861
+ }
1862
+ accept(event, sessionKey) {
1863
+ this.flush();
1864
+ const goalId = event.snapshot?.goalId;
1865
+ const memoryKey = goalId ? `${sessionKey}|${goalId}` : null;
1866
+ const side = lifecycleSide(event);
1867
+ if (memoryKey) {
1868
+ if (event.kind === "remove" && event.goalId) {
1869
+ this.announced.delete(memoryKey);
1870
+ this.yielding.delete(memoryKey);
1871
+ } else if (event.kind === "create") {
1872
+ this.claimStartAnnouncement(sessionKey, goalId);
1873
+ } else if (event.snapshot?.status === "paused" && YIELDING_STOP_REASONS.has(event.snapshot.stopReason)) {
1874
+ this.yielding.add(memoryKey);
1875
+ this.pruneRemembered();
1876
+ }
1877
+ }
1878
+ let firstTime = false;
1879
+ if (!shouldToast(event))
1880
+ return;
1881
+ if (side === "start" && memoryKey) {
1882
+ if (this.yielding.has(memoryKey)) {
1883
+ this.yielding.delete(memoryKey);
1884
+ return;
1885
+ }
1886
+ }
1887
+ if (side === "start" && goalId)
1888
+ firstTime = this.claimStartAnnouncement(sessionKey, goalId);
1889
+ this.enqueue(sessionKey, formatCuratedToast(event, firstTime), goalId);
1890
+ }
1891
+ brief(sessionKey, toast) {
1892
+ this.flush();
1893
+ this.enqueue(sessionKey, toast, undefined);
1894
+ }
1895
+ flush() {
1896
+ for (const [sessionKey, queue] of [...this.queues]) {
1897
+ while (queue.length > 0) {
1898
+ const nowTs = this.now();
1899
+ if (nowTs - this.emittedAtFor(sessionKey) < TOAST_MIN_INTERVAL_MS)
1900
+ break;
1901
+ const next = queue.shift();
1902
+ if (!next)
1903
+ break;
1904
+ this.emitNow(sessionKey, next, nowTs);
1905
+ }
1906
+ if (queue.length === 0)
1907
+ this.queues.delete(sessionKey);
1908
+ }
1909
+ }
1910
+ startAutoFlush() {
1911
+ if (this.pumpTimer || this.autoFlushMs === null)
1912
+ return;
1913
+ this.pumpTimer = setInterval(() => this.flush(), this.autoFlushMs);
1914
+ if (typeof this.pumpTimer === "object" && this.pumpTimer !== null && "unref" in this.pumpTimer) {
1915
+ this.pumpTimer.unref();
1916
+ }
1917
+ }
1918
+ stopAutoFlush() {
1919
+ if (this.pumpTimer) {
1920
+ clearInterval(this.pumpTimer);
1921
+ this.pumpTimer = null;
1922
+ }
1923
+ }
1924
+ claimStartAnnouncement(sessionKey, goalId) {
1925
+ if (!goalId)
1926
+ return true;
1927
+ const key = `${sessionKey}|${goalId}`;
1928
+ if (this.announced.has(key))
1929
+ return false;
1930
+ this.announced.add(key);
1931
+ this.pruneRemembered();
1932
+ return true;
1933
+ }
1934
+ pruneRemembered() {
1935
+ while (this.announced.size + this.yielding.size > REMEMBERED_LIMIT) {
1936
+ const oldest = this.announced.values().next();
1937
+ if (!oldest.done) {
1938
+ this.announced.delete(oldest.value);
1939
+ continue;
1940
+ }
1941
+ const oldestYield = this.yielding.values().next();
1942
+ if (oldestYield.done)
1943
+ return;
1944
+ this.yielding.delete(oldestYield.value);
1945
+ }
1946
+ }
1947
+ enqueue(sessionKey, toast, goalId) {
1948
+ const last = this.lastMessageBySession.get(sessionKey);
1949
+ if (last && toast.message === last.message && this.now() - last.at < TOAST_COALESCE_WINDOW_MS) {
1950
+ return;
1951
+ }
1952
+ this.lastMessageBySession.set(sessionKey, {
1953
+ message: toast.message,
1954
+ at: this.now()
1955
+ });
1956
+ const nowTs = this.now();
1957
+ if (nowTs - this.emittedAtFor(sessionKey) >= TOAST_MIN_INTERVAL_MS) {
1958
+ this.emitNow(sessionKey, toast, nowTs);
1959
+ return;
1960
+ }
1961
+ let queue = this.queues.get(sessionKey);
1962
+ if (!queue) {
1963
+ queue = [];
1964
+ this.queues.set(sessionKey, queue);
1965
+ }
1966
+ if (goalId) {
1967
+ const staleAt = queue.findIndex((queued) => queued.goalId === goalId);
1968
+ if (staleAt >= 0)
1969
+ queue.splice(staleAt, 1);
1970
+ }
1971
+ queue.push({ ...toast, goalId });
1972
+ if (queue.length > TOAST_QUEUE_MAX) {
1973
+ queue.shift();
1974
+ }
1975
+ }
1976
+ emittedAtFor(sessionKey) {
1977
+ return this.lastEmittedAt.get(sessionKey) ?? Number.NEGATIVE_INFINITY;
1978
+ }
1979
+ emitNow(sessionKey, toast, nowTs) {
1980
+ let final = toast;
1981
+ if (final.message.length > TOAST_MESSAGE_MAX) {
1982
+ final = {
1983
+ ...final,
1984
+ message: `${final.message.slice(0, TOAST_MESSAGE_MAX - 1)}\u2026`
1985
+ };
1986
+ }
1987
+ this.lastEmittedAt.set(sessionKey, nowTs);
1988
+ const { goalId: _goalId, ...visible } = final;
1989
+ this.emit(visible);
1990
+ }
1991
+ }
1992
+
1993
+ // src/tui-sound.ts
1994
+ function soundForEvent(kind, status) {
1995
+ switch (kind) {
1996
+ case "create":
1997
+ return "default";
1998
+ case "transition":
1999
+ switch (status) {
2000
+ case "complete":
2001
+ return "done";
2002
+ case "paused":
2003
+ return "question";
2004
+ case "blocked":
2005
+ return "question";
2006
+ case "budgetLimited":
2007
+ return "error";
2008
+ case "active":
2009
+ return "default";
2010
+ case "finalizing":
2011
+ return;
2012
+ default:
2013
+ return;
2014
+ }
2015
+ case "usage":
2016
+ return;
2017
+ case "remove":
2018
+ return;
2019
+ default:
2020
+ return;
2021
+ }
2022
+ }
2023
+
2024
+ // src/tui-v2-events.ts
2025
+ function wireV2Events(args) {
2026
+ const {
2027
+ context,
2028
+ store,
2029
+ stateRoot,
2030
+ resolveWorkspaceDir,
2031
+ ensureHydrated,
2032
+ disarmWatchdogs,
2033
+ dashboardRouteDispose,
2034
+ activeWatchdogs,
2035
+ log
2036
+ } = args;
2037
+ const playSound = (kind, status) => {
2038
+ const name = soundForEvent(kind, status);
2039
+ if (!name)
2040
+ return;
2041
+ try {
2042
+ context.attention.notify({
2043
+ message: `Goal ${kind}${status ? ` \u2192 ${status}` : ""}`,
2044
+ sound: { name, when: "always" },
2045
+ notification: false
2046
+ }).catch(() => {});
2047
+ } catch {}
2048
+ };
2049
+ let diskLoop = null;
2050
+ let disposed = false;
2051
+ const coalescer = new ToastCoalescer((toast) => {
2052
+ try {
2053
+ context.ui.toast.show({
2054
+ variant: toast.variant,
2055
+ title: PRODUCT_DISPLAY_NAME,
2056
+ message: toast.message,
2057
+ duration: 5000
2058
+ });
2059
+ } catch {}
2060
+ }, Date.now, 500);
2061
+ coalescer.startAutoFlush();
2062
+ let briefingFired = false;
2063
+ const briefIfNeeded = () => {
2064
+ if (briefingFired || disposed)
2065
+ return;
2066
+ briefingFired = true;
2067
+ const briefing = summarizeGoalsNeedingYou(store.getAllSnapshots());
2068
+ if (!briefing)
2069
+ return;
2070
+ log("info", `Briefing: ${briefing.message}`);
2071
+ coalescer.brief(BRIEFING_SESSION_KEY, briefing);
2072
+ };
2073
+ const startDiskLoop = async () => {
2074
+ if (diskLoop || disposed)
2075
+ return;
2076
+ for (let attempt = 0;attempt < 12; attempt++) {
2077
+ if (disposed)
2078
+ return;
2079
+ const dir = await resolveWorkspaceDir();
2080
+ if (dir) {
2081
+ diskLoop = createDiskRefreshLoop({
2082
+ directory: dir,
2083
+ stateRoot,
2084
+ store,
2085
+ intervalMs: 1000,
2086
+ onEvent: (event) => {
2087
+ if (disposed)
2088
+ return;
2089
+ playSound(event.kind, event.snapshot?.status);
2090
+ coalescer.accept(event, event.sessionID);
2091
+ }
2092
+ });
2093
+ diskLoop.start();
2094
+ log("info", `disk-refresh loop started (dir=${dir})`);
2095
+ await ensureHydrated();
2096
+ briefIfNeeded();
2097
+ return;
2098
+ }
2099
+ await new Promise((r) => setTimeout(r, 500));
2100
+ }
2101
+ log("info", "disk-refresh loop: workspace directory never resolved; loop not started");
2102
+ };
2103
+ startDiskLoop();
2104
+ const degraded = createDegradedModeDetector();
2105
+ let unsub = null;
2106
+ try {
2107
+ unsub = context.data.on("session.tool.success", (event) => {
2108
+ try {
2109
+ const evData = event?.data;
2110
+ if (evData?.sessionID && (evData.tool === "goal-command" || typeof evData.tool === "string" && evData.tool.endsWith("_goal"))) {
2111
+ disarmWatchdogs(evData.sessionID);
2112
+ }
2113
+ const meta = evData?.metadata;
2114
+ const events = decodeGoalToolMetadata(meta);
2115
+ if (!events)
2116
+ return;
2117
+ degraded.noteSurfaceAlive();
2118
+ for (const parsed of events) {
2119
+ disarmWatchdogs(parsed.sessionID);
2120
+ store.applyEvent(parsed);
2121
+ playSound(parsed.kind, parsed.snapshot?.status);
2122
+ }
2123
+ } catch (err) {
2124
+ log("error", `Event error: ${err instanceof Error ? err.message : String(err)}`);
2125
+ }
2126
+ });
2127
+ } catch (err) {
2128
+ log("error", `Subscribe error: ${err instanceof Error ? err.message : String(err)}`);
2129
+ }
2130
+ return {
2131
+ dispose: () => {
2132
+ disposed = true;
2133
+ if (unsub) {
2134
+ try {
2135
+ unsub();
2136
+ } catch {}
2137
+ }
2138
+ if (diskLoop)
2139
+ diskLoop.stop();
2140
+ coalescer.stopAutoFlush();
2141
+ for (const w of activeWatchdogs.values()) {
2142
+ clearTimeout(w.timer);
2143
+ }
2144
+ activeWatchdogs.clear();
2145
+ if (dashboardRouteDispose) {
2146
+ try {
2147
+ dashboardRouteDispose();
2148
+ } catch {}
2149
+ }
2150
+ }
2151
+ };
2152
+ }
2153
+
2154
+ // src/tui-v2.ts
2155
+ var GOAL_PREFIX = "ctrl+shift+g";
2156
+ function chord(actionKey) {
2157
+ return `${GOAL_PREFIX} ${actionKey}`;
2158
+ }
2159
+ function unwrapDirectory(out) {
2160
+ if (!out || typeof out !== "object")
2161
+ return;
2162
+ const direct = out;
2163
+ if (typeof direct.directory === "string" && direct.directory)
2164
+ return direct.directory;
2165
+ if (direct.location && typeof direct.location === "object") {
2166
+ const l = direct.location;
2167
+ if (typeof l.directory === "string" && l.directory)
2168
+ return l.directory;
2169
+ }
2170
+ if (direct.data && typeof direct.data === "object")
2171
+ return unwrapDirectory(direct.data);
2172
+ return;
2173
+ }
2174
+ var GoalTuiPluginV2 = {
2175
+ id: "fixate-on-tui",
2176
+ async setup(context) {
2177
+ if (!context.keymap || typeof context.keymap.layer !== "function") {
2178
+ return () => {};
2179
+ }
2180
+ const opts = {
2181
+ logLevel: context.options?.logLevel ?? "info",
2182
+ stateRoot: context.options?.stateRoot,
2183
+ workspaceDirectory: typeof context.options?.workspaceDirectory === "string" && context.options.workspaceDirectory.trim() ? context.options.workspaceDirectory.trim() : undefined
2184
+ };
2185
+ const store = createTuiStateStore();
2186
+ const activeSessionID = () => {
2187
+ const route = context.ui.router.current();
2188
+ if (route.type !== "session" || !route.sessionID)
2189
+ return null;
2190
+ return route.sessionID;
2191
+ };
2192
+ const log = (level, message) => {
2193
+ if (opts.logLevel === "error" && level !== "error")
2194
+ return;
2195
+ if (opts.logLevel === "info" && level === "debug")
2196
+ return;
2197
+ try {
2198
+ if (level === "error") {
2199
+ context.ui.toast.show({
2200
+ variant: "error",
2201
+ title: PRODUCT_DISPLAY_NAME,
2202
+ message,
2203
+ duration: 6000
2204
+ });
2205
+ }
2206
+ console[level === "error" ? "error" : "log"](`[${GOAL_TUI_EVENT_TITLE}/tui] ${message}`);
2207
+ } catch {}
2208
+ };
2209
+ let creatingSession = null;
2210
+ let lastAutoCreated = null;
2211
+ const resolveGoalSession = async () => {
2212
+ const active = activeSessionID();
2213
+ if (active)
2214
+ return active;
2215
+ const directory = context.location?.directory;
2216
+ const workspaceID = context.location?.workspaceID;
2217
+ if (!directory) {
2218
+ context.ui.toast.show({
2219
+ variant: "warning",
2220
+ title: PRODUCT_DISPLAY_NAME,
2221
+ message: "Open a session before controlling a goal."
2222
+ });
2223
+ return null;
2224
+ }
2225
+ if (lastAutoCreated && lastAutoCreated.directory === directory && lastAutoCreated.workspaceID === workspaceID) {
2226
+ return lastAutoCreated.sessionID;
2227
+ }
2228
+ if (creatingSession?.key === directory) {
2229
+ return creatingSession.promise;
2230
+ }
2231
+ const promise = (async () => {
2232
+ try {
2233
+ const created = await context.client.session.create({
2234
+ location: { directory }
2235
+ });
2236
+ const sessionID = created?.id;
2237
+ if (!sessionID)
2238
+ throw new Error("session.create returned no session id");
2239
+ const tabbed = context.ui.tabs && typeof context.ui.tabs.enabled === "function" && context.ui.tabs.enabled();
2240
+ const surfaced = tabbed ? context.ui.tabs.open(sessionID) : false;
2241
+ if (!surfaced) {
2242
+ try {
2243
+ context.ui.router.navigate({ type: "session", sessionID });
2244
+ } catch {}
2245
+ }
2246
+ lastAutoCreated = { directory, workspaceID, sessionID };
2247
+ return sessionID;
2248
+ } catch (error) {
2249
+ context.ui.toast.show({
2250
+ variant: "error",
2251
+ title: PRODUCT_DISPLAY_NAME,
2252
+ message: `Could not open a session: ${error instanceof Error ? error.message : String(error)}`
2253
+ });
2254
+ return null;
2255
+ }
2256
+ })();
2257
+ creatingSession = { key: directory, promise };
2258
+ try {
2259
+ return await promise;
2260
+ } finally {
2261
+ if (creatingSession?.key === directory)
2262
+ creatingSession = null;
2263
+ }
2264
+ };
2265
+ const activeWatchdogs = new Map;
2266
+ const degraded = createDegradedModeDetector();
2267
+ const armWatchdog = (sessionID, command, timeoutMs = 15000) => {
2268
+ const rootCommand = command.trim().split(/\s+/)[0];
2269
+ const key = `${sessionID}:${rootCommand}`;
2270
+ const existing = activeWatchdogs.get(key);
2271
+ if (existing) {
2272
+ clearTimeout(existing.timer);
2273
+ }
2274
+ const timer = setTimeout(() => {
2275
+ activeWatchdogs.delete(key);
2276
+ context.ui.toast.show({
2277
+ variant: "warning",
2278
+ title: PRODUCT_DISPLAY_NAME,
2279
+ message: degraded.checkDispatch() ?? watchdogTimeoutMessage("v2", command, timeoutMs),
2280
+ duration: 8000
2281
+ });
2282
+ }, timeoutMs);
2283
+ activeWatchdogs.set(key, { timer, command, sessionID });
2284
+ };
2285
+ const disarmWatchdogs = (sessionID) => {
2286
+ for (const [key, w] of activeWatchdogs.entries()) {
2287
+ if (w.sessionID === sessionID) {
2288
+ clearTimeout(w.timer);
2289
+ activeWatchdogs.delete(key);
2290
+ }
2291
+ }
2292
+ };
2293
+ const eagerHydrateDir = opts.workspaceDirectory ?? context.location?.directory;
2294
+ if (eagerHydrateDir) {
2295
+ hydrateStoreFromDisk(store, eagerHydrateDir, undefined, opts.stateRoot).catch(() => {});
2296
+ }
2297
+ const lastHydration = {
2298
+ count: 0
2299
+ };
2300
+ const resolveWorkspaceDir = async () => {
2301
+ const evidence = [];
2302
+ if (opts.workspaceDirectory)
2303
+ return opts.workspaceDirectory;
2304
+ const direct = context.location?.directory;
2305
+ if (direct)
2306
+ return direct;
2307
+ evidence.push("reactive-location:none");
2308
+ try {
2309
+ const client = context.client;
2310
+ const locOut = await client.location?.get?.();
2311
+ const locDir = unwrapDirectory(locOut);
2312
+ if (locDir)
2313
+ return locDir;
2314
+ evidence.push(`location.get=${JSON.stringify(locOut)?.slice(0, 120) ?? "undefined"}`);
2315
+ } catch (err) {
2316
+ evidence.push(`location.get=threw:${err instanceof Error ? err.message : String(err)}`.slice(0, 140));
2317
+ }
2318
+ const sid = activeSessionID();
2319
+ if (sid) {
2320
+ try {
2321
+ const sessOut = await context.client.session?.get?.({ sessionID: sid });
2322
+ const sessDir = unwrapDirectory(sessOut);
2323
+ if (sessDir)
2324
+ return sessDir;
2325
+ evidence.push(`session.get=${JSON.stringify(sessOut)?.slice(0, 120) ?? "undefined"}`);
2326
+ } catch (err) {
2327
+ evidence.push(`session.get=threw:${err instanceof Error ? err.message : String(err)}`.slice(0, 140));
2328
+ }
2329
+ } else {
2330
+ evidence.push("no-active-session");
2331
+ }
2332
+ lastHydration.evidence = evidence.join(" | ");
2333
+ return;
2334
+ };
2335
+ const ensureHydrated = async () => {
2336
+ let lastDir;
2337
+ let lastCount = -1;
2338
+ for (let attempt = 0;attempt < 8; attempt++) {
2339
+ const dir = await resolveWorkspaceDir();
2340
+ lastDir = dir;
2341
+ if (dir) {
2342
+ await hydrateStoreFromDisk(store, dir, undefined, opts.stateRoot).catch(() => {});
2343
+ lastCount = store.getAllSnapshots().length;
2344
+ if (lastCount > 0) {
2345
+ lastHydration.dir = dir;
2346
+ lastHydration.count = lastCount;
2347
+ return;
2348
+ }
2349
+ }
2350
+ await new Promise((r) => setTimeout(r, 350));
2351
+ }
2352
+ lastHydration.dir = lastDir;
2353
+ lastHydration.count = Math.max(lastCount, 0);
2354
+ log("info", `hydration exhausted: dir=${lastDir ?? "unresolved"} snapshots=${Math.max(lastCount, 0)}`);
2355
+ };
2356
+ const sendGoalCommand = async (command, opts) => {
2357
+ const sessionID = await resolveGoalSession();
2358
+ if (!sessionID)
2359
+ return;
2360
+ try {
2361
+ const directive = `[${PRODUCT_DISPLAY_NAME}] Execute the following goal command by calling the ` + "`goal-command` tool exactly once, passing its `subcommand` parameter " + `verbatim as the single argument:
2362
+
2363
+ ${command}
2364
+
2365
+ ` + "Do not ask for confirmation, do not summarize or describe the action, " + "and do not perform any other work. Call the tool now and reply with " + "only its returned output.";
2366
+ await context.client.session.synthetic({
2367
+ sessionID,
2368
+ text: directive,
2369
+ description: `${PRODUCT_DISPLAY_NAME}: ${command}`
2370
+ });
2371
+ armWatchdog(sessionID, command, opts?.timeoutMs);
2372
+ context.ui.toast.show({
2373
+ variant: "info",
2374
+ title: PRODUCT_DISPLAY_NAME,
2375
+ message: opts?.label ?? outcomeNeutralLabel(command)
2376
+ });
2377
+ } catch (error) {
2378
+ lastAutoCreated = null;
2379
+ context.ui.toast.show({
2380
+ variant: "error",
2381
+ title: PRODUCT_DISPLAY_NAME,
2382
+ message: `Command failed: ${error instanceof Error ? error.message : String(error)}`
2383
+ });
2384
+ }
2385
+ };
2386
+ const dashboardRouteName = "goal-dashboard";
2387
+ const dashboardSections = () => {
2388
+ const sid = dashboardSessionID ?? activeSessionID();
2389
+ let snaps = sid ? store.getSnapshots(sid) : [];
2390
+ if (snaps.length === 0) {
2391
+ snaps = store.getAllSnapshots();
2392
+ }
2393
+ const sections = formatGoalStatusDashboard(snaps, sid ?? null);
2394
+ if (snaps.length === 0) {
2395
+ sections.push({
2396
+ title: "Hydration",
2397
+ text: `No goals found on disk for this workspace${lastHydration.dir ? ` (checked ${lastHydration.dir})` : " (workspace location not resolved yet)"}.`
2398
+ });
2399
+ if (opts.logLevel === "debug") {
2400
+ log("debug", `hydration evidence: dir=${lastHydration.dir ?? "unresolved"} snapshots=${lastHydration.count}${lastHydration.evidence ? ` ${lastHydration.evidence}` : ""}`);
2401
+ }
2402
+ }
2403
+ return sections;
2404
+ };
2405
+ const dashboardFooter = (targetSessionID) => dashboardFooterText(resolveFocusedGoalId(store, targetSessionID()), chord("d"), chord("p"), chord("r"), chord("c"), "esc");
2406
+ let dashboardRouteDispose = null;
2407
+ try {
2408
+ dashboardRouteDispose = context.ui.router.register({
2409
+ name: dashboardRouteName,
2410
+ render: () => {
2411
+ const theme = context.theme ?? {};
2412
+ const [rev, setRev] = createSignal(0);
2413
+ const unsub = store.subscribe(() => setRev((r) => r + 1));
2414
+ onCleanup(() => {
2415
+ try {
2416
+ unsub();
2417
+ } catch {}
2418
+ });
2419
+ const sections = () => {
2420
+ rev();
2421
+ return dashboardSections();
2422
+ };
2423
+ const snapshots = () => {
2424
+ rev();
2425
+ const sid = dashboardSession();
2426
+ let snaps = sid ? store.getSnapshots(sid) : [];
2427
+ if (snaps.length === 0)
2428
+ snaps = store.getAllSnapshots();
2429
+ return snaps;
2430
+ };
2431
+ const focusedGoalId = () => {
2432
+ rev();
2433
+ const sid = dashboardSession();
2434
+ return resolveFocusedGoalId(store, sid ?? null);
2435
+ };
2436
+ const viewSessionID = () => {
2437
+ rev();
2438
+ return dashboardSession();
2439
+ };
2440
+ const hydrationText = () => {
2441
+ const s = sections();
2442
+ return s.length === 0 ? `No goals found on disk for this workspace${lastHydration.dir ? ` (checked ${lastHydration.dir})` : ""}.` : undefined;
2443
+ };
2444
+ return DashboardRoute({
2445
+ sections,
2446
+ snapshots,
2447
+ activeSessionID: viewSessionID,
2448
+ focusedGoalId,
2449
+ onSelectGoal: (goalId) => {
2450
+ const sid = activeSessionID();
2451
+ if (sid)
2452
+ store.getFocused(sid);
2453
+ sendGoalCommand(`focus ${goalId}`);
2454
+ },
2455
+ ...dashboardGoalActions(store, dashboardSession, (c) => void sendGoalCommand(c)),
2456
+ onFocus: (goalId) => {
2457
+ sendGoalCommand(`focus ${goalId}`);
2458
+ },
2459
+ onClose: () => {
2460
+ dashboardOpen = false;
2461
+ dashboardSessionID = null;
2462
+ try {
2463
+ context.ui.router.navigate({ type: "home" });
2464
+ } catch {}
2465
+ },
2466
+ theme,
2467
+ footer: dashboardFooter(dashboardSession),
2468
+ hydrationText: hydrationText()
2469
+ });
2470
+ }
2471
+ });
2472
+ } catch {
2473
+ dashboardRouteDispose = null;
2474
+ }
2475
+ let dashboardGeneration = 0;
2476
+ let dashboardOpen = false;
2477
+ let dashboardSessionID = null;
2478
+ let dashboardUnsubscribe = null;
2479
+ const isDashboardRouteActive = () => {
2480
+ try {
2481
+ const cur = context.ui.router.current();
2482
+ return cur?.type === "plugin" && cur?.name === dashboardRouteName;
2483
+ } catch {
2484
+ return false;
2485
+ }
2486
+ };
2487
+ const dashboardSession = () => (isDashboardRouteActive() && dashboardSessionID ? dashboardSessionID : activeSessionID()) ?? null;
2488
+ const repaintDashboard = () => {
2489
+ if (!dashboardOpen)
2490
+ return;
2491
+ const generation = ++dashboardGeneration;
2492
+ const theme = context.theme ?? {};
2493
+ const renderContent = () => DashboardRoute({
2494
+ sections: dashboardSections,
2495
+ snapshots: () => {
2496
+ const s = dashboardSessionID ?? activeSessionID();
2497
+ let snaps = s ? store.getSnapshots(s) : [];
2498
+ if (snaps.length === 0)
2499
+ snaps = store.getAllSnapshots();
2500
+ return snaps;
2501
+ },
2502
+ focusedGoalId: () => {
2503
+ const s = dashboardSessionID ?? activeSessionID();
2504
+ return resolveFocusedGoalId(store, s ?? null);
2505
+ },
2506
+ activeSessionID: dashboardSession,
2507
+ onSelectGoal: (goalId) => {
2508
+ sendGoalCommand(`focus ${goalId}`);
2509
+ },
2510
+ ...dashboardGoalActions(store, () => dashboardSessionID ?? activeSessionID(), (c) => void sendGoalCommand(c)),
2511
+ onFocus: (goalId) => {
2512
+ sendGoalCommand(`focus ${goalId}`);
2513
+ },
2514
+ onClose: () => {
2515
+ dashboardOpen = false;
2516
+ dashboardSessionID = null;
2517
+ if (dashboardUnsubscribe) {
2518
+ try {
2519
+ dashboardUnsubscribe();
2520
+ } catch {}
2521
+ dashboardUnsubscribe = null;
2522
+ }
2523
+ try {
2524
+ context.ui.dialog.clear();
2525
+ } catch {}
2526
+ },
2527
+ theme,
2528
+ footer: dashboardFooter(() => dashboardSessionID ?? activeSessionID()),
2529
+ hydrationText: store.getAllSnapshots().length === 0 ? `No goals found on disk for this workspace${lastHydration.dir ? ` (checked ${lastHydration.dir})` : ""}.` : undefined
2530
+ });
2531
+ const onClose = () => {
2532
+ if (generation === dashboardGeneration) {
2533
+ dashboardOpen = false;
2534
+ dashboardSessionID = null;
2535
+ if (dashboardUnsubscribe) {
2536
+ try {
2537
+ dashboardUnsubscribe();
2538
+ } catch {}
2539
+ dashboardUnsubscribe = null;
2540
+ }
2541
+ }
2542
+ };
2543
+ try {
2544
+ context.ui.dialog.set({ size: "xlarge" });
2545
+ } catch {}
2546
+ context.ui.dialog.show(renderContent, onClose);
2547
+ };
2548
+ const renderDashboard = async () => {
2549
+ const sid = activeSessionID();
2550
+ if (sid && store.getSnapshots(sid).length === 0 || !sid && store.getAllSnapshots().length === 0) {
2551
+ await ensureHydrated();
2552
+ }
2553
+ dashboardOpen = true;
2554
+ dashboardSessionID = sid;
2555
+ repaintDashboard();
2556
+ if (dashboardUnsubscribe) {
2557
+ try {
2558
+ dashboardUnsubscribe();
2559
+ } catch {}
2560
+ }
2561
+ dashboardUnsubscribe = store.subscribe((event) => {
2562
+ if (!dashboardOpen)
2563
+ return;
2564
+ const targetSid = dashboardSessionID ?? activeSessionID();
2565
+ if (targetSid && event.sessionID !== targetSid)
2566
+ return;
2567
+ repaintDashboard();
2568
+ });
2569
+ };
2570
+ const keymapDispatch = async (targeted, bare) => {
2571
+ const sid = dashboardSession();
2572
+ if (sid === null) {
2573
+ await sendGoalCommand(bare);
2574
+ return;
2575
+ }
2576
+ const goalId = resolveFocusedGoalId(store, sid);
2577
+ if (goalId === null)
2578
+ return;
2579
+ await sendGoalCommand(targeted(goalId));
2580
+ };
2581
+ const keymapPromptThen = async (verb, prompt) => {
2582
+ const sid = dashboardSession();
2583
+ const goalId = sid === null ? null : resolveFocusedGoalId(store, sid);
2584
+ if (sid !== null && goalId === null)
2585
+ return;
2586
+ const operand = await prompt();
2587
+ if (!operand)
2588
+ return;
2589
+ await sendGoalCommand(goalId === null ? `${verb} ${operand}` : `${verb} ${goalId} ${operand}`);
2590
+ };
2591
+ context.keymap.layer(() => ({
2592
+ commands: [
2593
+ {
2594
+ id: "fixate-on.dashboard",
2595
+ title: `${PRODUCT_DISPLAY_NAME}: Dashboard`,
2596
+ description: "Open the live goal dashboard",
2597
+ group: PRODUCT_DISPLAY_NAME,
2598
+ palette: true,
2599
+ bind: chord("d"),
2600
+ run: async () => {
2601
+ await renderDashboard();
2602
+ }
2603
+ },
2604
+ {
2605
+ id: "fixate-on.pause",
2606
+ title: `${PRODUCT_DISPLAY_NAME}: Pause Goal`,
2607
+ description: "Pause the active goal",
2608
+ group: PRODUCT_DISPLAY_NAME,
2609
+ palette: true,
2610
+ bind: chord("p"),
2611
+ run: async () => {
2612
+ await keymapDispatch((id) => `pause ${id}`, "pause");
2613
+ }
2614
+ },
2615
+ {
2616
+ id: "fixate-on.resume",
2617
+ title: `${PRODUCT_DISPLAY_NAME}: Resume Goal`,
2618
+ description: "Resume a paused goal",
2619
+ group: PRODUCT_DISPLAY_NAME,
2620
+ palette: true,
2621
+ bind: chord("r"),
2622
+ run: async () => {
2623
+ await keymapDispatch((id) => `resume ${id}`, "resume");
2624
+ }
2625
+ },
2626
+ {
2627
+ id: "fixate-on.clear",
2628
+ title: `${PRODUCT_DISPLAY_NAME}: Clear Goals`,
2629
+ description: "Clear active goal(s)",
2630
+ group: PRODUCT_DISPLAY_NAME,
2631
+ palette: true,
2632
+ bind: chord("c"),
2633
+ run: async () => {
2634
+ await keymapDispatch((id) => `clear ${id}`, "clear");
2635
+ }
2636
+ },
2637
+ {
2638
+ id: "fixate-on.list",
2639
+ title: `${PRODUCT_DISPLAY_NAME}: List Goals`,
2640
+ description: "List all active and archived goals",
2641
+ group: PRODUCT_DISPLAY_NAME,
2642
+ palette: true,
2643
+ run: async () => {
2644
+ await sendGoalCommand("list");
2645
+ }
2646
+ },
2647
+ {
2648
+ id: "fixate-on.history",
2649
+ title: `${PRODUCT_DISPLAY_NAME}: Show History`,
2650
+ description: "Show goal history and transition log",
2651
+ group: PRODUCT_DISPLAY_NAME,
2652
+ palette: true,
2653
+ run: async () => {
2654
+ await sendGoalCommand("history");
2655
+ }
2656
+ },
2657
+ {
2658
+ id: "fixate-on.edit",
2659
+ title: `${PRODUCT_DISPLAY_NAME}: Edit Objective`,
2660
+ description: "Edit objective of the active goal",
2661
+ group: PRODUCT_DISPLAY_NAME,
2662
+ palette: true,
2663
+ bind: chord("e"),
2664
+ run: async () => {
2665
+ await keymapPromptThen("edit", () => context.ui.dialog.prompt({
2666
+ title: "Edit Goal",
2667
+ placeholder: "Updated objective"
2668
+ }));
2669
+ }
2670
+ },
2671
+ {
2672
+ id: "fixate-on.checkpoint",
2673
+ title: `${PRODUCT_DISPLAY_NAME}: Save Checkpoint`,
2674
+ description: "Save a checkpoint for the active goal",
2675
+ group: PRODUCT_DISPLAY_NAME,
2676
+ palette: true,
2677
+ bind: chord("k"),
2678
+ run: async () => {
2679
+ await keymapPromptThen("checkpoint", () => context.ui.dialog.prompt({
2680
+ title: "Save Checkpoint",
2681
+ placeholder: "Checkpoint summary"
2682
+ }));
2683
+ }
2684
+ },
2685
+ {
2686
+ id: "fixate-on.focus",
2687
+ title: `${PRODUCT_DISPLAY_NAME}: Focus Goal`,
2688
+ description: "Focus a specific goal in the session",
2689
+ group: PRODUCT_DISPLAY_NAME,
2690
+ palette: true,
2691
+ bind: chord("f"),
2692
+ run: async () => {
2693
+ const sid = activeSessionID();
2694
+ let goals = sid ? store.getSnapshots(sid) : [];
2695
+ if (goals.length === 0 && sid) {
2696
+ await ensureHydrated();
2697
+ goals = store.getSnapshots(sid);
2698
+ }
2699
+ if (goals.length === 0) {
2700
+ context.ui.toast.show({
2701
+ variant: "warning",
2702
+ title: PRODUCT_DISPLAY_NAME,
2703
+ message: "No active goals to focus."
2704
+ });
2705
+ return;
2706
+ }
2707
+ const goalId = await context.ui.dialog.select({
2708
+ title: "Focus Goal",
2709
+ options: goals.map((g, idx) => ({
2710
+ title: `${idx + 1}. ${g.condition}`,
2711
+ value: g.goalId,
2712
+ description: `Status: ${g.status}`
2713
+ }))
2714
+ });
2715
+ if (goalId) {
2716
+ await sendGoalCommand(`focus ${goalId}`);
2717
+ }
2718
+ }
2719
+ },
2720
+ {
2721
+ id: "fixate-on.add",
2722
+ title: `${PRODUCT_DISPLAY_NAME}: Add Goal`,
2723
+ description: "Add a new goal to the session",
2724
+ group: PRODUCT_DISPLAY_NAME,
2725
+ palette: true,
2726
+ bind: chord("a"),
2727
+ run: async () => {
2728
+ const obj = await context.ui.dialog.prompt({
2729
+ title: "Add New Goal",
2730
+ placeholder: "New goal objective"
2731
+ });
2732
+ if (obj) {
2733
+ await sendGoalCommand(`add ${obj}`);
2734
+ }
2735
+ }
2736
+ },
2737
+ {
2738
+ id: "fixate-on.sequence",
2739
+ title: `${PRODUCT_DISPLAY_NAME}: Start Sequence`,
2740
+ description: "Start an ordered sequence of goals",
2741
+ group: PRODUCT_DISPLAY_NAME,
2742
+ palette: true,
2743
+ run: async () => {
2744
+ const t = await context.ui.dialog.prompt({
2745
+ title: "Start Goal Sequence",
2746
+ placeholder: "Objective 1; Objective 2; Objective 3"
2747
+ });
2748
+ if (t) {
2749
+ await sendGoalCommand(`sequence ${t}`);
2750
+ }
2751
+ }
2752
+ },
2753
+ {
2754
+ id: "fixate-on.handback",
2755
+ title: `${PRODUCT_DISPLAY_NAME}: Handback Deliverables`,
2756
+ description: "Generate reviewable diff and handback deliverables",
2757
+ group: PRODUCT_DISPLAY_NAME,
2758
+ palette: true,
2759
+ bind: chord("h"),
2760
+ run: async () => {
2761
+ await sendGoalCommand("handback");
2762
+ }
2763
+ },
2764
+ {
2765
+ id: "fixate-on.review-payload",
2766
+ title: `${PRODUCT_DISPLAY_NAME}: External Review Payload`,
2767
+ description: "Generate paste-ready external review payload",
2768
+ group: PRODUCT_DISPLAY_NAME,
2769
+ palette: true,
2770
+ run: async () => {
2771
+ await sendGoalCommand("review-payload");
2772
+ }
2773
+ }
2774
+ ]
2775
+ }));
2776
+ log("info", "TUI companion initialized (v2) \u2014 subscribing to goal events.");
2777
+ const events = wireV2Events({
2778
+ context,
2779
+ store,
2780
+ stateRoot: opts.stateRoot,
2781
+ resolveWorkspaceDir,
2782
+ ensureHydrated,
2783
+ disarmWatchdogs,
2784
+ dashboardRouteDispose,
2785
+ activeWatchdogs,
2786
+ log
2787
+ });
2788
+ return () => {
2789
+ events.dispose();
2790
+ };
2791
+ }
2792
+ };
2793
+ var tui_v2_default = GoalTuiPluginV2;
2794
+ export {
2795
+ GoalTuiPluginV2,
2796
+ tui_v2_default as default
2797
+ };