@narumitw/pi-starship 0.59.2 → 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.
@@ -34,19 +34,19 @@ Before its apply script replaces an existing document, it preserves the inspecte
34
34
  Backups are written and flushed under a private temporary name, atomically renamed to their final private file, and followed by flushes of the backup directory and its parent directory before publication continues; a recoverable failure removes the owned temporary file and preserves the active document.
35
35
  If configuration publication fails after that backup is durable, the failure reports its retained path; cleanup failures report both their operation and cause without hiding the primary failure.
36
36
  A missing document creates no backup, and a backup with the same minute name blocks publication when observed before rename; this check does not provide cross-process locking.
37
- The interactive `/starship` editor, preset, and restore flows do not invoke this script and keep their separately documented backup behavior.
37
+ The interactive `/starship` flows do not invoke this script. They preserve replaced documents in the separate recovery history described below; existing skill backups remain available read-only in History.
38
38
 
39
- The shallow main menu also exposes **Presets**, **Explain footer**, **Modules**, **Configuration**, **Help**, and **Restore built-in…**.
39
+ The main menu also exposes **Profiles**, **Presets**, **Explain footer**, **Modules**, **Configuration**, **Help**, and **Restore built-in…**.
40
40
  Explain footer uses the current immutable runtime snapshot to list each currently showing non-empty module once with its rendered value and description; it starts no new collection work.
41
41
  Modules opens a bounded searchable inspector for every registered module.
42
42
  Its textual states distinguish **Showing**, **Empty**, **Disabled**, **Not in format**, and **Unavailable** only when the current footer cannot provide an inspection snapshot.
43
43
  Module detail shows the current preview when available, description, root reference and reachability, format variables, style fields, supported style-rule selectors, configured rule count, display rules, and the known reason for absent output.
44
44
  Both views are read-only and do not create or update the settings document.
45
45
 
46
- Configuration contains **Overview**, **Effective configuration**, **Settings document**, **Reload from disk**, **Share settings as Gist…**, and **Import settings from Gist…** on one nested level.
46
+ Configuration contains **Overview**, **Effective configuration**, **Settings document**, **Reload from disk**, **History**, **Share settings as Gist…**, and **Import settings from Gist…** on one nested level.
47
47
  Gist actions use `gh` authentication for github.com and transfer only `pi-starship.toml`, limited to 64 KiB; sharing includes comments and unknown fields and requires review and confirmation before creating an unlisted Gist.
48
48
  Unlisted Gists are readable by anyone with the link; remove sensitive data before sharing, and check GitHub before retrying a cancelled or failed upload because a remote Gist may already exist.
49
- Import accepts a Gist ID or URL, validates the complete document, requires raw TOML review, footer preview, and full-replacement confirmation, and applies immediately without a post-success backup; review untrusted settings for command execution and network access before accepting.
49
+ Import accepts a Gist ID or URL, validates the complete document, requires raw TOML review, footer preview, and full-replacement confirmation, and preserves the previous document before applying; review untrusted settings for command execution and network access before accepting.
50
50
  Overview combines state, source, path, health, and bounded diagnostics.
51
51
  Effective configuration shows deterministic catalog-ordered public TOML from the normalized state currently in use; comments, unknown fields, parser ASTs, and private runtime selectors are excluded.
52
52
  Settings document shows the exact loaded UTF-8 text through a terminal-safe, cell-aware read-only review without changing the raw payload.
@@ -56,7 +56,64 @@ A deleted document is a valid previewable transition to built-in defaults and cr
56
56
  An unchanged document is a no-op, while read or parse failure, cancellation, disposal, external changes after preview, session replacement, shutdown, or runtime apply failure preserves the prior effective footer and every file byte.
57
57
  Reload re-reads immediately after confirmation and rejects a different external snapshot; it does not claim cross-process locking or continuing synchronization with later edits.
58
58
  Restore is disabled when no settings document exists or the exact built-in document is already saved.
59
- For a custom or invalid document, Restore previews the result and warns that the complete document, including custom settings, unknown fields, and comments, will be replaced without a post-success backup before asking for confirmation.
59
+ For a custom or invalid document, Restore previews the result and warns that the complete document, including custom settings, unknown fields, and comments, will be replaced before asking for confirmation. The previous bytes are preserved first, including invalid content on an explicit recovery path.
60
+
61
+ ### Named profiles
62
+
63
+ Profiles are complete TOML documents saved under `<getAgentDir()>/pi-starship/profiles/<name>.toml`.
64
+ The active settings remain an independent copy at `<getAgentDir()>/pi-starship.toml`.
65
+ There is no active-profile pointer or live link: editing, renaming, or deleting a profile does not modify active settings.
66
+ The browser marks every profile whose exact bytes match the active document; identical profiles can all match.
67
+
68
+ Open **Profiles** to save the current document, browse saved documents, and manage the selected profile.
69
+ Selection previews the footer from existing runtime data without saving, creating history, starting collectors, running commands, or accessing the network.
70
+ Modules with no data in the current snapshot can be empty.
71
+ Display text removes terminal controls before layout and style rendering; generated colors and validated HTTP(S) hyperlinks remain supported without changing stored TOML.
72
+ Invalid documents show diagnostics, cannot be applied, and never silently preview the built-in fallback.
73
+ Documents with invalid UTF-8 remain visible and can be renamed, duplicated, or deleted without changing their bytes.
74
+ Repairing such a profile requires explicit confirmation before opening an empty text draft; only a validated save replaces its unreadable bytes.
75
+
76
+ **Edit TOML** uses a separate draft and validates it before saving.
77
+ The draft review offers saving only the profile, saving and applying it, continuing the edit, or discarding the draft.
78
+ Saving a profile and applying it are separate operations: application failure does not delete a successfully saved profile.
79
+ Applying requires confirmation and replaces the entire active document.
80
+ **Rename**, **Duplicate**, and confirmed **Delete** act only on the saved profile.
81
+ Preset and reviewed Gist candidates can also be saved as profiles without changing the active file.
82
+
83
+ New names are normalized to NFC and contain 1–80 Unicode code points, excluding path separators, terminal controls, leading dots, leading/trailing whitespace, and platform-reserved names or characters.
84
+ Encoded filenames must fit the filesystem limit, and names cannot collide without regard to case.
85
+ Invalid names are rejected, not silently rewritten; case-only renames are rejected unless supported safely.
86
+ Only regular files are used; package-owned storage directories and files cannot be symbolic links.
87
+ Comments, ordering, and unknown fields remain unchanged.
88
+
89
+ Escape returns one level; Ctrl+C closes the workflow.
90
+ Leaving a browser removes its temporary preview, while an already committed change remains active.
91
+ The native Pi editor has no public abort method; session cancellation removes the preview immediately and blocks stale saves, but an open editor can remain until it is closed.
92
+
93
+ ### Recovery history
94
+
95
+ Managed active-file replacements preserve the previous document in `<getAgentDir()>/pi-starship/history/<timestamp>-<random-id>.toml` before writing the replacement.
96
+ Editor, preset, profile, restore, and Gist application use this policy.
97
+ A missing file or a byte-identical no-op creates no recovery copy.
98
+ Backup failure blocks replacement; runtime-application failure attempts guarded disk/runtime restoration and retains the backup.
99
+ A recovery copy can therefore come from an unsuccessful application attempt; it is not proof that a candidate was applied.
100
+
101
+ **Configuration** → **History** supports read-only review, preview and confirmed restore, saving valid content as a profile, and confirmed deletion of new history entries.
102
+ Legacy `pi-starship-YYYYMMDDHHmm.toml` skill backups remain in their existing directory and are read-only in History.
103
+ Malformed recovery content remains available for inspection; it cannot be applied without repair and validation.
104
+ History has no automatic pruning.
105
+
106
+ Explicit **Reload from disk** preserves the previous loaded document before changing the runtime, without rewriting the external file.
107
+ Ordinary `session_start`, including `/reload`, does not write history or materialize defaults.
108
+ Versions overwritten by an external editor before Pi observes them cannot be recovered automatically.
109
+
110
+ New directories and documents use private POSIX permissions (`0700` and `0600`).
111
+ Files are flushed before publication; directory-entry flushing is used on POSIX and is not available through the same API on Windows, so the same crash-durability guarantee is not claimed there.
112
+ Mutations preserve exact document bytes, use temporary files plus rename, and publish recovery before active-file replacement.
113
+ There is no atomic transaction across history, the active file, and the running footer.
114
+ Detected changes after review block the operation rather than overwrite the changed document.
115
+ In-process ordering and cooperative storage locking do not lock out external editors; external check-to-rename races remain possible.
116
+ A stale cooperative mutation lock is never removed automatically; after confirming no storage operation is running, inspect the reported lock path before removing it manually.
60
117
 
61
118
  ### 🎛️ Presets
62
119
 
@@ -81,11 +138,12 @@ Colors, separators, typography, and layout follow the named Starship preset; mod
81
138
  | **Tokyo Night** | Connected cool blue Tokyo Night blocks | Nerd Font |
82
139
 
83
140
  Moving through the preset picker temporarily renders the selected preset in the footer without writing settings or starting collectors.
84
- Press Enter to confirm replacement, or press `e` to edit the selected complete TOML document before preview and confirmation.
141
+ Press Enter to confirm replacement, press `e` to edit the selected complete TOML document before preview and confirmation, or use the displayed `s` save-as-profile action without applying.
142
+ Standard configured actions take precedence over these additive shortcuts; a conflicting shortcut is omitted from the hint.
85
143
  Escape returns to the main menu, while Ctrl+C closes the workflow; both restore the active footer.
86
144
 
87
145
  Presets are complete documents, not overlays.
88
- After confirmation, applying one replaces all of `pi-starship.toml`, including custom settings, unknown fields, and comments; no backup is kept.
146
+ After confirmation, applying one replaces all of `pi-starship.toml`, including custom settings, unknown fields, and comments; the previous document is retained in History.
89
147
  Cancellation, disposal, validation failure, write failure, and runtime-apply failure preserve the previous document and footer.
90
148
  An exact match is **Currently applied** and cannot be selected again; editing any byte makes it custom.
91
149
  Use **Restore built-in…** for deterministic recovery.
@@ -305,16 +363,17 @@ Style expressions support:
305
363
 
306
364
  - Named colors and ANSI numbers `0`–`255`.
307
365
  - Hex RGB (`#7aa2f7`), rendered as ANSI-256 when Pi's effective terminal capabilities disable true color.
366
+ - `pi:<role>` references to exact public Pi theme colors; see [Pi theme colors](#pi-theme-colors).
308
367
  - `fg:<color>` and `bg:<color>`; an unprefixed color is foreground.
309
368
  - `bold`, `dimmed`, `italic`, `underline`, `blink`, `inverted`, `hidden`, and `strikethrough`.
310
369
  - `none` and `fg:none`, which make the complete expression unstyled regardless of position.
311
- - `bg:none`, which clears only the absolute background; an unknown `bg:<value>` has the same Starship-compatible reset behavior.
370
+ - `bg:none`, which clears only the absolute background; an unknown legacy `bg:<value>` keeps the same Starship-compatible reset behavior, but an unknown `bg:pi:<role>` is invalid.
312
371
  - `prev_fg` and `prev_bg`, which use the previous rendered chunk's colors when present and retain any absolute foreground/background in the expression as the no-previous fallback.
313
372
  - Direct color names from one explicitly selected `[palettes.<name>]` table.
314
373
 
315
374
  There is no built-in or fallback palette.
316
- A custom palette is active only when its table is explicitly selected, and its values must be direct named, ANSI, or RGB colors—palette entries cannot reference other entries.
317
- Palette names override terminal color names such as `blue`:
375
+ A custom palette is active only when its table is explicitly selected, and its values must be direct named, ANSI, RGB, or `pi:<role>` colors—palette entries cannot reference other entries.
376
+ Palette keys override terminal color names such as `blue` and are checked before interpreting `pi:<role>`:
318
377
 
319
378
  ```toml
320
379
  palette = "company"
@@ -327,7 +386,9 @@ accent = "208"
327
386
  style = "bold blue"
328
387
  ```
329
388
 
330
- Style tokens are case-insensitive and ordinary foreground/background colors are last-wins.
389
+ Existing style keywords and named colors remain case-insensitive, and palette-key matching keeps its existing behavior.
390
+ Pi role names are case-sensitive and retain their exact spelling in direct styles and palette values.
391
+ Ordinary foreground/background colors are last-wins.
331
392
  `prev_fg`/`prev_bg` override their absolute fallback only when a previous chunk exists.
332
393
  Empty styled groups still advance previous-color state.
333
394
  Invalid literal style expressions warn and render unstyled.
@@ -337,6 +398,56 @@ An invalid root format falls back to the built-in root format; an invalid module
337
398
  The background-free defaults are: `brand = "bold white"`, `provider`/`model` = `"bold blue"`, `thinking`/`git_branch`/`turn` = `"bold purple"`, `directory`/`git_worktree` = `"cyan bold"`, `github_pr = "bold blue"`, `git_commit = "green bold"`, `git_state`/`activity`/`time` = `"bold yellow"`, `git_status = "red bold"`, `tokens = "bold cyan"`, `cache = "bold green"`, `extension_status = "dimmed white"`, `direnv = "bold bright-yellow"`, and `fill = "bold black"`.
338
399
  Context, cost, Git metrics, and username use the state/multi-style defaults below.
339
400
 
401
+ ### Pi theme colors
402
+
403
+ Use `pi:<role>` wherever a color is accepted: module style fields, literal format styles, `style_rules`, `display` styles, extension-status styles, and palette values.
404
+ The role must be an exact public Pi `ThemeToken`, such as `accent`, `muted`, `thinkingHigh`, or `selectedBg`; preserve camelCase.
405
+ Theme variables and HTML export colors are not public roles.
406
+
407
+ ```toml
408
+ format = "$model$directory"
409
+
410
+ [model]
411
+ style = "bold fg:pi:accent bg:pi:selectedBg"
412
+
413
+ [directory]
414
+ style = "fg:pi:muted"
415
+ ```
416
+
417
+ A reference supplies only a color through Pi's public `theme.colors` API, not the role's ANSI styling.
418
+ Any role can supply either foreground or background: `bg:pi:accent` and `fg:pi:selectedBg` are valid regardless of the role's original slot.
419
+ Modifiers remain independent: add `bold` or `dimmed` explicitly when needed; a role adds neither implicitly.
420
+ For terminal-default roles, Pi supplies the terminal's reported default color or an appearance-based fallback when it is unavailable.
421
+ For faint roles, Pi supplies a concrete approximation mixed toward the background, not an implicit dim modifier.
422
+ Theme colors use ANSI-256 output when Pi's effective terminal capabilities disable true color.
423
+ Arbitrary theme colors do not guarantee readable contrast when combined as foreground and background.
424
+
425
+ Palette-key lookup takes precedence over role interpretation:
426
+
427
+ ```toml
428
+ palette = "company"
429
+
430
+ [palettes.company]
431
+ "pi:accent" = "#ff0000"
432
+ primary = "pi:accent"
433
+
434
+ [model]
435
+ style = "fg:pi:accent" # palette key wins: fixed red
436
+
437
+ [directory]
438
+ style = "fg:primary" # direct palette value: current Pi accent
439
+ ```
440
+
441
+ Palette values resolve directly as colors, not as recursive aliases.
442
+ Thus `primary = "pi:accent"` uses the Pi role even when the palette defines a `"pi:accent"` key.
443
+ An unknown Pi role in either foreground or background, including `bg:pi:unknown`, produces a settings diagnostic and uses the owning field's [fallback behavior](#diagnostic-and-fallback-behavior); an invalid palette value is omitted.
444
+ Validation does not rewrite the TOML file.
445
+ Unknown legacy background colors still clear the background as described above.
446
+
447
+ The footer and previews follow Pi theme switches and active theme hot reload without reloading TOML.
448
+ Fixed named, ANSI, and RGB colors, built-in defaults, and presets remain unchanged; only explicit `pi:<role>` references follow the theme.
449
+ To use the document with an older extension, replace these references with fixed colors before downgrading.
450
+
340
451
  ### Content-selected styles
341
452
 
342
453
  `provider`, `model`, and `thinking` can replace their `$style` value with the first matching entry from an ordered `style_rules` array.
@@ -1,65 +1,119 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { randomUUID } from "node:crypto";
4
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
- import { basename, dirname, isAbsolute, join } from "node:path";
4
+ import { closeSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync } from "node:fs";
5
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
6
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { pathToFileURL } from "node:url";
6
8
  import { parse } from "smol-toml";
7
9
  import { backupExpectedDocument } from "./backup.mjs";
8
10
  import { formatDisplayValue, formatError } from "./script-support.mjs";
9
11
 
10
- const [draftPath, destinationPath, expectedPath, ...extraArguments] = process.argv.slice(2);
11
-
12
- if (!draftPath || !destinationPath || !expectedPath || extraArguments.length > 0) {
13
- console.error(
14
- "Usage: node scripts/apply.mjs <draft-path> <absolute-pi-starship.toml-path> <expected-path|--expect-missing>",
15
- );
16
- process.exitCode = 2;
17
- } else if (!isAbsolute(destinationPath) || basename(destinationPath) !== "pi-starship.toml") {
18
- console.error("The destination must be an absolute path named pi-starship.toml.");
19
- process.exitCode = 2;
20
- } else {
12
+ /** Keep this script independent of the extension's generated runtime. */
13
+ export async function applyGuardedDocument(draftPath, destinationPath, expectedPath, options = {}) {
21
14
  let temporaryPath;
22
15
  let backupPath;
16
+ let published = false;
17
+ let failureMessage;
23
18
  try {
24
- const draft = await readFile(draftPath, "utf8");
19
+ const draft = await readFile(draftPath);
20
+ parse(new TextDecoder("utf-8", { fatal: true }).decode(draft));
25
21
  const expectMissing = expectedPath === "--expect-missing";
26
22
  const expected = expectMissing ? undefined : await readFile(expectedPath);
27
- await mkdir(dirname(destinationPath), { recursive: true });
23
+ const initial = assertDestinationUnchanged(destinationPath, expectMissing, expected);
24
+ if (expected?.equals(draft)) return { backupPath: undefined, unchanged: true };
25
+ await mkdir(dirname(destinationPath), { recursive: true, mode: 0o700 });
28
26
  temporaryPath = join(dirname(destinationPath), `.pi-starship.toml.${randomUUID()}.tmp`);
29
- await writeFile(temporaryPath, draft, { encoding: "utf8", flag: "wx" });
30
- parse(await readFile(temporaryPath, "utf8"));
31
- await assertDestinationUnchanged(destinationPath, expectMissing, expected);
32
- backupPath = expected === undefined ? undefined : await backupExpectedDocument(destinationPath, expected);
33
- await rename(temporaryPath, destinationPath);
27
+ await writeFile(temporaryPath, draft, { flag: "wx", mode: 0o600, flush: true });
28
+ assertDestinationUnchanged(destinationPath, expectMissing, expected, initial);
29
+ backupPath =
30
+ expected === undefined ? undefined : await (options.backup ?? backupExpectedDocument)(destinationPath, expected);
31
+ // Backup has asynchronous durability boundaries. Recheck after them, then publish without an await gap.
32
+ if (!readFileSync(draftPath).equals(draft)) {
33
+ throw new Error("The draft changed during backup; review it again before applying.");
34
+ }
35
+ assertDestinationUnchanged(destinationPath, expectMissing, expected, initial);
36
+ (options.rename ?? renameSync)(temporaryPath, destinationPath);
34
37
  temporaryPath = undefined;
35
- if (backupPath) console.log(`Backed up the previous TOML to ${formatDisplayValue(backupPath)}`);
36
- console.log(`Applied valid TOML atomically to ${formatDisplayValue(destinationPath)}`);
38
+ published = true;
39
+ (options.syncDirectory ?? syncDirectory)(dirname(destinationPath));
40
+ return { backupPath, unchanged: false };
37
41
  } catch (error) {
38
- const failure = `Draft was not applied to ${formatDisplayValue(destinationPath)}: ${formatError(error)}`;
39
- console.error(backupPath ? `${failure}\nRetained backup: ${formatDisplayValue(backupPath)}` : failure);
40
- process.exitCode = 1;
41
- } finally {
42
+ const failure = published
43
+ ? `Draft was published to ${formatDisplayValue(destinationPath)}, but its directory durability check failed: ${formatError(error)}`
44
+ : `Draft was not applied to ${formatDisplayValue(destinationPath)}: ${formatError(error)}`;
45
+ failureMessage = backupPath ? `${failure}\nRetained backup: ${formatDisplayValue(backupPath)}` : failure;
42
46
  if (temporaryPath) {
43
47
  try {
44
- await rm(temporaryPath, { force: true });
45
- } catch {
46
- // Cleanup is best-effort and must not obscure the original failure.
48
+ await (options.remove ?? rm)(temporaryPath, { force: true });
49
+ } catch (cleanupError) {
50
+ failureMessage += `\nRemoving the staged document also failed: ${formatError(cleanupError)}. Temporary path: ${formatDisplayValue(temporaryPath)}`;
47
51
  }
48
52
  }
53
+ throw new Error(failureMessage, { cause: error });
49
54
  }
50
55
  }
51
56
 
52
- async function assertDestinationUnchanged(destinationPath, expectMissing, expected) {
57
+ function assertDestinationUnchanged(destinationPath, expectMissing, expected, initial) {
53
58
  let current;
59
+ let info;
54
60
  try {
55
- current = await readFile(destinationPath);
61
+ info = lstatSync(destinationPath);
62
+ if (!info.isFile() || info.isSymbolicLink())
63
+ throw new Error("The active settings path must be a regular file, not a symbolic link.");
64
+ current = readFileSync(destinationPath);
65
+ const after = lstatSync(destinationPath);
66
+ if (after.dev !== info.dev || after.ino !== info.ino)
67
+ throw new Error("The active settings file changed while being read.");
56
68
  } catch (error) {
57
69
  if (error && typeof error === "object" && error.code === "ENOENT") {
58
- if (expectMissing) return;
70
+ if (expectMissing) return undefined;
59
71
  throw new Error("The active pi-starship.toml was removed after inspection.");
60
72
  }
61
73
  throw error;
62
74
  }
63
- if (!expectMissing && expected !== undefined && current.equals(expected)) return;
75
+ if (
76
+ !expectMissing &&
77
+ expected !== undefined &&
78
+ current.equals(expected) &&
79
+ (!initial || (info.dev === initial.dev && info.ino === initial.ino))
80
+ )
81
+ return { dev: info.dev, ino: info.ino };
64
82
  throw new Error("The active pi-starship.toml changed after inspection; the newer file was preserved.");
65
83
  }
84
+
85
+ function syncDirectory(directoryPath) {
86
+ if (process.platform === "win32") return;
87
+ const handle = openSync(directoryPath, "r");
88
+ try {
89
+ fsyncSync(handle);
90
+ } finally {
91
+ closeSync(handle);
92
+ }
93
+ }
94
+
95
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
96
+ const [draftPath, destinationPath, expectedPath, ...extraArguments] = process.argv.slice(2);
97
+ if (!draftPath || !destinationPath || !expectedPath || extraArguments.length > 0) {
98
+ console.error(
99
+ "Usage: node scripts/apply.mjs <draft-path> <absolute-pi-starship.toml-path> <expected-path|--expect-missing>",
100
+ );
101
+ process.exitCode = 2;
102
+ } else if (!isAbsolute(destinationPath) || basename(destinationPath) !== "pi-starship.toml") {
103
+ console.error("The destination must be an absolute path named pi-starship.toml.");
104
+ process.exitCode = 2;
105
+ } else {
106
+ try {
107
+ const result = await applyGuardedDocument(draftPath, destinationPath, expectedPath);
108
+ if (result.backupPath) console.log(`Backed up the previous TOML to ${formatDisplayValue(result.backupPath)}`);
109
+ console.log(
110
+ result.unchanged
111
+ ? "The active TOML already matches the draft."
112
+ : `Applied valid TOML atomically to ${formatDisplayValue(destinationPath)}`,
113
+ );
114
+ } catch (error) {
115
+ console.error(formatError(error));
116
+ process.exitCode = 1;
117
+ }
118
+ }
119
+ }
@@ -19,7 +19,9 @@ export async function backupExpectedDocument(destinationPath, expected, options
19
19
  const renameFile = options.renameFile ?? rename;
20
20
  const syncDirectory = options.syncDirectory ?? syncDirectoryEntry;
21
21
 
22
+ await assertBackupDirectorySafe(backupDirectory, inspectPath, true);
22
23
  await makeDirectory(backupDirectory, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
24
+ await assertBackupDirectorySafe(backupDirectory, inspectPath, false);
23
25
 
24
26
  let handle;
25
27
  let ownsTemporaryPath = false;
@@ -96,6 +98,21 @@ async function syncDirectoryEntry(directoryPath) {
96
98
  if (syncError) throw syncError;
97
99
  }
98
100
 
101
+ async function assertBackupDirectorySafe(directoryPath, inspectPath, allowMissing) {
102
+ let info;
103
+ try {
104
+ info = await inspectPath(directoryPath);
105
+ } catch (error) {
106
+ if (allowMissing && error && typeof error === "object" && error.code === "ENOENT") return;
107
+ throw error;
108
+ }
109
+ if (info.isSymbolicLink() || !info.isDirectory()) {
110
+ throw new Error(
111
+ `Backup directory must be a real directory, not a symbolic link: ${formatDisplayValue(directoryPath)}`,
112
+ );
113
+ }
114
+ }
115
+
99
116
  async function assertBackupMissing(backupPath, inspectPath) {
100
117
  try {
101
118
  await inspectPath(backupPath);
@@ -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
+ }