@narumitw/pi-starship 0.59.2 → 0.60.1

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,169 @@
1
+ import { type ExtensionCommandContext, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
2
+ import type { ConfigurationCommandOptions, WorkflowOwner } from "./command-configuration.js";
3
+ import {
4
+ assertConfigDocumentUnchanged,
5
+ atomicRestoreConfigDocument,
6
+ atomicSaveConfigDocument,
7
+ type ConfigDocumentSnapshot,
8
+ ConfigPublicationError,
9
+ type LoadedStarshipConfig,
10
+ readConfigDocumentSnapshot,
11
+ removeConfigDocumentIfMatches,
12
+ validateConfigDocument,
13
+ } from "./config.js";
14
+ import { archiveConfigDocument } from "./profile-store.js";
15
+
16
+ export interface CommitOptions extends ConfigurationCommandOptions {
17
+ save?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
18
+ restore?: (settingsPath: string, rawDocument: string) => void;
19
+ archive?: typeof archiveConfigDocument;
20
+ }
21
+
22
+ export interface CommitExpectation {
23
+ previous: LoadedStarshipConfig;
24
+ revision: number | undefined;
25
+ disk: ConfigDocumentSnapshot;
26
+ }
27
+
28
+ export function captureCommitExpectation(options: ConfigurationCommandOptions): CommitExpectation {
29
+ return {
30
+ previous: options.getLoaded(),
31
+ revision: options.getLoadedRevision?.(),
32
+ disk: readConfigDocumentSnapshot(options.settingsPath),
33
+ };
34
+ }
35
+
36
+ export function commitOwnerCurrent(
37
+ options: ConfigurationCommandOptions,
38
+ owner: WorkflowOwner,
39
+ expected: CommitExpectation,
40
+ ): boolean {
41
+ const loaded = options.getLoaded();
42
+ return (
43
+ !owner.signal.aborted &&
44
+ owner.isCurrent() &&
45
+ loaded.rawDocument === expected.previous.rawDocument &&
46
+ loaded.source === expected.previous.source &&
47
+ JSON.stringify(loaded.diagnostics) === JSON.stringify(expected.previous.diagnostics) &&
48
+ options.getLoadedRevision?.() === expected.revision
49
+ );
50
+ }
51
+
52
+ /** The queue has asynchronous admission; the owned file/runtime transaction has no await boundary. */
53
+ export async function commitActiveDocument(
54
+ ctx: ExtensionCommandContext,
55
+ options: CommitOptions,
56
+ candidate: LoadedStarshipConfig,
57
+ owner: WorkflowOwner,
58
+ expected: CommitExpectation,
59
+ allowInvalid = false,
60
+ checkCandidate?: () => void,
61
+ ): Promise<"applied" | "cancel"> {
62
+ const raw = candidate.rawDocument;
63
+ if (raw === undefined) throw new Error("The candidate settings document is unavailable");
64
+ return withFileMutationQueue(options.settingsPath, async () => {
65
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
66
+ checkCandidate?.();
67
+ assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
68
+ const previousBytes = expected.disk.rawBytes;
69
+ if (expected.previous.rawDocument !== previousBytes?.toString("utf8")) {
70
+ throw new Error(
71
+ "The active file differs from the loaded document. Reload and review it before replacing settings.",
72
+ );
73
+ }
74
+ const invalid = expected.previous.diagnostics.some((item) => item.severity === "error");
75
+ if (invalid && !allowInvalid)
76
+ throw new Error("The active settings document is invalid. Use explicit repair or recovery before replacing it.");
77
+ // Always validate again at the publication boundary, not only in the preview layer.
78
+ validateConfigDocument(options.settingsPath, raw);
79
+ if (previousBytes?.equals(Buffer.from(raw))) return "applied";
80
+
81
+ let recoveryPath: string | undefined;
82
+ if (previousBytes !== undefined) {
83
+ recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
84
+ }
85
+ // A recovery publication can fail or observe an external edit. Never publish over that edit.
86
+ try {
87
+ assertConfigDocumentUnchanged(options.settingsPath, expected.disk);
88
+ if (!commitOwnerCurrent(options, owner, expected)) return "cancel";
89
+ checkCandidate?.();
90
+ } catch (error) {
91
+ throw new Error(`${message(error)}.${recoveryNote(recoveryPath)}`);
92
+ }
93
+ let saved: LoadedStarshipConfig;
94
+ try {
95
+ saved = options.save
96
+ ? options.save(options.settingsPath, raw)
97
+ : atomicSaveConfigDocument(options.settingsPath, raw, {}, expected.disk);
98
+ } catch (error) {
99
+ if (error instanceof ConfigPublicationError) {
100
+ const rollback = restorePrevious(ctx, options, owner, expected, raw, error.fileIdentity, false);
101
+ throw new Error(`Footer settings were not saved: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`);
102
+ }
103
+ throw new Error(
104
+ `Footer settings were not saved: ${message(error)}. The previous footer remains active.${recoveryNote(recoveryPath)}`,
105
+ );
106
+ }
107
+ try {
108
+ if (
109
+ owner.signal.aborted ||
110
+ !(owner.isSessionCurrent?.() ?? owner.isCurrent()) ||
111
+ options.getLoadedRevision?.() !== expected.revision
112
+ ) {
113
+ throw new Error("The configuration owner changed during publication");
114
+ }
115
+ options.apply(saved, ctx);
116
+ } catch (error) {
117
+ const rollback = restorePrevious(ctx, options, owner, expected, raw, saved.fileIdentity, true);
118
+ throw new Error(
119
+ `Footer settings could not be applied: ${message(error)}. ${rollback}${recoveryNote(recoveryPath)}`,
120
+ );
121
+ }
122
+ return "applied";
123
+ });
124
+ }
125
+
126
+ function restorePrevious(
127
+ ctx: ExtensionCommandContext,
128
+ options: CommitOptions,
129
+ owner: WorkflowOwner,
130
+ expected: CommitExpectation,
131
+ raw: string,
132
+ identity: LoadedStarshipConfig["fileIdentity"],
133
+ restoreRuntime: boolean,
134
+ ): string {
135
+ try {
136
+ if (owner.signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent()))
137
+ throw new Error("The session owner changed; stale restoration was blocked");
138
+ const current = options.getLoaded();
139
+ if (current.rawDocument !== expected.previous.rawDocument && current.rawDocument !== raw) {
140
+ throw new Error("The active runtime changed; stale restoration was blocked");
141
+ }
142
+ if (!identity) throw new Error("The saved settings document identity is unavailable");
143
+ assertConfigDocumentUnchanged(options.settingsPath, { rawBytes: Buffer.from(raw), fileIdentity: identity });
144
+ if (expected.disk.rawBytes === undefined) {
145
+ removeConfigDocumentIfMatches(options.settingsPath, raw, identity);
146
+ } else if (options.restore && expected.disk.rawBytes.equals(Buffer.from(expected.previous.rawDocument ?? ""))) {
147
+ options.restore(options.settingsPath, expected.previous.rawDocument ?? "");
148
+ } else {
149
+ atomicRestoreConfigDocument(
150
+ options.settingsPath,
151
+ expected.disk.rawBytes,
152
+ {},
153
+ { rawBytes: Buffer.from(raw), fileIdentity: identity },
154
+ );
155
+ }
156
+ if (restoreRuntime) options.apply(expected.previous, ctx);
157
+ return "The previous configuration was restored.";
158
+ } catch (error) {
159
+ return `Restoring the previous configuration also failed: ${message(error)}. Active path: ${options.settingsPath}.`;
160
+ }
161
+ }
162
+
163
+ function recoveryNote(path: string | undefined): string {
164
+ return path ? ` Recovery copy retained: ${path}.` : "";
165
+ }
166
+
167
+ function message(error: unknown): string {
168
+ return error instanceof Error ? error.message : String(error);
169
+ }
@@ -1,9 +1,17 @@
1
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
1
+ import { type ExtensionCommandContext, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
2
2
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
3
3
  import { type PreviewMenuResult, showPreviewActionMenu } from "./command-preview.js";
4
- import { BUILT_IN_EXAMPLE, type LoadedStarshipConfig, loadStarshipConfig } from "./config.js";
4
+ import {
5
+ assertConfigDocumentUnchanged,
6
+ BUILT_IN_EXAMPLE,
7
+ type ConfigDocumentSnapshot,
8
+ type LoadedStarshipConfig,
9
+ loadStarshipConfig,
10
+ readConfigDocumentSnapshot,
11
+ } from "./config.js";
5
12
  import { serializeEffectiveConfig } from "./effective-config.js";
6
13
  import { presetForDocument } from "./presets/catalog.js";
14
+ import { archiveConfigDocument } from "./profile-store.js";
7
15
 
8
16
  const RELOAD_ACTIONS = {
9
17
  apply: "apply",
@@ -13,6 +21,8 @@ const RELOAD_ACTIONS = {
13
21
  export interface WorkflowOwner {
14
22
  signal: AbortSignal;
15
23
  isCurrent(): boolean;
24
+ /** Session ownership independent of command cancellation and candidate/revision guards. */
25
+ isSessionCurrent?(): boolean;
16
26
  }
17
27
 
18
28
  export interface ConfigurationCommandOptions {
@@ -22,6 +32,7 @@ export interface ConfigurationCommandOptions {
22
32
  settingsPath: string;
23
33
  renderPreview?(loaded: LoadedStarshipConfig, width: number, ctx: ExtensionCommandContext): string[];
24
34
  read?: (settingsPath: string) => LoadedStarshipConfig;
35
+ archive?: typeof archiveConfigDocument;
25
36
  }
26
37
 
27
38
  export interface ConfigurationPresentation {
@@ -111,6 +122,12 @@ export function configurationMenuScreen(loaded: LoadedStarshipConfig) {
111
122
  description: "Review and preview remote TOML before replacing settings · requires gh",
112
123
  action: "gist-import" as const,
113
124
  },
125
+ {
126
+ id: "history",
127
+ label: "History",
128
+ description: "Review and restore recovery copies; legacy skill backups are read-only",
129
+ action: "history" as const,
130
+ },
114
131
  ],
115
132
  hint: "back" as const,
116
133
  };
@@ -184,6 +201,13 @@ export async function reloadConfiguration(
184
201
  const previous = options.getLoaded();
185
202
  const revision = options.getLoadedRevision?.();
186
203
  const candidate = readReloadCandidate(options);
204
+ let disk: ConfigDocumentSnapshot;
205
+ try {
206
+ disk = readConfigDocumentSnapshot(options.settingsPath);
207
+ } catch (error) {
208
+ ctx.ui.notify(`Footer reload was blocked: ${safeError(error)}`, "error");
209
+ return "stay";
210
+ }
187
211
  if (!candidate.ok) {
188
212
  ctx.ui.notify(`Footer reload was blocked: ${safeError(candidate.error)}`, "error");
189
213
  return "stay";
@@ -212,47 +236,67 @@ export async function reloadConfiguration(
212
236
  "Apply configuration from disk?",
213
237
  candidate.loaded.rawDocument === undefined
214
238
  ? "Use built-in defaults for this session? No settings file will be created."
215
- : "Apply the validated settings document to this session without changing its bytes?",
239
+ : "Apply the validated settings document to this session without changing its bytes? The previous loaded document will be kept in History.",
240
+ { signal: owner.signal },
216
241
  );
217
242
  if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision) || !confirmed) {
218
243
  return "stay";
219
244
  }
220
245
 
221
- const fresh = readReloadCandidate(options);
222
- if (!fresh.ok) {
223
- ctx.ui.notify(
224
- `Footer reload was blocked after confirmation: ${safeError(fresh.error)}. The previous footer remains active.`,
225
- "error",
226
- );
227
- return "stay";
228
- }
229
- if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
230
- ctx.ui.notify(
231
- "The settings document changed after preview. The previous footer remains active; reload again to review the latest version.",
232
- "warning",
233
- );
234
- return "stay";
235
- }
236
-
246
+ let warnings = 0;
237
247
  try {
238
- options.apply(fresh.loaded, ctx);
248
+ const applied = await withFileMutationQueue(options.settingsPath, async () => {
249
+ if (
250
+ !isCurrentOwner(owner) ||
251
+ activeRevisionChanged(options, revision) ||
252
+ !sameLoadedDocument(previous, options.getLoaded())
253
+ )
254
+ return false;
255
+ assertConfigDocumentUnchanged(options.settingsPath, disk);
256
+ const fresh = readReloadCandidate(options);
257
+ if (!fresh.ok) throw new Error(fresh.error);
258
+ if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
259
+ throw new Error(
260
+ "The settings document changed after preview. The previous footer remains active; reload again to review the latest version.",
261
+ );
262
+ }
263
+ let recoveryPath: string | undefined;
264
+ const previousBytes = previous.rawBytes ?? previous.rawDocument;
265
+ if (previousBytes !== undefined) {
266
+ recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
267
+ }
268
+ assertConfigDocumentUnchanged(options.settingsPath, disk);
269
+ if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision)) return false;
270
+ try {
271
+ options.apply(fresh.loaded, ctx);
272
+ } catch (error) {
273
+ let rollbackError: unknown;
274
+ try {
275
+ if (!isCurrentOwner(owner)) throw new Error("The session owner changed; stale restoration was blocked");
276
+ const current = options.getLoaded();
277
+ if (!sameLoadedDocument(current, previous) && !sameLoadedDocument(current, fresh.loaded))
278
+ throw new Error("The active runtime changed; stale restoration was blocked");
279
+ options.apply(previous, ctx);
280
+ } catch (rollback) {
281
+ rollbackError = rollback;
282
+ }
283
+ throw new Error(
284
+ `Footer reload failed: ${formatError(error)}. ${
285
+ rollbackError
286
+ ? `Restoring the previous configuration also failed: ${formatError(rollbackError)}.`
287
+ : "The previous configuration was restored."
288
+ }${recoveryPath ? ` Recovery copy retained: ${recoveryPath}.` : ""}`,
289
+ );
290
+ }
291
+ warnings = fresh.loaded.diagnostics.length;
292
+ return true;
293
+ });
294
+ if (!isCurrentOwner(owner) || !applied) return "stay";
239
295
  } catch (error) {
240
- let rollbackError: unknown;
241
- try {
242
- options.apply(previous, ctx);
243
- } catch (rollback) {
244
- rollbackError = rollback;
245
- }
246
- ctx.ui.notify(
247
- rollbackError
248
- ? `Footer reload failed: ${safeError(error)}. Restoring the previous configuration also failed: ${safeError(rollbackError)}.`
249
- : `Footer reload failed: ${safeError(error)}. The previous configuration was restored.`,
250
- "error",
251
- );
296
+ if (isCurrentOwner(owner))
297
+ ctx.ui.notify(`Footer reload was blocked after confirmation: ${safeError(error)}`, "error");
252
298
  return "stay";
253
299
  }
254
-
255
- const warnings = fresh.loaded.diagnostics.length;
256
300
  ctx.ui.notify(
257
301
  warnings === 0
258
302
  ? "Footer configuration reloaded and applied."
@@ -8,6 +8,7 @@ import {
8
8
  BUILT_IN_EXAMPLE,
9
9
  type LoadedStarshipConfig,
10
10
  loadStarshipConfig,
11
+ readConfigDocumentSnapshot,
11
12
  validateConfigDocument,
12
13
  } from "./config.js";
13
14
  import { checkGistDocument, createSettingsGist, fetchSettingsGist, type GhApi, gistId } from "./gist.js";
@@ -91,8 +92,10 @@ export async function importSettingsGist(
91
92
  const previous = options.getLoaded();
92
93
  const revision = options.getLoadedRevision?.();
93
94
  const disk = diskSnapshot(options);
95
+ const initialDisk = readConfigDocumentSnapshot(options.settingsPath);
94
96
  const guardedOwner: WorkflowOwner = {
95
97
  signal: owner.signal,
98
+ isSessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
96
99
  isCurrent: () =>
97
100
  current(owner) &&
98
101
  options.getLoadedRevision?.() === revision &&
@@ -138,7 +141,7 @@ export async function importSettingsGist(
138
141
  [
139
142
  `Source: https://gist.github.com/${id}`,
140
143
  "Untrusted settings can enable local commands and network requests. Review the complete TOML before applying.",
141
- "Import replaces the entire local document, including comments and unknown fields; no backup is kept after success.",
144
+ "Import replaces the entire local document, including comments and unknown fields; its previous bytes will be kept in History.",
142
145
  ],
143
146
  "Preview imported footer…",
144
147
  );
@@ -152,7 +155,7 @@ export async function importSettingsGist(
152
155
  if (!current(guardedOwner) || diskSnapshot(options) !== disk) {
153
156
  throw new Error("Settings changed during import. Start a new import to review the latest state.");
154
157
  }
155
- return (options.save ?? atomicSaveConfigDocument)(path, raw);
158
+ return options.save ? options.save(path, raw) : atomicSaveConfigDocument(path, raw, {}, initialDisk);
156
159
  },
157
160
  },
158
161
  guardedOwner,
@@ -196,7 +199,12 @@ async function reviewDocument(
196
199
 
197
200
  function diskSnapshot(options: StarshipCommandOptions): string {
198
201
  const loaded = (options.read ?? loadStarshipConfig)(options.settingsPath);
199
- return JSON.stringify([loaded.rawDocument, loaded.source, loaded.diagnostics]);
202
+ return JSON.stringify([
203
+ loaded.rawDocument,
204
+ loaded.source,
205
+ loaded.diagnostics,
206
+ readConfigDocumentSnapshot(options.settingsPath),
207
+ ]);
200
208
  }
201
209
 
202
210
  function current(owner: WorkflowOwner): boolean {
@@ -5,6 +5,7 @@ import type { StarshipPreset } from "./presets/catalog.js";
5
5
  export type PresetPickerResult =
6
6
  | { kind: "apply"; presetId: StarshipPreset["id"] }
7
7
  | { kind: "customize"; presetId: StarshipPreset["id"] }
8
+ | { kind: "save-profile"; presetId: StarshipPreset["id"] }
8
9
  | { kind: "back" }
9
10
  | { kind: "close" };
10
11
 
@@ -40,7 +41,10 @@ export async function showPresetPicker(
40
41
  hint: "back",
41
42
  navigationLabel: "live preview",
42
43
  confirmLabel: "apply",
43
- shortcuts: [{ id: "customize", keys: ["e", "shift+e"], label: "customize" }],
44
+ shortcuts: [
45
+ { id: "customize", keys: ["e", "shift+e"], label: "customize" },
46
+ { id: "save-profile", keys: ["s", "shift+s"], label: "save as profile" },
47
+ ],
44
48
  onSelectionChange: ({ item }) => {
45
49
  const preset = options.presets.find((candidate) => candidate.id === item.id);
46
50
  if (preset) options.preview(preset);
@@ -50,7 +54,7 @@ export async function showPresetPicker(
50
54
  });
51
55
  if (result.kind === "selected") return { kind: "apply", presetId: result.itemId };
52
56
  if (result.kind === "shortcut") {
53
- return { kind: "customize", presetId: result.itemId };
57
+ return { kind: result.shortcutId === "save-profile" ? "save-profile" : "customize", presetId: result.itemId };
54
58
  }
55
59
  if (result.kind === "closed" && result.reason === "back") return { kind: "back" };
56
60
  return { kind: "close" };