@narumitw/pi-starship 0.59.1 → 0.60.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.
@@ -2,21 +2,519 @@
2
2
  // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  BUILT_IN_EXAMPLE,
5
+ ConfigPublicationError,
5
6
  MODULE_DEFINITIONS,
6
7
  STARSHIP_SUBCOMMANDS,
8
+ assertConfigDocumentUnchanged,
7
9
  atomicRestoreConfigDocument,
8
10
  atomicSaveConfigDocument,
9
11
  completeStarshipArguments,
10
12
  inspectUnavailableModules,
11
13
  loadStarshipConfig,
14
+ readConfigDocumentSnapshot,
12
15
  removeConfigDocumentIfMatches,
13
16
  validateConfigDocument
14
- } from "./chunk-MTFSZ63Q.ts";
17
+ } from "./chunk-KZZKGGFW.ts";
15
18
 
16
19
  // src/commands.ts
17
- import { defineMenu as defineMenu2, runMenu as runMenu2 } from "@narumitw/pi-tui-kit";
20
+ import { isKeyRelease as isKeyRelease2, Key as Key3, matchesKey as matchesKey3 } from "@earendil-works/pi-tui";
21
+ import { defineMenu as defineMenu3, runMenu as runMenu3 } from "@narumitw/pi-tui-kit";
22
+
23
+ // src/command-commit.ts
24
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
25
+
26
+ // src/profile-store.ts
27
+ import { randomUUID } from "node:crypto";
28
+ import {
29
+ closeSync,
30
+ constants,
31
+ fstatSync,
32
+ fsyncSync,
33
+ lstatSync,
34
+ mkdirSync,
35
+ openSync,
36
+ readdirSync,
37
+ readFileSync,
38
+ realpathSync,
39
+ renameSync,
40
+ rmdirSync,
41
+ unlinkSync,
42
+ writeFileSync
43
+ } from "node:fs";
44
+ import { basename, dirname, join, parse, resolve, sep } from "node:path";
45
+ var HISTORY_NAME = /^(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.\d{3}Z)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.toml$/u;
46
+ var LEGACY_NAME = /^pi-starship-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\.toml$/u;
47
+ var RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$|clock\$)(?:\.|$)/iu;
48
+ function normalizeProfileName(value) {
49
+ const name = value.normalize("NFC");
50
+ if ([...name].length < 1 || [...name].length > 80 || name !== name.trim() || name.startsWith(".") || name.endsWith(".") || /[\p{Cc}\p{Cf}\p{Cs}<>:"/\\|?*]/u.test(name) || RESERVED_NAME.test(name) || Buffer.byteLength(`${name}.toml`, "utf8") > 255) {
51
+ throw new Error("Invalid profile name: use 1\u201380 characters without controls, path characters, or reserved names");
52
+ }
53
+ return name;
54
+ }
55
+ function trustedDirectory(path) {
56
+ try {
57
+ return realpathSync(path);
58
+ } catch (error) {
59
+ if (!isMissing(error)) throw error;
60
+ const parent = dirname(path);
61
+ if (parent === path) throw error;
62
+ return join(trustedDirectory(parent), basename(path));
63
+ }
64
+ }
65
+ function rootPath(settingsPath) {
66
+ return join(trustedDirectory(dirname(resolve(settingsPath))), "pi-starship");
67
+ }
68
+ function profileDirectory(settingsPath) {
69
+ return join(rootPath(settingsPath), "profiles");
70
+ }
71
+ function historyDirectory(settingsPath) {
72
+ return join(rootPath(settingsPath), "history");
73
+ }
74
+ function isMissing(error) {
75
+ return error.code === "ENOENT";
76
+ }
77
+ function statIfPresent(path) {
78
+ try {
79
+ return lstatSync(path, { bigint: true });
80
+ } catch (error) {
81
+ if (isMissing(error)) return void 0;
82
+ throw error;
83
+ }
84
+ }
85
+ function checkedDirectory(path, create = false) {
86
+ const absolute = resolve(path);
87
+ const root = parse(absolute).root;
88
+ let current3 = root;
89
+ for (const part of absolute.slice(root.length).split(sep).filter(Boolean)) {
90
+ current3 = join(current3, part);
91
+ let stat = statIfPresent(current3);
92
+ let created = false;
93
+ if (!stat && create) {
94
+ try {
95
+ mkdirSync(current3, { mode: 448 });
96
+ } catch (error) {
97
+ if (error.code !== "EEXIST") throw error;
98
+ }
99
+ stat = statIfPresent(current3);
100
+ created = true;
101
+ }
102
+ if (!stat) return false;
103
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Not a safe directory: ${current3}`);
104
+ if (created) flushDirectory(dirname(current3));
105
+ }
106
+ return true;
107
+ }
108
+ function identity(stat) {
109
+ return Object.freeze({ dev: stat.dev, ino: stat.ino, size: stat.size, mtimeNs: stat.mtimeNs, ctimeNs: stat.ctimeNs });
110
+ }
111
+ function sameIdentity(left, right) {
112
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
113
+ }
114
+ function sameFile(left, right) {
115
+ return left.dev === right.dev && left.ino === right.ino;
116
+ }
117
+ function encodeDocument(rawDocument) {
118
+ const bytes = Buffer.from(rawDocument, "utf8");
119
+ if (bytes.toString("utf8") !== rawDocument) throw new Error("Document is not lossless UTF-8 text");
120
+ return bytes;
121
+ }
122
+ function readBytes(path) {
123
+ if (!checkedDirectory(dirname(path))) throw new Error(`Document directory is missing: ${dirname(path)}`);
124
+ const before = statIfPresent(path);
125
+ if (!before?.isFile() || before.isSymbolicLink()) throw new Error(`Not a regular document: ${path}`);
126
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
127
+ try {
128
+ const opened = fstatSync(fd, { bigint: true });
129
+ if (!opened.isFile() || !sameIdentity(identity(before), identity(opened))) {
130
+ throw new Error(`Document changed while opening: ${path}`);
131
+ }
132
+ const bytes = readFileSync(fd);
133
+ const after = fstatSync(fd, { bigint: true });
134
+ const published = statIfPresent(path);
135
+ if (!sameIdentity(identity(opened), identity(after)) || !published || !sameIdentity(identity(after), identity(published))) {
136
+ throw new Error(`Document changed while reading: ${path}`);
137
+ }
138
+ return { rawBytes: bytes, identity: identity(after) };
139
+ } finally {
140
+ closeSync(fd);
141
+ }
142
+ }
143
+ function readProfile(settingsPath, name) {
144
+ const normalized = normalizeProfileName(name);
145
+ const path = join(profileDirectory(settingsPath), `${normalized}.toml`);
146
+ const document = readBytes(path);
147
+ const decoded = document.rawBytes.toString("utf8");
148
+ const valid = Buffer.from(decoded, "utf8").equals(document.rawBytes);
149
+ return Object.freeze({
150
+ kind: "profile",
151
+ name: normalized,
152
+ path,
153
+ ...document,
154
+ rawDocument: valid ? decoded : void 0,
155
+ ...valid ? {} : { readError: "Profile document is not valid UTF-8; raw bytes are preserved" }
156
+ });
157
+ }
158
+ function listProfiles(settingsPath) {
159
+ const directory = profileDirectory(settingsPath);
160
+ if (!checkedDirectory(directory)) return [];
161
+ const profiles = [];
162
+ for (const filename of readdirSync(directory).sort()) {
163
+ if (!filename.endsWith(".toml")) continue;
164
+ const name = filename.slice(0, -5);
165
+ try {
166
+ if (normalizeProfileName(name) !== name) continue;
167
+ } catch {
168
+ continue;
169
+ }
170
+ const stat = statIfPresent(join(directory, filename));
171
+ if (!stat?.isFile() || stat.isSymbolicLink()) continue;
172
+ profiles.push(readProfile(settingsPath, name));
173
+ }
174
+ return profiles;
175
+ }
176
+ function mutate(settingsPath, operation) {
177
+ const root = rootPath(settingsPath);
178
+ checkedDirectory(root, true);
179
+ const lock = join(root, ".mutation-lock");
180
+ try {
181
+ mkdirSync(lock, { mode: 448 });
182
+ } catch (error) {
183
+ if (error.code === "EEXIST") {
184
+ throw new Error(`Profile/history storage is locked; inspect the owner before manually removing ${lock}`);
185
+ }
186
+ throw error;
187
+ }
188
+ const owned = lstatSync(lock, { bigint: true });
189
+ let result;
190
+ let operationError;
191
+ let failed = false;
192
+ try {
193
+ result = operation();
194
+ } catch (error) {
195
+ failed = true;
196
+ operationError = error;
197
+ }
198
+ try {
199
+ const current3 = statIfPresent(lock);
200
+ if (current3?.isDirectory() && sameFile(identity(owned), current3)) rmdirSync(lock);
201
+ } catch (error) {
202
+ if (failed) throw new AggregateError([operationError, error], `Mutation and lock cleanup failed at ${lock}`);
203
+ throw new Error(`Mutation completed but lock cleanup failed at ${lock}`, { cause: error });
204
+ }
205
+ if (failed) throw operationError;
206
+ return result;
207
+ }
208
+ function collisionKey(name) {
209
+ return name.normalize("NFC").toUpperCase().toLowerCase().toUpperCase().toLowerCase().normalize("NFC");
210
+ }
211
+ function assertAvailable(directory, filename) {
212
+ const key = collisionKey(filename);
213
+ if (readdirSync(directory).some((entry) => collisionKey(entry) === key)) {
214
+ throw new Error(`Document name already exists: ${filename}`);
215
+ }
216
+ }
217
+ function assertExpected(current3, expected) {
218
+ if (current3.kind !== expected.kind || current3.path !== expected.path || current3.name !== expected.name || current3.rawDocument !== expected.rawDocument || !current3.rawBytes.equals(expected.rawBytes) || !sameIdentity(current3.identity, expected.identity)) {
219
+ throw new Error(`Document changed since review: ${current3.path}`);
220
+ }
221
+ }
222
+ function flushDirectory(path) {
223
+ if (process.platform === "win32") return;
224
+ checkedDirectory(path);
225
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
226
+ try {
227
+ fsyncSync(fd);
228
+ } finally {
229
+ closeSync(fd);
230
+ }
231
+ }
232
+ function flushMutation(directory, path) {
233
+ try {
234
+ flushDirectory(directory);
235
+ } catch (error) {
236
+ throw new Error(`Mutation completed at ${path}, but directory flush failed: ${String(error)}`, { cause: error });
237
+ }
238
+ }
239
+ function publish(directory, filename, bytes, beforeRename) {
240
+ const temporary = join(directory, `.tmp-${randomUUID()}`);
241
+ const fd = openSync(
242
+ temporary,
243
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
244
+ 384
245
+ );
246
+ const owned = fstatSync(fd, { bigint: true });
247
+ let open = true;
248
+ try {
249
+ writeFileSync(fd, bytes);
250
+ fsyncSync(fd);
251
+ closeSync(fd);
252
+ open = false;
253
+ checkedDirectory(directory);
254
+ beforeRename();
255
+ const destination = join(directory, filename);
256
+ renameSync(temporary, destination);
257
+ flushMutation(directory, destination);
258
+ } finally {
259
+ try {
260
+ if (open) closeSync(fd);
261
+ } finally {
262
+ const current3 = statIfPresent(temporary);
263
+ if (current3 && sameFile(identity(owned), current3)) unlinkSync(temporary);
264
+ }
265
+ }
266
+ }
267
+ function readTextProfile(settingsPath, name) {
268
+ const document = readProfile(settingsPath, name);
269
+ if (document.rawDocument === void 0) throw new Error(document.readError);
270
+ return { ...document, rawDocument: document.rawDocument };
271
+ }
272
+ function createProfile(settingsPath, name, rawDocument) {
273
+ const normalized = normalizeProfileName(name);
274
+ const bytes = encodeDocument(rawDocument);
275
+ return mutate(settingsPath, () => {
276
+ const directory = profileDirectory(settingsPath);
277
+ checkedDirectory(directory, true);
278
+ const filename = `${normalized}.toml`;
279
+ assertAvailable(directory, filename);
280
+ publish(directory, filename, bytes, () => assertAvailable(directory, filename));
281
+ return readTextProfile(settingsPath, normalized);
282
+ });
283
+ }
284
+ function duplicateProfile(settingsPath, name, newName, expected) {
285
+ const normalized = normalizeProfileName(newName);
286
+ return mutate(settingsPath, () => {
287
+ const current3 = readProfile(settingsPath, name);
288
+ assertExpected(current3, expected);
289
+ const directory = profileDirectory(settingsPath);
290
+ const filename = `${normalized}.toml`;
291
+ assertAvailable(directory, filename);
292
+ publish(directory, filename, current3.rawBytes, () => {
293
+ assertExpected(readProfile(settingsPath, name), expected);
294
+ assertAvailable(directory, filename);
295
+ });
296
+ return readProfile(settingsPath, normalized);
297
+ });
298
+ }
299
+ function saveProfile(settingsPath, name, rawDocument, expected) {
300
+ const normalized = normalizeProfileName(name);
301
+ const bytes = encodeDocument(rawDocument);
302
+ return mutate(settingsPath, () => {
303
+ const current3 = readProfile(settingsPath, normalized);
304
+ assertExpected(current3, expected);
305
+ if (current3.rawDocument === rawDocument) return { ...current3, rawDocument };
306
+ publish(profileDirectory(settingsPath), `${normalized}.toml`, bytes, () => {
307
+ assertExpected(readProfile(settingsPath, normalized), expected);
308
+ });
309
+ return readTextProfile(settingsPath, normalized);
310
+ });
311
+ }
312
+ function renameProfile(settingsPath, name, newName, expected) {
313
+ const normalized = normalizeProfileName(newName);
314
+ return mutate(settingsPath, () => {
315
+ const current3 = readProfile(settingsPath, name);
316
+ assertExpected(current3, expected);
317
+ if (current3.name === normalized) return current3;
318
+ if (collisionKey(current3.name) === collisionKey(normalized))
319
+ throw new Error("Case-only profile rename is not supported");
320
+ const directory = profileDirectory(settingsPath);
321
+ assertAvailable(directory, `${normalized}.toml`);
322
+ assertExpected(readProfile(settingsPath, name), expected);
323
+ const destination = join(directory, `${normalized}.toml`);
324
+ renameSync(current3.path, destination);
325
+ flushMutation(directory, destination);
326
+ return readProfile(settingsPath, normalized);
327
+ });
328
+ }
329
+ function deleteProfile(settingsPath, name, expected) {
330
+ mutate(settingsPath, () => {
331
+ const current3 = readProfile(settingsPath, name);
332
+ assertExpected(current3, expected);
333
+ unlinkSync(current3.path);
334
+ flushMutation(dirname(current3.path), current3.path);
335
+ });
336
+ }
337
+ function assertTimestamp(value) {
338
+ const time = Date.parse(value);
339
+ if (!Number.isFinite(time) || new Date(time).toISOString() !== value) throw new Error("Invalid history timestamp");
340
+ }
341
+ function historyLocation(settingsPath, name) {
342
+ const modern = HISTORY_NAME.exec(name);
343
+ if (modern) {
344
+ const createdAt = modern[1].replace(/T(\d{2})-(\d{2})-(\d{2})/u, "T$1:$2:$3");
345
+ assertTimestamp(createdAt);
346
+ return { path: join(historyDirectory(settingsPath), name), legacy: false, createdAt };
347
+ }
348
+ const legacy = LEGACY_NAME.exec(name);
349
+ if (legacy) {
350
+ const createdAt = `${legacy[1]}-${legacy[2]}-${legacy[3]}T${legacy[4]}:${legacy[5]}`;
351
+ assertTimestamp(`${createdAt}:00.000Z`);
352
+ return { path: join(rootPath(settingsPath), name), legacy: true, createdAt };
353
+ }
354
+ throw new Error("Invalid history filename");
355
+ }
356
+ function readHistory(settingsPath, name) {
357
+ const location = historyLocation(settingsPath, name);
358
+ const document = readBytes(location.path);
359
+ const decoded = document.rawBytes.toString("utf8");
360
+ const valid = Buffer.from(decoded, "utf8").equals(document.rawBytes);
361
+ return Object.freeze({
362
+ kind: "history",
363
+ name,
364
+ ...location,
365
+ ...document,
366
+ rawDocument: valid ? decoded : void 0,
367
+ ...valid ? {} : { readError: "Recovery document is not valid UTF-8; raw bytes are preserved" }
368
+ });
369
+ }
370
+ function listHistory(settingsPath) {
371
+ const history = [];
372
+ for (const [directory, pattern] of [
373
+ [historyDirectory(settingsPath), HISTORY_NAME],
374
+ [rootPath(settingsPath), LEGACY_NAME]
375
+ ]) {
376
+ if (!checkedDirectory(directory)) continue;
377
+ for (const name of readdirSync(directory).sort()) {
378
+ if (!pattern.test(name)) continue;
379
+ try {
380
+ historyLocation(settingsPath, name);
381
+ } catch (error) {
382
+ if (error instanceof Error && error.message === "Invalid history timestamp") continue;
383
+ throw error;
384
+ }
385
+ const stat = statIfPresent(join(directory, name));
386
+ if (!stat?.isFile() || stat.isSymbolicLink()) continue;
387
+ history.push(readHistory(settingsPath, name));
388
+ }
389
+ }
390
+ return history.sort(
391
+ (left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt) || left.name.localeCompare(right.name)
392
+ );
393
+ }
394
+ function archiveConfigDocument(settingsPath, rawDocument) {
395
+ const bytes = typeof rawDocument === "string" ? encodeDocument(rawDocument) : Buffer.from(rawDocument);
396
+ return mutate(settingsPath, () => {
397
+ const directory = historyDirectory(settingsPath);
398
+ checkedDirectory(directory, true);
399
+ const name = `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/gu, "-")}-${randomUUID()}.toml`;
400
+ publish(directory, name, bytes, () => assertAvailable(directory, name));
401
+ return Object.freeze({ name, path: join(directory, name) });
402
+ });
403
+ }
404
+ function deleteHistory(settingsPath, name, expected) {
405
+ if (historyLocation(settingsPath, name).legacy) throw new Error("Legacy recovery files are read-only");
406
+ mutate(settingsPath, () => {
407
+ const current3 = readHistory(settingsPath, name);
408
+ assertExpected(current3, expected);
409
+ unlinkSync(current3.path);
410
+ flushMutation(dirname(current3.path), current3.path);
411
+ });
412
+ }
413
+
414
+ // src/command-commit.ts
415
+ function captureCommitExpectation(options) {
416
+ return {
417
+ previous: options.getLoaded(),
418
+ revision: options.getLoadedRevision?.(),
419
+ disk: readConfigDocumentSnapshot(options.settingsPath)
420
+ };
421
+ }
422
+ function commitOwnerCurrent(options, owner, expected) {
423
+ const loaded = options.getLoaded();
424
+ return !owner.signal.aborted && owner.isCurrent() && loaded.rawDocument === expected.previous.rawDocument && loaded.source === expected.previous.source && JSON.stringify(loaded.diagnostics) === JSON.stringify(expected.previous.diagnostics) && options.getLoadedRevision?.() === expected.revision;
425
+ }
426
+ async function commitActiveDocument(ctx, options, candidate, owner, expected, allowInvalid = false, checkCandidate) {
427
+ const raw = candidate.rawDocument;
428
+ if (raw === void 0) throw new Error("The candidate settings document is unavailable");
429
+ return withFileMutationQueue(options.settingsPath, async () => {
430
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
431
+ checkCandidate?.();
432
+ assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
433
+ const previousBytes = expected.disk.rawBytes;
434
+ if (expected.previous.rawDocument !== previousBytes?.toString("utf8")) {
435
+ throw new Error(
436
+ "The active file differs from the loaded document. Reload and review it before replacing settings."
437
+ );
438
+ }
439
+ const invalid = expected.previous.diagnostics.some((item) => item.severity === "error");
440
+ if (invalid && !allowInvalid)
441
+ throw new Error("The active settings document is invalid. Use explicit repair or recovery before replacing it.");
442
+ validateConfigDocument(options.settingsPath, raw);
443
+ if (previousBytes?.equals(Buffer.from(raw))) return "applied";
444
+ let recoveryPath;
445
+ if (previousBytes !== void 0) {
446
+ recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
447
+ }
448
+ try {
449
+ assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
450
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
451
+ checkCandidate?.();
452
+ } catch (error) {
453
+ throw new Error(`${message(error)}.${recoveryNote(recoveryPath)}`);
454
+ }
455
+ let saved;
456
+ try {
457
+ saved = options.save ? options.save(options.settingsPath, raw) : atomicSaveConfigDocument(options.settingsPath, raw, {}, expected.disk);
458
+ } catch (error) {
459
+ if (error instanceof ConfigPublicationError) {
460
+ const rollback = restorePrevious(ctx, options, owner, expected, raw, error.fileIdentity, false);
461
+ throw new Error(`Footer settings were not saved: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`);
462
+ }
463
+ throw new Error(
464
+ `Footer settings were not saved: ${message(error)}. The previous footer remains active.${recoveryNote(recoveryPath)}`
465
+ );
466
+ }
467
+ try {
468
+ if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()) || options.getLoadedRevision?.() !== expected.revision) {
469
+ throw new Error("The configuration owner changed during publication");
470
+ }
471
+ options.apply(saved, ctx);
472
+ } catch (error) {
473
+ const rollback = restorePrevious(ctx, options, owner, expected, raw, saved.fileIdentity, true);
474
+ throw new Error(
475
+ `Footer settings could not be applied: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`
476
+ );
477
+ }
478
+ return "applied";
479
+ });
480
+ }
481
+ function restorePrevious(ctx, options, owner, expected, raw, identity2, restoreRuntime) {
482
+ try {
483
+ if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()))
484
+ throw new Error("The session owner changed; stale restoration was blocked");
485
+ const current3 = options.getLoaded();
486
+ if (current3.rawDocument !== expected.previous.rawDocument && current3.rawDocument !== raw) {
487
+ throw new Error("The active runtime changed; stale restoration was blocked");
488
+ }
489
+ if (!identity2) throw new Error("The saved settings document identity is unavailable");
490
+ assertConfigDocumentUnchanged(options.settingsPath, { rawBytes: Buffer.from(raw), fileIdentity: identity2 });
491
+ if (expected.disk.rawBytes === void 0) {
492
+ removeConfigDocumentIfMatches(options.settingsPath, raw, identity2);
493
+ } else if (options.restore && expected.disk.rawBytes.equals(Buffer.from(expected.previous.rawDocument ?? ""))) {
494
+ options.restore(options.settingsPath, expected.previous.rawDocument ?? "");
495
+ } else {
496
+ atomicRestoreConfigDocument(
497
+ options.settingsPath,
498
+ expected.disk.rawBytes,
499
+ {},
500
+ { rawBytes: Buffer.from(raw), fileIdentity: identity2 }
501
+ );
502
+ }
503
+ if (restoreRuntime) options.apply(expected.previous, ctx);
504
+ return "The previous configuration was restored.";
505
+ } catch (error) {
506
+ return `Restoring the previous configuration also failed: ${message(error)}. Active path: ${options.settingsPath}.`;
507
+ }
508
+ }
509
+ function recoveryNote(path) {
510
+ return path ? ` Recovery copy retained: ${path}.` : "";
511
+ }
512
+ function message(error) {
513
+ return error instanceof Error ? error.message : String(error);
514
+ }
18
515
 
19
516
  // src/command-configuration.ts
517
+ import { withFileMutationQueue as withFileMutationQueue2 } from "@earendil-works/pi-coding-agent";
20
518
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
21
519
 
22
520
  // src/command-preview.ts
@@ -1083,6 +1581,12 @@ function configurationMenuScreen(loaded) {
1083
1581
  label: "Import settings from Gist\u2026",
1084
1582
  description: "Review and preview remote TOML before replacing settings \xB7 requires gh",
1085
1583
  action: "gist-import"
1584
+ },
1585
+ {
1586
+ id: "history",
1587
+ label: "History",
1588
+ description: "Review and restore recovery copies; legacy skill backups are read-only",
1589
+ action: "history"
1086
1590
  }
1087
1591
  ],
1088
1592
  hint: "back"
@@ -1112,6 +1616,7 @@ function effectiveConfigurationScreen(loaded) {
1112
1616
  "Normalized public TOML; comments and unknown fields are intentionally excluded."
1113
1617
  ],
1114
1618
  content: serializeEffectiveConfig(loaded.config),
1619
+ enableSearch: true,
1115
1620
  format: { kind: "code", language: "toml" },
1116
1621
  viewportSize: "adaptive",
1117
1622
  hint: "back"
@@ -1125,6 +1630,7 @@ function settingsDocumentScreen(loaded, settingsPath) {
1125
1630
  title: "Settings document",
1126
1631
  lines: ["Exact loaded UTF-8 text \xB7 display controls sanitized \xB7 read-only", `Path: ${path}`],
1127
1632
  content: loaded.rawDocument,
1633
+ enableSearch: true,
1128
1634
  format: { kind: "code", language: "toml" },
1129
1635
  viewportSize: "adaptive",
1130
1636
  hint: "back"
@@ -1145,6 +1651,13 @@ async function reloadConfiguration(ctx, options, owner) {
1145
1651
  const previous = options.getLoaded();
1146
1652
  const revision = options.getLoadedRevision?.();
1147
1653
  const candidate = readReloadCandidate(options);
1654
+ let disk;
1655
+ try {
1656
+ disk = readConfigDocumentSnapshot(options.settingsPath);
1657
+ } catch (error) {
1658
+ ctx.ui.notify(`Footer reload was blocked: ${safeError(error)}`, "error");
1659
+ return "stay";
1660
+ }
1148
1661
  if (!candidate.ok) {
1149
1662
  ctx.ui.notify(`Footer reload was blocked: ${safeError(candidate.error)}`, "error");
1150
1663
  return "stay";
@@ -1169,42 +1682,58 @@ async function reloadConfiguration(ctx, options, owner) {
1169
1682
  if (selectedReloadAction(selection) !== RELOAD_ACTIONS.apply) return "stay";
1170
1683
  const confirmed = await ctx.ui.confirm(
1171
1684
  "Apply configuration from disk?",
1172
- candidate.loaded.rawDocument === void 0 ? "Use built-in defaults for this session? No settings file will be created." : "Apply the validated settings document to this session without changing its bytes?"
1685
+ candidate.loaded.rawDocument === void 0 ? "Use built-in defaults for this session? No settings file will be created." : "Apply the validated settings document to this session without changing its bytes? The previous loaded document will be kept in History.",
1686
+ { signal: owner.signal }
1173
1687
  );
1174
1688
  if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision) || !confirmed) {
1175
1689
  return "stay";
1176
1690
  }
1177
- const fresh = readReloadCandidate(options);
1178
- if (!fresh.ok) {
1179
- ctx.ui.notify(
1180
- `Footer reload was blocked after confirmation: ${safeError(fresh.error)}. The previous footer remains active.`,
1181
- "error"
1182
- );
1183
- return "stay";
1184
- }
1185
- if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
1186
- ctx.ui.notify(
1187
- "The settings document changed after preview. The previous footer remains active; reload again to review the latest version.",
1188
- "warning"
1189
- );
1190
- return "stay";
1191
- }
1691
+ let warnings = 0;
1192
1692
  try {
1193
- options.apply(fresh.loaded, ctx);
1693
+ const applied = await withFileMutationQueue2(options.settingsPath, async () => {
1694
+ if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision) || !sameLoadedDocument(previous, options.getLoaded()))
1695
+ return false;
1696
+ assertConfigDocumentUnchanged(options.settingsPath, disk);
1697
+ const fresh = readReloadCandidate(options);
1698
+ if (!fresh.ok) throw new Error(fresh.error);
1699
+ if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
1700
+ throw new Error(
1701
+ "The settings document changed after preview. The previous footer remains active; reload again to review the latest version."
1702
+ );
1703
+ }
1704
+ let recoveryPath;
1705
+ const previousBytes = previous.rawBytes ?? previous.rawDocument;
1706
+ if (previousBytes !== void 0) {
1707
+ recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
1708
+ }
1709
+ assertConfigDocumentUnchanged(options.settingsPath, disk);
1710
+ if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision)) return false;
1711
+ try {
1712
+ options.apply(fresh.loaded, ctx);
1713
+ } catch (error) {
1714
+ let rollbackError;
1715
+ try {
1716
+ if (!isCurrentOwner(owner)) throw new Error("The session owner changed; stale restoration was blocked");
1717
+ const current3 = options.getLoaded();
1718
+ if (!sameLoadedDocument(current3, previous) && !sameLoadedDocument(current3, fresh.loaded))
1719
+ throw new Error("The active runtime changed; stale restoration was blocked");
1720
+ options.apply(previous, ctx);
1721
+ } catch (rollback) {
1722
+ rollbackError = rollback;
1723
+ }
1724
+ throw new Error(
1725
+ `Footer reload failed: ${formatError(error)}. ${rollbackError ? `Restoring the previous configuration also failed: ${formatError(rollbackError)}.` : "The previous configuration was restored."}${recoveryPath ? ` Recovery copy retained: ${recoveryPath}.` : ""}`
1726
+ );
1727
+ }
1728
+ warnings = fresh.loaded.diagnostics.length;
1729
+ return true;
1730
+ });
1731
+ if (!isCurrentOwner(owner) || !applied) return "stay";
1194
1732
  } catch (error) {
1195
- let rollbackError;
1196
- try {
1197
- options.apply(previous, ctx);
1198
- } catch (rollback) {
1199
- rollbackError = rollback;
1200
- }
1201
- ctx.ui.notify(
1202
- rollbackError ? `Footer reload failed: ${safeError(error)}. Restoring the previous configuration also failed: ${safeError(rollbackError)}.` : `Footer reload failed: ${safeError(error)}. The previous configuration was restored.`,
1203
- "error"
1204
- );
1733
+ if (isCurrentOwner(owner))
1734
+ ctx.ui.notify(`Footer reload was blocked after confirmation: ${safeError(error)}`, "error");
1205
1735
  return "stay";
1206
1736
  }
1207
- const warnings = fresh.loaded.diagnostics.length;
1208
1737
  ctx.ui.notify(
1209
1738
  warnings === 0 ? "Footer configuration reloaded and applied." : `Footer configuration reloaded and applied with ${warnings} warning${warnings === 1 ? "" : "s"}.`,
1210
1739
  "info"
@@ -1342,7 +1871,7 @@ function isRecord(value) {
1342
1871
  }
1343
1872
  var executeGhApi = (args, input, signal) => {
1344
1873
  signal.throwIfAborted();
1345
- return new Promise((resolve, reject) => {
1874
+ return new Promise((resolve2, reject) => {
1346
1875
  const child = spawn(process.platform === "win32" ? "gh.exe" : "gh", ["api", "--hostname", "github.com", ...args], {
1347
1876
  env: { ...process.env, GH_PROMPT_DISABLED: "1", GH_PAGER: "", GH_DEBUG: "" },
1348
1877
  stdio: ["pipe", "pipe", "ignore"],
@@ -1383,7 +1912,7 @@ var executeGhApi = (args, input, signal) => {
1383
1912
  "Gist request failed. Check gh auth status, Gist access, and connectivity. An upload may already exist."
1384
1913
  )
1385
1914
  );
1386
- else resolve(Buffer.concat(chunks).toString("utf8"));
1915
+ else resolve2(Buffer.concat(chunks).toString("utf8"));
1387
1916
  });
1388
1917
  if (signal.aborted) onAbort();
1389
1918
  child.stdin.end(input);
@@ -1450,8 +1979,10 @@ async function importSettingsGist(ctx, options, owner, reviewImport, api) {
1450
1979
  const previous = options.getLoaded();
1451
1980
  const revision = options.getLoadedRevision?.();
1452
1981
  const disk = diskSnapshot(options);
1982
+ const initialDisk = readConfigDocumentSnapshot(options.settingsPath);
1453
1983
  const guardedOwner = {
1454
1984
  signal: owner.signal,
1985
+ isSessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
1455
1986
  isCurrent: () => current(owner) && options.getLoadedRevision?.() === revision && options.getLoaded().rawDocument === previous.rawDocument && options.getLoaded().source === previous.source
1456
1987
  };
1457
1988
  const value = await ctx.ui.input("Import pi-starship settings from Gist", "https://gist.github.com/<owner>/<id>", {
@@ -1492,7 +2023,7 @@ async function importSettingsGist(ctx, options, owner, reviewImport, api) {
1492
2023
  [
1493
2024
  `Source: https://gist.github.com/${id}`,
1494
2025
  "Untrusted settings can enable local commands and network requests. Review the complete TOML before applying.",
1495
- "Import replaces the entire local document, including comments and unknown fields; no backup is kept after success."
2026
+ "Import replaces the entire local document, including comments and unknown fields; its previous bytes will be kept in History."
1496
2027
  ],
1497
2028
  "Preview imported footer\u2026"
1498
2029
  );
@@ -1506,7 +2037,7 @@ async function importSettingsGist(ctx, options, owner, reviewImport, api) {
1506
2037
  if (!current(guardedOwner) || diskSnapshot(options) !== disk) {
1507
2038
  throw new Error("Settings changed during import. Start a new import to review the latest state.");
1508
2039
  }
1509
- return (options.save ?? atomicSaveConfigDocument)(path, raw);
2040
+ return options.save ? options.save(path, raw) : atomicSaveConfigDocument(path, raw, {}, initialDisk);
1510
2041
  }
1511
2042
  },
1512
2043
  guardedOwner
@@ -1541,7 +2072,12 @@ async function reviewDocument(ctx, owner, title, content, lines, label) {
1541
2072
  }
1542
2073
  function diskSnapshot(options) {
1543
2074
  const loaded = (options.read ?? loadStarshipConfig)(options.settingsPath);
1544
- return JSON.stringify([loaded.rawDocument, loaded.source, loaded.diagnostics]);
2075
+ return JSON.stringify([
2076
+ loaded.rawDocument,
2077
+ loaded.source,
2078
+ loaded.diagnostics,
2079
+ readConfigDocumentSnapshot(options.settingsPath)
2080
+ ]);
1545
2081
  }
1546
2082
  function current(owner) {
1547
2083
  return !owner.signal.aborted && owner.isCurrent();
@@ -1591,9 +2127,9 @@ function safeDisplayText2(value) {
1591
2127
  // src/command-preset-picker.ts
1592
2128
  import { runLiveChoice } from "@narumitw/pi-tui-kit";
1593
2129
  async function showPresetPicker(ctx, options) {
1594
- const current2 = options.presets.find((preset) => preset.id === options.activePresetId)?.label ?? "Custom configuration";
2130
+ const current3 = options.presets.find((preset) => preset.id === options.activePresetId)?.label ?? "Custom configuration";
1595
2131
  const result = await runLiveChoice(ctx, {
1596
- title: `Presets \xB7 current: ${current2}`,
2132
+ title: `Presets \xB7 current: ${current3}`,
1597
2133
  items: options.presets.map((preset) => ({
1598
2134
  id: preset.id,
1599
2135
  label: preset.label,
@@ -1608,7 +2144,10 @@ async function showPresetPicker(ctx, options) {
1608
2144
  hint: "back",
1609
2145
  navigationLabel: "live preview",
1610
2146
  confirmLabel: "apply",
1611
- shortcuts: [{ id: "customize", keys: ["e", "shift+e"], label: "customize" }],
2147
+ shortcuts: [
2148
+ { id: "customize", keys: ["e", "shift+e"], label: "customize" },
2149
+ { id: "save-profile", keys: ["s", "shift+s"], label: "save as profile" }
2150
+ ],
1612
2151
  onSelectionChange: ({ item }) => {
1613
2152
  const preset = options.presets.find((candidate) => candidate.id === item.id);
1614
2153
  if (preset) options.preview(preset);
@@ -1618,12 +2157,520 @@ async function showPresetPicker(ctx, options) {
1618
2157
  });
1619
2158
  if (result.kind === "selected") return { kind: "apply", presetId: result.itemId };
1620
2159
  if (result.kind === "shortcut") {
1621
- return { kind: "customize", presetId: result.itemId };
2160
+ return { kind: result.shortcutId === "save-profile" ? "save-profile" : "customize", presetId: result.itemId };
1622
2161
  }
1623
2162
  if (result.kind === "closed" && result.reason === "back") return { kind: "back" };
1624
2163
  return { kind: "close" };
1625
2164
  }
1626
2165
 
2166
+ // src/command-profiles.ts
2167
+ import { isKeyRelease, Key as Key2, matchesKey as matchesKey2 } from "@earendil-works/pi-tui";
2168
+ import { defineMenu as defineMenu2, runLiveChoice as runLiveChoice2, runMenu as runMenu2 } from "@narumitw/pi-tui-kit";
2169
+ import { sanitizeTerminalText as sanitizeTerminalText3 } from "@narumitw/pi-tui-kit/terminal-text";
2170
+ var PREVIEW_NOTICE = "Preview uses the current runtime snapshot only; unavailable module data can be empty.";
2171
+ var SAVE_CURRENT = "save-current";
2172
+ var FlowEnded = class extends Error {
2173
+ };
2174
+ async function showProfiles(ctx, options, owner, applyCandidate) {
2175
+ return browseDocuments(ctx, options, owner, applyCandidate, "profile");
2176
+ }
2177
+ async function showHistory(ctx, options, owner, applyCandidate) {
2178
+ return browseDocuments(ctx, options, owner, applyCandidate, "history");
2179
+ }
2180
+ async function saveAsProfile(ctx, options, owner, raw) {
2181
+ if (!interactive(ctx) || !current2(owner)) return void 0;
2182
+ const flow = createFlow(ctx, options, owner);
2183
+ try {
2184
+ candidateFor(options, raw, true);
2185
+ const saved = await saveNamedCopy(ctx, options, flow, raw);
2186
+ flow.ensure();
2187
+ return saved;
2188
+ } catch (error) {
2189
+ if (flow.signal.aborted || !flow.sessionCurrent()) return "close";
2190
+ report(ctx, flow, error);
2191
+ return void 0;
2192
+ } finally {
2193
+ flow.dispose();
2194
+ }
2195
+ }
2196
+ async function browseDocuments(ctx, options, owner, applyCandidate, kind) {
2197
+ if (!interactive(ctx) || !current2(owner)) return "close";
2198
+ const flow = createFlow(ctx, options, owner);
2199
+ let selectedId;
2200
+ try {
2201
+ while (flow.current()) {
2202
+ let interacted = false;
2203
+ try {
2204
+ const documents = kind === "profile" ? listProfiles(options.settingsPath) : listHistory(options.settingsPath);
2205
+ const active = options.getLoaded();
2206
+ const matches = documents.filter(
2207
+ (document2) => document2.rawDocument !== void 0 && document2.rawDocument === active.rawDocument
2208
+ );
2209
+ const candidates = new Map(
2210
+ documents.map((document2) => [documentId(document2), candidateFor(options, document2.rawDocument)])
2211
+ );
2212
+ const selection = await runLiveChoice2(ctx, {
2213
+ title: kind === "profile" ? "Profiles" : "History",
2214
+ lines: [
2215
+ active.rawDocument === void 0 && active.diagnostics.length === 0 ? "Active: Built-in defaults" : active.diagnostics.some((item) => item.severity === "error") ? "Active: Invalid settings document \xB7 replacement requires explicit recovery" : "Active: Independent settings document",
2216
+ ...kind === "profile" && matches.length === 0 ? ["Current settings are not saved as a profile"] : [],
2217
+ PREVIEW_NOTICE
2218
+ ],
2219
+ items: [
2220
+ ...kind === "profile" ? [
2221
+ {
2222
+ id: SAVE_CURRENT,
2223
+ label: "Save current as\u2026",
2224
+ description: "Copy exact loaded TOML; keep active settings unchanged"
2225
+ }
2226
+ ] : [],
2227
+ ...documents.map((document2) => ({
2228
+ id: documentId(document2),
2229
+ label: safe(document2.name),
2230
+ description: [
2231
+ ...document2.kind === "history" ? [safe(document2.createdAt), ...document2.legacy ? ["Legacy \xB7 read-only"] : []] : [],
2232
+ ...document2.rawDocument !== void 0 && document2.rawDocument === active.rawDocument ? ["Matches active settings"] : [],
2233
+ ...!candidates.get(documentId(document2))?.loaded ? ["Invalid document \xB7 review or repair"] : []
2234
+ ].join(" \xB7 "),
2235
+ details: [
2236
+ `Selected: ${safe(document2.name)}`,
2237
+ `Path: ${safe(document2.path)}`,
2238
+ ...candidates.get(documentId(document2))?.lines ?? []
2239
+ ]
2240
+ }))
2241
+ ],
2242
+ initialItemId: selectedId,
2243
+ enableSearch: true,
2244
+ viewportSize: 10,
2245
+ hint: "back",
2246
+ confirmLabel: "actions",
2247
+ navigationLabel: "live preview",
2248
+ signal: flow.signal,
2249
+ isCurrent: flow.current,
2250
+ onSelectionChange: ({ item, signal }) => {
2251
+ if (signal.aborted || !flow.current()) return;
2252
+ selectedId = item.id;
2253
+ flow.preview(candidates.get(item.id)?.loaded);
2254
+ }
2255
+ });
2256
+ flow.ensure();
2257
+ interacted = true;
2258
+ if (selection.kind !== "selected") {
2259
+ return selection.kind === "closed" && selection.reason === "back" ? "back" : "close";
2260
+ }
2261
+ selectedId = selection.itemId;
2262
+ if (selectedId === SAVE_CURRENT) {
2263
+ flow.preview(void 0);
2264
+ const loaded = options.getLoaded();
2265
+ if (loaded.diagnostics.some((item) => item.severity === "error")) {
2266
+ throw new Error(
2267
+ "Cannot save unreadable or malformed active settings as a profile. Repair the settings document first."
2268
+ );
2269
+ }
2270
+ const raw = loaded.rawDocument ?? BUILT_IN_EXAMPLE;
2271
+ candidateFor(options, raw, true);
2272
+ const saved = await saveNamedCopy(ctx, options, flow, raw);
2273
+ flow.ensure();
2274
+ if (saved) selectedId = documentId(saved);
2275
+ continue;
2276
+ }
2277
+ const document = documents.find((item) => documentId(item) === selectedId);
2278
+ if (!document) continue;
2279
+ flow.ensure(document);
2280
+ const outcome = await documentActions(ctx, options, flow, document, applyCandidate);
2281
+ flow.ensure();
2282
+ if (outcome === "close") return "close";
2283
+ if (outcome) selectedId = documentId(outcome);
2284
+ } catch (error) {
2285
+ if (error instanceof FlowEnded || !flow.current()) return "close";
2286
+ flow.preview(void 0);
2287
+ report(ctx, flow, error);
2288
+ if (!interacted) return "close";
2289
+ }
2290
+ }
2291
+ return "close";
2292
+ } finally {
2293
+ flow.dispose();
2294
+ }
2295
+ }
2296
+ async function documentActions(ctx, options, flow, document, applyCandidate) {
2297
+ const candidate = candidateFor(options, document.rawDocument);
2298
+ const profile = document.kind === "profile";
2299
+ const activeInvalid = profile && options.getLoaded().diagnostics.some((item) => item.severity === "error");
2300
+ const action = await actionScreen(ctx, flow, {
2301
+ title: `${profile ? "Profile" : "Recovery copy"}: ${safe(document.name)}`,
2302
+ lines: [
2303
+ `Path: ${safe(document.path)}`,
2304
+ ...document.kind === "history" ? [`Recovery time: ${safe(document.createdAt)}`, "A recovery copy is not proof that an application succeeded."] : [],
2305
+ ...document.kind === "history" && document.legacy ? ["Legacy backup \xB7 read-only; restore copies bytes without changing this backup."] : [],
2306
+ ...document.readError ? [safe(document.readError)] : [],
2307
+ ...candidate.lines,
2308
+ PREVIEW_NOTICE
2309
+ ],
2310
+ raw: document.rawDocument,
2311
+ actions: [
2312
+ {
2313
+ id: "apply",
2314
+ label: profile ? "Apply\u2026" : "Restore\u2026",
2315
+ disabled: !candidate.loaded || activeInvalid,
2316
+ disabledReason: activeInvalid ? "Repair active settings or use explicit recovery first" : "Invalid TOML cannot be applied"
2317
+ },
2318
+ ...profile ? [
2319
+ { id: "edit", label: "Edit TOML\u2026" },
2320
+ { id: "rename", label: "Rename\u2026" },
2321
+ { id: "duplicate", label: "Duplicate\u2026" }
2322
+ ] : [
2323
+ {
2324
+ id: "save-as",
2325
+ label: "Save as a profile\u2026",
2326
+ disabled: !candidate.loaded,
2327
+ disabledReason: "Invalid TOML cannot be saved as a validated profile"
2328
+ }
2329
+ ],
2330
+ {
2331
+ id: "delete",
2332
+ label: "Delete\u2026",
2333
+ disabled: document.kind === "history" && document.legacy,
2334
+ disabledReason: "Legacy backups are read-only"
2335
+ }
2336
+ ]
2337
+ });
2338
+ flow.ensure(document);
2339
+ if (action === "close") return "close";
2340
+ if (action === "back") return void 0;
2341
+ if (action === "apply" && candidate.loaded) {
2342
+ const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, document);
2343
+ flow.ensure(document);
2344
+ return result === "close" ? "close" : document;
2345
+ }
2346
+ if (action === "edit" && profile) {
2347
+ const result = await editProfile(ctx, options, flow, document, applyCandidate);
2348
+ flow.ensure();
2349
+ return result;
2350
+ }
2351
+ if (action === "rename" && profile) {
2352
+ const name = await flow.dialog(
2353
+ () => ctx.ui.input(`Rename profile: ${safe(document.name)}`, "New profile name", { signal: flow.signal })
2354
+ );
2355
+ flow.ensure(document);
2356
+ if (name === void 0) return document;
2357
+ return renameProfile(options.settingsPath, document.name, name, document);
2358
+ }
2359
+ if (action === "duplicate" || action === "save-as" && document.rawDocument !== void 0) {
2360
+ const saved = await saveNamedCopy(ctx, options, flow, document.rawDocument, document);
2361
+ flow.ensure(document);
2362
+ return action === "duplicate" || document.kind === "history" ? document : saved ?? document;
2363
+ }
2364
+ if (action === "delete" && !(document.kind === "history" && document.legacy)) {
2365
+ const confirmed = await flow.dialog(
2366
+ () => ctx.ui.confirm(
2367
+ `Delete ${profile ? "profile" : "recovery copy"}: ${safe(document.name)}?`,
2368
+ `Path: ${safe(document.path)}
2369
+ ${profile ? "This deletes only the saved profile. The active settings copy remains unchanged." : "This permanently deletes only this recovery copy. Active settings remain unchanged."}`,
2370
+ { signal: flow.signal }
2371
+ )
2372
+ );
2373
+ flow.ensure(document);
2374
+ if (confirmed) {
2375
+ if (document.kind === "profile") deleteProfile(options.settingsPath, document.name, document);
2376
+ else deleteHistory(options.settingsPath, document.name, document);
2377
+ }
2378
+ }
2379
+ return void 0;
2380
+ }
2381
+ async function editProfile(ctx, options, flow, original, applyCandidate) {
2382
+ let draft = original.rawDocument ?? "";
2383
+ if (original.rawDocument === void 0) {
2384
+ const repair = await flow.dialog(
2385
+ () => ctx.ui.confirm(
2386
+ `Repair invalid UTF-8 profile: ${safe(original.name)}?`,
2387
+ `Path: ${safe(original.path)}
2388
+ The original bytes cannot be edited as TOML text. Open an empty repair draft? Saving replaces these invalid bytes; the saved copy stays unchanged until you select Save profile. Duplicate it first to keep the original bytes.`,
2389
+ { signal: flow.signal }
2390
+ )
2391
+ );
2392
+ flow.ensure(original);
2393
+ if (!repair) return original;
2394
+ }
2395
+ while (flow.current()) {
2396
+ const edited = await flow.dialog(() => ctx.ui.editor(`Edit profile: ${safe(original.name)}`, draft));
2397
+ flow.ensure(original);
2398
+ if (edited === void 0) return original;
2399
+ draft = edited;
2400
+ const candidate = candidateFor(options, draft);
2401
+ flow.preview(candidate.loaded);
2402
+ const action = await actionScreen(ctx, flow, {
2403
+ title: candidate.loaded ? "Profile draft preview" : "Profile draft needs attention",
2404
+ lines: [
2405
+ "Save profile changes only the saved copy, even when it matches active settings.",
2406
+ ...candidate.lines,
2407
+ PREVIEW_NOTICE
2408
+ ],
2409
+ raw: draft,
2410
+ actions: [
2411
+ {
2412
+ id: "save",
2413
+ label: "Save profile",
2414
+ disabled: !candidate.loaded,
2415
+ disabledReason: "Repair the draft before saving"
2416
+ },
2417
+ {
2418
+ id: "save-apply",
2419
+ label: "Save profile and apply\u2026",
2420
+ description: "Two operations: a failed apply retains the saved profile",
2421
+ disabled: !candidate.loaded,
2422
+ disabledReason: "Repair the draft before saving"
2423
+ },
2424
+ { id: "continue", label: "Continue editing" },
2425
+ { id: "discard", label: "Discard draft" }
2426
+ ]
2427
+ });
2428
+ flow.ensure(original);
2429
+ if (action === "close") return "close";
2430
+ if (action === "discard") return original;
2431
+ if (action === "continue" || action === "back") continue;
2432
+ if (!candidate.loaded || action !== "save" && action !== "save-apply") continue;
2433
+ const saved = saveProfile(options.settingsPath, original.name, draft, original);
2434
+ ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
2435
+ if (action === "save-apply") {
2436
+ try {
2437
+ const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, saved);
2438
+ flow.ensure(saved);
2439
+ if (result === "close") return "close";
2440
+ if (result !== "applied")
2441
+ ctx.ui.notify(
2442
+ "The profile was saved. Application did not complete; review the configuration result before retrying.",
2443
+ "warning"
2444
+ );
2445
+ } catch (error) {
2446
+ if (!flow.current()) throw error;
2447
+ ctx.ui.notify(
2448
+ `The saved profile was retained, but application did not complete: ${safeError3(error)}. Review active settings before retrying.`,
2449
+ "error"
2450
+ );
2451
+ }
2452
+ }
2453
+ return saved;
2454
+ }
2455
+ throw new FlowEnded();
2456
+ }
2457
+ async function applyReviewedCandidate(flow, loaded, applyCandidate, document) {
2458
+ flow.ensure(document);
2459
+ const result = await applyCandidate(
2460
+ loaded,
2461
+ {
2462
+ signal: flow.signal,
2463
+ // The shared commit policy captures the active revision before applying.
2464
+ // A successful apply changes it; session ownership must remain valid after it.
2465
+ isCurrent: () => !flow.signal.aborted && flow.sessionCurrent(),
2466
+ isSessionCurrent: flow.sessionCurrent
2467
+ },
2468
+ () => flow.ensure(document),
2469
+ document.name
2470
+ );
2471
+ if (result === "applied") flow.adoptAppliedRevision();
2472
+ flow.ensure(document);
2473
+ flow.preview(void 0);
2474
+ return result;
2475
+ }
2476
+ async function saveNamedCopy(ctx, options, flow, raw, source) {
2477
+ while (flow.current()) {
2478
+ const name = await flow.dialog(
2479
+ () => ctx.ui.input("Save as a profile", "Profile name (without .toml)", { signal: flow.signal })
2480
+ );
2481
+ flow.ensure(source);
2482
+ if (name === void 0) return void 0;
2483
+ try {
2484
+ const saved = source?.kind === "profile" ? duplicateProfile(options.settingsPath, source.name, name, source) : createProfile(options.settingsPath, name, requireText(raw));
2485
+ ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
2486
+ return saved;
2487
+ } catch (error) {
2488
+ report(ctx, flow, error);
2489
+ }
2490
+ }
2491
+ throw new FlowEnded();
2492
+ }
2493
+ async function actionScreen(ctx, flow, screen) {
2494
+ let selected;
2495
+ const menu = defineMenu2({
2496
+ start: "actions",
2497
+ screens: {
2498
+ actions: () => ({
2499
+ kind: "actions",
2500
+ title: screen.title,
2501
+ lines: screen.lines,
2502
+ items: [
2503
+ {
2504
+ id: "review",
2505
+ label: "Review TOML",
2506
+ to: "document",
2507
+ disabled: screen.raw === void 0,
2508
+ disabledReason: "The document is not valid UTF-8"
2509
+ },
2510
+ ...screen.actions.map((action) => ({ ...action, action: "select" }))
2511
+ ],
2512
+ hint: "back"
2513
+ }),
2514
+ document: () => ({
2515
+ kind: "review",
2516
+ title: screen.title,
2517
+ lines: ["Exact UTF-8 text \xB7 display controls sanitized \xB7 read-only"],
2518
+ content: screen.raw ?? "The document is not valid UTF-8; no decoded fallback is shown.",
2519
+ format: { kind: "code", language: "toml" },
2520
+ enableSearch: true,
2521
+ viewportSize: "adaptive",
2522
+ hint: "back"
2523
+ })
2524
+ },
2525
+ actions: {
2526
+ select: ({ itemId }) => {
2527
+ flow.ensure();
2528
+ selected = itemId;
2529
+ return { kind: "close" };
2530
+ }
2531
+ }
2532
+ });
2533
+ const result = await runMenu2(ctx, menu, { getState: () => void 0, signal: flow.signal, isCurrent: flow.current });
2534
+ flow.ensure();
2535
+ return selected ?? (result.kind === "closed" && result.reason === "back" ? "back" : "close");
2536
+ }
2537
+ function createFlow(ctx, options, owner) {
2538
+ const controller = new AbortController();
2539
+ const signal = AbortSignal.any([controller.signal, owner.signal]);
2540
+ let revision = options.getLoadedRevision?.();
2541
+ let activeDocument = activeFingerprint(options.getLoaded());
2542
+ let previewOwned = false;
2543
+ const isCurrent = () => !signal.aborted && owner.isCurrent() && (revision === void 0 ? activeFingerprint(options.getLoaded()) === activeDocument : options.getLoadedRevision?.() === revision);
2544
+ const clearPreview = () => {
2545
+ if (!previewOwned) return;
2546
+ previewOwned = false;
2547
+ if (owner.isSessionCurrent?.() ?? owner.isCurrent()) {
2548
+ try {
2549
+ options.preview?.(void 0, ctx);
2550
+ } catch (error) {
2551
+ ctx.ui.notify(`Could not clear the footer preview: ${safeError3(error)}`, "error");
2552
+ }
2553
+ }
2554
+ };
2555
+ const matches = (expected) => {
2556
+ if (!isCurrent()) return false;
2557
+ if (!expected) return true;
2558
+ try {
2559
+ const fresh = expected.kind === "profile" ? readProfile(options.settingsPath, expected.name) : readHistory(options.settingsPath, expected.name);
2560
+ return fresh.rawDocument === expected.rawDocument && fresh.identity.dev === expected.identity.dev && fresh.identity.ino === expected.identity.ino && fresh.identity.size === expected.identity.size && fresh.identity.mtimeNs === expected.identity.mtimeNs && fresh.identity.ctimeNs === expected.identity.ctimeNs && fresh.rawBytes.equals(expected.rawBytes);
2561
+ } catch {
2562
+ return false;
2563
+ }
2564
+ };
2565
+ const ensure = (expected) => {
2566
+ if (!isCurrent()) throw new FlowEnded();
2567
+ if (!matches(expected))
2568
+ throw new Error("The selected document changed or was removed. Review the latest copy before trying again.");
2569
+ };
2570
+ signal.addEventListener("abort", clearPreview, { once: true });
2571
+ return {
2572
+ signal,
2573
+ current: isCurrent,
2574
+ sessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
2575
+ ensure,
2576
+ preview(loaded) {
2577
+ ensure();
2578
+ if (!loaded) {
2579
+ clearPreview();
2580
+ return;
2581
+ }
2582
+ previewOwned = true;
2583
+ try {
2584
+ options.preview?.(loaded, ctx);
2585
+ } catch (error) {
2586
+ clearPreview();
2587
+ throw error;
2588
+ }
2589
+ },
2590
+ async dialog(run) {
2591
+ ensure();
2592
+ const unsubscribe = ctx.ui.onTerminalInput((data) => {
2593
+ if (!isKeyRelease(data) && matchesKey2(data, Key2.ctrl("c"))) {
2594
+ queueMicrotask(() => controller.abort());
2595
+ }
2596
+ return void 0;
2597
+ });
2598
+ let released = false;
2599
+ const release = () => {
2600
+ if (released) return;
2601
+ released = true;
2602
+ unsubscribe();
2603
+ };
2604
+ signal.addEventListener("abort", release, { once: true });
2605
+ try {
2606
+ if (signal.aborted) release();
2607
+ ensure();
2608
+ const result = await run();
2609
+ ensure();
2610
+ return result;
2611
+ } finally {
2612
+ signal.removeEventListener("abort", release);
2613
+ release();
2614
+ }
2615
+ },
2616
+ adoptAppliedRevision() {
2617
+ if (signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent())) throw new FlowEnded();
2618
+ revision = options.getLoadedRevision?.();
2619
+ activeDocument = activeFingerprint(options.getLoaded());
2620
+ },
2621
+ dispose() {
2622
+ try {
2623
+ clearPreview();
2624
+ } finally {
2625
+ signal.removeEventListener("abort", clearPreview);
2626
+ controller.abort();
2627
+ }
2628
+ }
2629
+ };
2630
+ }
2631
+ function candidateFor(options, raw, required = false) {
2632
+ try {
2633
+ if (raw === void 0) throw new Error("The document is not valid UTF-8; no decoded fallback is shown.");
2634
+ const loaded = (options.validate ?? validateConfigDocument)(options.settingsPath, raw);
2635
+ if (loaded.diagnostics.some((item) => item.severity === "error"))
2636
+ throw new Error(loaded.diagnostics.map((item) => item.message).join("; "));
2637
+ return {
2638
+ loaded,
2639
+ lines: loaded.diagnostics.length === 0 ? ["No configuration warnings."] : loaded.diagnostics.map((item) => `${safe(item.path || "root")}: ${safe(item.message)}`)
2640
+ };
2641
+ } catch (error) {
2642
+ if (required) throw error;
2643
+ return { lines: [`Invalid TOML: ${safeError3(error)}`, "No candidate footer preview is shown."] };
2644
+ }
2645
+ }
2646
+ function requireText(raw) {
2647
+ if (raw === void 0) throw new Error("The document is not valid UTF-8; no decoded fallback can be saved.");
2648
+ return raw;
2649
+ }
2650
+ function activeFingerprint(loaded) {
2651
+ return JSON.stringify([loaded.source, loaded.rawDocument, loaded.diagnostics]);
2652
+ }
2653
+ function current2(owner) {
2654
+ return !owner.signal.aborted && owner.isCurrent();
2655
+ }
2656
+ function interactive(ctx) {
2657
+ if (ctx.mode === "tui" && ctx.hasUI) return true;
2658
+ if (ctx.hasUI) ctx.ui.notify("Profiles and History require TUI mode.", "info");
2659
+ return false;
2660
+ }
2661
+ function documentId(document) {
2662
+ return `${document.kind}:${document.name}`;
2663
+ }
2664
+ function report(ctx, flow, error) {
2665
+ if (!(error instanceof FlowEnded) && flow.current()) ctx.ui.notify(safeError3(error), "error");
2666
+ }
2667
+ function safeError3(error) {
2668
+ return safe(error instanceof Error ? error.message : String(error));
2669
+ }
2670
+ function safe(value) {
2671
+ return sanitizeTerminalText3(value);
2672
+ }
2673
+
1627
2674
  // src/commands.ts
1628
2675
  var MAIN_ACTIONS = {
1629
2676
  customize: "customize",
@@ -1632,12 +2679,14 @@ var MAIN_ACTIONS = {
1632
2679
  modules: "modules",
1633
2680
  configuration: "configuration",
1634
2681
  help: "help",
1635
- restore: "restore"
2682
+ restore: "restore",
2683
+ profiles: "profiles"
1636
2684
  };
1637
2685
  var PREVIEW_ACTIONS = {
1638
2686
  continue: "continue",
1639
2687
  edit: "edit",
1640
- cancel: "cancel"
2688
+ cancel: "cancel",
2689
+ saveProfile: "save-profile"
1641
2690
  };
1642
2691
  function registerStarshipCommand(pi, options) {
1643
2692
  pi.registerCommand("starship", {
@@ -1647,6 +2696,38 @@ function registerStarshipCommand(pi, options) {
1647
2696
  });
1648
2697
  }
1649
2698
  async function handleStarshipCommand(args, ctx, options) {
2699
+ if (ctx.mode !== "tui") return runStarshipCommand(args, ctx, options);
2700
+ const base = workflowOwner(options);
2701
+ if (!isCurrentOwner2(base)) return;
2702
+ const controller = new AbortController();
2703
+ const signal = AbortSignal.any([base.signal, controller.signal]);
2704
+ const owner = {
2705
+ signal,
2706
+ isCurrent: () => !signal.aborted && base.isCurrent(),
2707
+ isSessionCurrent: () => base.isSessionCurrent?.() ?? base.isCurrent()
2708
+ };
2709
+ const unsubscribe = ctx.ui.onTerminalInput((data) => {
2710
+ if (!isKeyRelease2(data) && matchesKey3(data, Key3.ctrl("c"))) {
2711
+ queueMicrotask(() => controller.abort());
2712
+ }
2713
+ return void 0;
2714
+ });
2715
+ let listening = true;
2716
+ const release = () => {
2717
+ if (!listening) return;
2718
+ listening = false;
2719
+ unsubscribe();
2720
+ };
2721
+ signal.addEventListener("abort", release, { once: true });
2722
+ try {
2723
+ return await runStarshipCommand(args, ctx, { ...options, getMenuOwner: () => owner });
2724
+ } finally {
2725
+ signal.removeEventListener("abort", release);
2726
+ release();
2727
+ controller.abort();
2728
+ }
2729
+ }
2730
+ async function runStarshipCommand(args, ctx, options) {
1650
2731
  const normalized = args.trim();
1651
2732
  if (!normalized) {
1652
2733
  if (ctx.mode === "tui") await showMainMenu(ctx, options);
@@ -1680,7 +2761,7 @@ async function showMainMenu(ctx, options) {
1680
2761
  signal: fallbackController.signal,
1681
2762
  isCurrent: () => !fallbackController.signal.aborted
1682
2763
  };
1683
- const menu = defineMenu2({
2764
+ const menu = defineMenu3({
1684
2765
  start: "main",
1685
2766
  screens: {
1686
2767
  main: () => {
@@ -1733,6 +2814,12 @@ async function showMainMenu(ctx, options) {
1733
2814
  description: presentation.restoreDescription,
1734
2815
  disabled: presentation.restoreDisabled,
1735
2816
  action: "restore"
2817
+ },
2818
+ {
2819
+ id: MAIN_ACTIONS.profiles,
2820
+ label: "Profiles",
2821
+ description: "Save, edit, manage, and live-preview named TOML documents",
2822
+ action: "profiles"
1736
2823
  }
1737
2824
  ],
1738
2825
  hint: "close"
@@ -1782,7 +2869,9 @@ async function showMainMenu(ctx, options) {
1782
2869
  title: "pi-starship help",
1783
2870
  lines: [
1784
2871
  "Customize footer opens the TOML editor, then previews and confirms before saving.",
1785
- "Presets live-previews the cursor in the footer; Enter confirms apply and e customizes first.",
2872
+ "Presets live-previews the cursor in the footer; Enter confirms apply, e customizes, and s saves a profile when available.",
2873
+ "Profiles manages named TOML copies; selecting a document previews it without saving.",
2874
+ "Configuration History reviews and restores recovery copies; external edits are not fully tracked.",
1786
2875
  "Explain footer breaks down the modules currently showing from the existing snapshot.",
1787
2876
  "Modules searches every supported module and explains its current read-only state.",
1788
2877
  "Configuration includes disk reload plus unlisted Gist sharing and reviewed Gist import through gh.",
@@ -1801,6 +2890,36 @@ async function showMainMenu(ctx, options) {
1801
2890
  const result = await choosePreset(ctx, options, owner);
1802
2891
  return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
1803
2892
  },
2893
+ profiles: async () => {
2894
+ const result = await showProfiles(ctx, options, owner, async (loaded, guardedOwner, checkCandidate, name) => {
2895
+ const applied = await reviewAndApply(
2896
+ ctx,
2897
+ options,
2898
+ loaded,
2899
+ { kind: "profile", name },
2900
+ guardedOwner,
2901
+ false,
2902
+ checkCandidate
2903
+ );
2904
+ return applied === "applied" ? "applied" : applied === "close" ? "close" : "stay";
2905
+ });
2906
+ return result === "close" ? { kind: "close" } : { kind: "stay" };
2907
+ },
2908
+ history: async () => {
2909
+ const result = await showHistory(ctx, options, owner, async (loaded, guardedOwner, checkCandidate, name) => {
2910
+ const applied = await reviewAndApply(
2911
+ ctx,
2912
+ options,
2913
+ loaded,
2914
+ { kind: "history", name },
2915
+ guardedOwner,
2916
+ false,
2917
+ checkCandidate
2918
+ );
2919
+ return applied === "applied" ? "applied" : applied === "close" ? "close" : "stay";
2920
+ });
2921
+ return result === "close" ? { kind: "close" } : { kind: "stay" };
2922
+ },
1804
2923
  "gist-share": async () => {
1805
2924
  const result = await shareSettingsGist(ctx, options, owner, options.gistApi);
1806
2925
  return result === "close" ? { kind: "close" } : { kind: "stay" };
@@ -1834,7 +2953,7 @@ async function showMainMenu(ctx, options) {
1834
2953
  }
1835
2954
  });
1836
2955
  try {
1837
- await runMenu2(ctx, menu, {
2956
+ await runMenu3(ctx, menu, {
1838
2957
  getState: () => void 0,
1839
2958
  signal: owner.signal,
1840
2959
  isCurrent: owner.isCurrent
@@ -1850,10 +2969,12 @@ async function editSettings(ctx, options) {
1850
2969
  if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${options.settingsPath}`, "info");
1851
2970
  return "cancel";
1852
2971
  }
1853
- let draft = options.getLoaded().rawDocument ?? BUILT_IN_EXAMPLE;
2972
+ const expected = captureExpectation(ctx, options);
2973
+ if (!expected) return "cancel";
2974
+ let draft = expected.previous.rawDocument ?? BUILT_IN_EXAMPLE;
1854
2975
  while (true) {
1855
2976
  const edited = await ctx.ui.editor("Customize footer \u2014 close to preview", draft);
1856
- if (!isCurrentOwner2(owner) || edited === void 0) return "cancel";
2977
+ if (!commitOwnerCurrent(options, owner, expected) || edited === void 0) return "cancel";
1857
2978
  draft = edited;
1858
2979
  let validated;
1859
2980
  try {
@@ -1871,18 +2992,29 @@ async function editSettings(ctx, options) {
1871
2992
  owner.signal,
1872
2993
  owner.isCurrent
1873
2994
  );
1874
- if (!isCurrentOwner2(owner)) return "cancel";
2995
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
1875
2996
  if (action?.kind === "closed") return "close";
1876
2997
  if (selectedPreviewAction(action) === PREVIEW_ACTIONS.edit) continue;
1877
2998
  return "cancel";
1878
2999
  }
1879
- const result = await reviewAndApply(ctx, options, validated, { kind: "customize" }, owner);
3000
+ const result = await reviewAndApply(
3001
+ ctx,
3002
+ options,
3003
+ validated,
3004
+ { kind: "customize" },
3005
+ owner,
3006
+ false,
3007
+ void 0,
3008
+ expected
3009
+ );
1880
3010
  if (result === "edit") continue;
1881
3011
  return result;
1882
3012
  }
1883
3013
  }
1884
3014
  async function choosePreset(ctx, options, owner) {
1885
- const activePreset = presetForDocument(options.getLoaded().rawDocument);
3015
+ const expected = captureExpectation(ctx, options);
3016
+ if (!expected) return "cancel";
3017
+ const activePreset = presetForDocument(expected.previous.rawDocument);
1886
3018
  const selection = await showPresetPicker(ctx, {
1887
3019
  presets: STARSHIP_PRESETS,
1888
3020
  activePresetId: activePreset?.id,
@@ -1894,28 +3026,41 @@ async function choosePreset(ctx, options, owner) {
1894
3026
  options.preview?.(loaded, ctx);
1895
3027
  }
1896
3028
  });
1897
- if (!isCurrentOwner2(owner)) {
1898
- options.preview?.(void 0, ctx);
3029
+ if (!commitOwnerCurrent(options, owner, expected)) {
3030
+ clearSessionPreview(ctx, options, owner);
1899
3031
  return "cancel";
1900
3032
  }
1901
3033
  if (selection.kind === "back" || selection.kind === "close") {
1902
- options.preview?.(void 0, ctx);
3034
+ clearSessionPreview(ctx, options, owner);
1903
3035
  return selection.kind === "close" ? "close" : "cancel";
1904
3036
  }
1905
3037
  const preset = getStarshipPreset(selection.presetId);
1906
3038
  try {
1907
- return await applyPreset(ctx, options, preset, selection.kind === "customize" ? "customize" : "confirm");
3039
+ if (selection.kind === "save-profile") {
3040
+ const saved = await saveAsProfile(ctx, options, owner, preset.rawDocument);
3041
+ return saved === "close" ? "close" : "cancel";
3042
+ }
3043
+ return await applyPreset(
3044
+ ctx,
3045
+ options,
3046
+ preset,
3047
+ selection.kind === "customize" ? "customize" : "confirm",
3048
+ expected,
3049
+ owner
3050
+ );
1908
3051
  } finally {
1909
- options.preview?.(void 0, ctx);
3052
+ clearSessionPreview(ctx, options, owner);
1910
3053
  }
1911
3054
  }
1912
- async function applyPreset(ctx, options, preset, start = "review") {
1913
- const owner = workflowOwner(options);
3055
+ async function applyPreset(ctx, options, preset, start = "review", captured, capturedOwner) {
3056
+ const owner = capturedOwner ?? workflowOwner(options);
1914
3057
  if (!isCurrentOwner2(owner)) return "cancel";
3058
+ const expected = captured ?? captureExpectation(ctx, options);
3059
+ if (!expected) return "cancel";
1915
3060
  let draft = preset.rawDocument;
1916
3061
  if (start === "customize") {
1917
3062
  const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
1918
- if (!isCurrentOwner2(owner) || edited === void 0) return "cancel";
3063
+ if (!commitOwnerCurrent(options, owner, expected) || edited === void 0) return "cancel";
1919
3064
  draft = edited;
1920
3065
  }
1921
3066
  while (true) {
@@ -1935,11 +3080,11 @@ async function applyPreset(ctx, options, preset, start = "review") {
1935
3080
  owner.signal,
1936
3081
  owner.isCurrent
1937
3082
  );
1938
- if (!isCurrentOwner2(owner)) return "cancel";
3083
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
1939
3084
  if (action?.kind === "closed") return "close";
1940
3085
  if (selectedPreviewAction(action) !== PREVIEW_ACTIONS.edit) return "cancel";
1941
3086
  const edited2 = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
1942
- if (!isCurrentOwner2(owner) || edited2 === void 0) return "cancel";
3087
+ if (!commitOwnerCurrent(options, owner, expected) || edited2 === void 0) return "cancel";
1943
3088
  draft = edited2;
1944
3089
  continue;
1945
3090
  }
@@ -1949,11 +3094,13 @@ async function applyPreset(ctx, options, preset, start = "review") {
1949
3094
  validated,
1950
3095
  { kind: "preset", preset },
1951
3096
  owner,
1952
- start === "confirm"
3097
+ start === "confirm",
3098
+ void 0,
3099
+ expected
1953
3100
  );
1954
3101
  if (result !== "edit") return result;
1955
3102
  const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
1956
- if (!isCurrentOwner2(owner) || edited === void 0) return "cancel";
3103
+ if (!commitOwnerCurrent(options, owner, expected) || edited === void 0) return "cancel";
1957
3104
  draft = edited;
1958
3105
  }
1959
3106
  }
@@ -1964,7 +3111,10 @@ async function restoreBuiltIn(ctx, options) {
1964
3111
  const result = await reviewAndApply(ctx, options, validated, { kind: "restore" }, owner);
1965
3112
  return result === "edit" ? "cancel" : result;
1966
3113
  }
1967
- async function reviewAndApply(ctx, options, validated, intent, owner, skipReview = false) {
3114
+ async function reviewAndApply(ctx, options, validated, intent, owner, skipReview = false, checkCandidate, captured) {
3115
+ if (ctx.mode !== "tui" || !isCurrentOwner2(owner)) return "cancel";
3116
+ const expected = captured ?? captureExpectation(ctx, options);
3117
+ if (!expected) return "cancel";
1968
3118
  let reviewRequired = !skipReview;
1969
3119
  while (true) {
1970
3120
  const directAttempt = !reviewRequired;
@@ -1975,7 +3125,7 @@ async function reviewAndApply(ctx, options, validated, intent, owner, skipReview
1975
3125
  (width) => reviewPreviewBody(ctx, options, validated, width, intent),
1976
3126
  [
1977
3127
  { value: PREVIEW_ACTIONS.continue, label: continueLabel(intent) },
1978
- ...intent.kind === "restore" || intent.kind === "import" ? [] : [
3128
+ ...intent.kind !== "customize" && intent.kind !== "preset" ? [] : [
1979
3129
  {
1980
3130
  value: PREVIEW_ACTIONS.edit,
1981
3131
  label: intent.kind === "preset" ? "Customize before applying" : "Continue editing"
@@ -1984,53 +3134,53 @@ async function reviewAndApply(ctx, options, validated, intent, owner, skipReview
1984
3134
  {
1985
3135
  value: PREVIEW_ACTIONS.cancel,
1986
3136
  label: intent.kind === "restore" ? "Cancel" : intent.kind === "preset" ? "Choose another preset" : "Discard draft"
1987
- }
3137
+ },
3138
+ ...intent.kind === "customize" || intent.kind === "preset" || intent.kind === "import" ? [{ value: PREVIEW_ACTIONS.saveProfile, label: "Save as profile\u2026" }] : []
1988
3139
  ],
1989
3140
  owner.signal,
1990
3141
  owner.isCurrent
1991
3142
  );
1992
- if (!isCurrentOwner2(owner)) return "cancel";
3143
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
1993
3144
  if (selection?.kind === "closed") return "close";
1994
3145
  const selected = selectedPreviewAction(selection);
1995
3146
  if (selected === PREVIEW_ACTIONS.edit) return "edit";
3147
+ if (selected === PREVIEW_ACTIONS.saveProfile) {
3148
+ const saved = await saveAsProfile(ctx, options, owner, validated.rawDocument ?? BUILT_IN_EXAMPLE);
3149
+ if (saved === "close") return "close";
3150
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
3151
+ continue;
3152
+ }
1996
3153
  if (selected !== PREVIEW_ACTIONS.continue) return "cancel";
1997
3154
  }
1998
3155
  reviewRequired = true;
1999
3156
  const confirmed = await ctx.ui.confirm(
2000
3157
  confirmationTitle(intent),
2001
- confirmationMessage(options.settingsPath, intent),
3158
+ confirmationMessage(options.settingsPath, intent, expected.previous),
2002
3159
  { signal: owner.signal }
2003
3160
  );
2004
- if (!isCurrentOwner2(owner)) return "cancel";
3161
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
2005
3162
  if (!confirmed) {
2006
3163
  if (directAttempt) return "cancel";
2007
3164
  continue;
2008
3165
  }
2009
- const save = options.save ?? atomicSaveConfigDocument;
2010
- const previous = options.getLoaded();
2011
- let saved;
2012
3166
  try {
2013
- saved = save(options.settingsPath, validated.rawDocument ?? BUILT_IN_EXAMPLE);
2014
- } catch (error) {
2015
- ctx.ui.notify(
2016
- `Footer settings were not saved: ${safeText(formatError2(error))}. The previous footer remains active.`,
2017
- "error"
3167
+ const result = await commitActiveDocument(
3168
+ ctx,
3169
+ options,
3170
+ validated,
3171
+ owner,
3172
+ expected,
3173
+ intent.kind === "restore" || intent.kind === "history" || intent.kind === "customize",
3174
+ checkCandidate
2018
3175
  );
2019
- if (directAttempt) return "cancel";
2020
- continue;
2021
- }
2022
- try {
2023
- options.apply(saved, ctx);
3176
+ if (!isSessionOwnerCurrent(owner) || result === "cancel") return "cancel";
2024
3177
  } catch (error) {
2025
- const rollbackError = restorePreviousConfiguration(ctx, options, previous, saved);
2026
- ctx.ui.notify(
2027
- rollbackError ? `Footer settings could not be applied: ${safeText(formatError2(error))}. Restoring the previous configuration also failed: ${safeText(formatError2(rollbackError))}.` : `Footer settings could not be applied: ${safeText(formatError2(error))}. The previous configuration was restored.`,
2028
- "error"
2029
- );
3178
+ if (!isSessionOwnerCurrent(owner)) return "cancel";
3179
+ ctx.ui.notify(safeText(formatError2(error)), "error");
2030
3180
  if (directAttempt) return "cancel";
2031
3181
  continue;
2032
3182
  }
2033
- const warningSuffix = saved.diagnostics.length > 0 ? ` (${saved.diagnostics.length} warning${saved.diagnostics.length === 1 ? "" : "s"})` : "";
3183
+ const warningSuffix = validated.diagnostics.length > 0 ? ` (${validated.diagnostics.length} warning${validated.diagnostics.length === 1 ? "" : "s"})` : "";
2034
3184
  ctx.ui.notify(`${successMessage(intent)}${warningSuffix}.`, "info");
2035
3185
  return "applied";
2036
3186
  }
@@ -2043,6 +3193,10 @@ function reviewTitle(intent) {
2043
3193
  return "Restore preview";
2044
3194
  case "import":
2045
3195
  return "Gist footer preview";
3196
+ case "profile":
3197
+ return `${safeText(intent.name)} profile preview`;
3198
+ case "history":
3199
+ return "History recovery preview";
2046
3200
  case "preset":
2047
3201
  return `${intent.preset.label} preset preview`;
2048
3202
  }
@@ -2055,6 +3209,10 @@ function continueLabel(intent) {
2055
3209
  return "Replace with built-in\u2026";
2056
3210
  case "import":
2057
3211
  return "Replace with Gist settings\u2026";
3212
+ case "profile":
3213
+ return `Apply ${safeText(intent.name)} profile\u2026`;
3214
+ case "history":
3215
+ return "Restore history document\u2026";
2058
3216
  case "preset":
2059
3217
  return `Apply ${intent.preset.label} preset\u2026`;
2060
3218
  }
@@ -2067,14 +3225,22 @@ function confirmationTitle(intent) {
2067
3225
  return "Restore built-in footer?";
2068
3226
  case "import":
2069
3227
  return "Replace settings with Gist?";
3228
+ case "profile":
3229
+ return `Apply ${safeText(intent.name)} profile?`;
3230
+ case "history":
3231
+ return "Restore settings from history?";
2070
3232
  case "preset":
2071
3233
  return `Apply ${intent.preset.label} preset?`;
2072
3234
  }
2073
3235
  }
2074
- function confirmationMessage(settingsPath, intent) {
2075
- if (intent.kind === "customize") return "Save this configuration and apply it immediately?";
2076
- const replacement = intent.kind === "restore" ? "the built-in configuration" : intent.kind === "import" ? "the reviewed Gist settings" : `the ${intent.preset.label} preset`;
2077
- return `Replace ${safeText(settingsPath)} entirely with ${replacement}? All custom settings, unknown fields, and comments will be removed. No backup is kept after success.`;
3236
+ function confirmationMessage(settingsPath, intent, previous) {
3237
+ if (previous.diagnostics.some((item) => item.severity === "error")) {
3238
+ return `Explicit recovery: replace the invalid settings file ${safeText(settingsPath)} entirely with the reviewed document? Its exact original bytes will be kept in History before replacement.`;
3239
+ }
3240
+ if (intent.kind === "customize")
3241
+ return "Replace the entire settings document and apply it immediately? Its previous bytes will be kept in History.";
3242
+ const replacement = intent.kind === "restore" ? "the built-in configuration" : intent.kind === "import" ? "the reviewed Gist settings" : intent.kind === "profile" ? `the ${safeText(intent.name)} profile` : intent.kind === "history" ? "the reviewed history document" : `the ${intent.preset.label} preset`;
3243
+ return `Replace ${safeText(settingsPath)} entirely with ${replacement}? All custom settings, unknown fields, and comments will be replaced. The previous document will be kept in History.`;
2078
3244
  }
2079
3245
  function successMessage(intent) {
2080
3246
  switch (intent.kind) {
@@ -2084,6 +3250,10 @@ function successMessage(intent) {
2084
3250
  return "Built-in footer restored and applied";
2085
3251
  case "import":
2086
3252
  return "Gist settings saved and applied";
3253
+ case "profile":
3254
+ return `${safeText(intent.name)} profile applied`;
3255
+ case "history":
3256
+ return "History document restored and applied";
2087
3257
  case "preset":
2088
3258
  return `${intent.preset.label} preset saved and applied`;
2089
3259
  }
@@ -2100,43 +3270,42 @@ function workflowOwner(options) {
2100
3270
  function isCurrentOwner2(owner) {
2101
3271
  return !owner.signal.aborted && owner.isCurrent();
2102
3272
  }
2103
- function restorePreviousConfiguration(ctx, options, previous, saved) {
3273
+ function isSessionOwnerCurrent(owner) {
3274
+ return !owner.signal.aborted && (owner.isSessionCurrent?.() ?? owner.isCurrent());
3275
+ }
3276
+ function clearSessionPreview(ctx, options, owner) {
3277
+ if (owner.isSessionCurrent?.() ?? owner.isCurrent()) options.preview?.(void 0, ctx);
3278
+ }
3279
+ function captureExpectation(ctx, options) {
2104
3280
  try {
2105
- if (saved.rawDocument === void 0 || saved.fileIdentity === void 0) {
2106
- throw new Error("The saved settings document identity is unavailable");
2107
- }
2108
- removeConfigDocumentIfMatches(options.settingsPath, saved.rawDocument, saved.fileIdentity);
2109
- if (previous.rawDocument !== void 0) {
2110
- (options.restore ?? atomicRestoreConfigDocument)(options.settingsPath, previous.rawDocument);
2111
- }
2112
- options.apply(previous, ctx);
2113
- return void 0;
3281
+ return captureCommitExpectation(options);
2114
3282
  } catch (error) {
2115
- return error;
3283
+ ctx.ui.notify(`Footer settings were not saved: ${safeText(formatError2(error))}`, "error");
3284
+ return void 0;
2116
3285
  }
2117
3286
  }
2118
3287
  function reviewPreviewBody(ctx, options, loaded, width, intent) {
2119
3288
  if (intent.kind === "restore") return restorePreviewBody(ctx, options, loaded, width);
2120
- if (intent.kind === "customize" || intent.kind === "import") return previewBody(ctx, options, loaded, width);
2121
- const current2 = configurationPresentation(options.getLoaded());
3289
+ if (intent.kind !== "preset") return previewBody(ctx, options, loaded, width);
3290
+ const current3 = configurationPresentation(options.getLoaded());
2122
3291
  return [
2123
3292
  `Preset: ${intent.preset.label}`,
2124
3293
  `Requirement: ${intent.preset.requiresNerdFont ? "Nerd Font" : "No special font"}`,
2125
- `Current: ${current2.state}`,
3294
+ `Current: ${current3.state}`,
2126
3295
  `Path: ${safeText(options.settingsPath)}`,
2127
3296
  "Applying replaces the entire settings document, including custom settings, unknown fields, and comments.",
2128
- "No backup is kept after a successful apply.",
3297
+ "The previous document will be kept in History before replacement.",
2129
3298
  "",
2130
3299
  ...previewBody(ctx, options, loaded, width)
2131
3300
  ];
2132
3301
  }
2133
3302
  function restorePreviewBody(ctx, options, loaded, width) {
2134
- const current2 = configurationPresentation(options.getLoaded());
3303
+ const current3 = configurationPresentation(options.getLoaded());
2135
3304
  return [
2136
- `Current: ${current2.state}`,
3305
+ `Current: ${current3.state}`,
2137
3306
  `Path: ${safeText(options.settingsPath)}`,
2138
3307
  "The entire settings document will be replaced, including custom settings, unknown fields, and comments.",
2139
- "No backup is kept after a successful restore.",
3308
+ "The previous document will be kept in History before replacement.",
2140
3309
  "",
2141
3310
  ...previewBody(ctx, options, loaded, width)
2142
3311
  ];
@@ -2174,7 +3343,7 @@ function showHelp(ctx, settingsPath) {
2174
3343
  if (!canNotify(ctx)) return;
2175
3344
  ctx.ui.notify(
2176
3345
  [
2177
- "/starship \u2014 customize, live-preview presets, explain, or inspect the footer in TUI mode",
3346
+ "/starship \u2014 manage profiles, live-preview presets, recover history, explain, or inspect the footer in TUI mode",
2178
3347
  "/starship settings \u2014 customize, preview, and apply TOML",
2179
3348
  "/starship status \u2014 show source, path, and warnings",
2180
3349
  "/starship help \u2014 show this help",
@@ -2199,6 +3368,7 @@ function formatError2(error) {
2199
3368
  }
2200
3369
  export {
2201
3370
  handleStarshipCommand,
2202
- registerStarshipCommand
3371
+ registerStarshipCommand,
3372
+ reviewAndApply
2203
3373
  };
2204
- //# sourceMappingURL=commands-M6GHLJIR.ts.map
3374
+ //# sourceMappingURL=commands-C2VJ6ZBN.ts.map