@narumitw/pi-starship 0.55.1 → 0.56.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.
Files changed (106) hide show
  1. package/README.md +2 -0
  2. package/dist/chunks/{chunk-UX6PBXVK.js → chunk-SD7TUSSU.js} +113 -113
  3. package/dist/chunks/chunk-SD7TUSSU.js.map +7 -0
  4. package/dist/chunks/{chunk-P4XMFSQW.js → chunk-YWY5RIDQ.js} +3 -7
  5. package/dist/chunks/chunk-YWY5RIDQ.js.map +7 -0
  6. package/dist/chunks/{chunk-EOGXAMTA.js → chunk-ZQZSXXPI.js} +1 -1
  7. package/dist/chunks/chunk-ZQZSXXPI.js.map +7 -0
  8. package/dist/chunks/{cloud-BKHYWCTA.js → cloud-C4VU3TX3.js} +7 -14
  9. package/dist/chunks/cloud-C4VU3TX3.js.map +7 -0
  10. package/dist/chunks/{commands-53ZO2JUK.js → commands-MJCAK6JL.js} +18 -42
  11. package/dist/chunks/commands-MJCAK6JL.js.map +7 -0
  12. package/dist/chunks/{deployment-RKKOEQQ2.js → deployment-FMNTYRBW.js} +6 -21
  13. package/dist/chunks/deployment-FMNTYRBW.js.map +7 -0
  14. package/dist/chunks/{development-BERD42HW.js → development-OUYXDPBS.js} +4 -8
  15. package/dist/chunks/development-OUYXDPBS.js.map +7 -0
  16. package/dist/chunks/{execution-42JTEY3N.js → execution-HJOGLMWD.js} +3 -3
  17. package/dist/chunks/execution-HJOGLMWD.js.map +7 -0
  18. package/dist/chunks/{languages-RMP6DW7H.js → languages-WXMF4GOF.js} +6 -22
  19. package/dist/chunks/languages-WXMF4GOF.js.map +7 -0
  20. package/dist/chunks/{package-LG5H7BBM.js → package-YXRZQAOV.js} +5 -14
  21. package/dist/chunks/package-YXRZQAOV.js.map +7 -0
  22. package/dist/index.ts +20 -55
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +60 -61
  25. package/skills/configuring-pi-starship/SKILL.md +18 -4
  26. package/skills/configuring-pi-starship/references/configuration.md +70 -2
  27. package/skills/configuring-pi-starship/references/module-catalog.md +21 -0
  28. package/skills/configuring-pi-starship/references/modules.md +2 -0
  29. package/skills/configuring-pi-starship/scripts/apply.mjs +48 -47
  30. package/skills/configuring-pi-starship/scripts/backup.mjs +118 -0
  31. package/skills/configuring-pi-starship/scripts/config-path.mjs +3 -3
  32. package/skills/configuring-pi-starship/scripts/script-support.mjs +6 -6
  33. package/skills/configuring-pi-starship/scripts/validate.mjs +18 -18
  34. package/src/command-configuration.ts +267 -286
  35. package/src/command-contract.ts +6 -6
  36. package/src/command-inspector.ts +27 -27
  37. package/src/command-preset-picker.ts +45 -50
  38. package/src/command-preview.ts +153 -166
  39. package/src/commands.ts +590 -618
  40. package/src/config.ts +635 -660
  41. package/src/effective-config.ts +49 -48
  42. package/src/format/formatter.ts +211 -227
  43. package/src/format/style.ts +205 -216
  44. package/src/modules/activity.ts +74 -74
  45. package/src/modules/brand.ts +9 -9
  46. package/src/modules/cache.ts +18 -18
  47. package/src/modules/catalog.ts +79 -83
  48. package/src/modules/cloud.ts +54 -54
  49. package/src/modules/context.ts +27 -27
  50. package/src/modules/cost.ts +23 -23
  51. package/src/modules/deployment.ts +45 -45
  52. package/src/modules/development.ts +80 -81
  53. package/src/modules/directory.ts +89 -113
  54. package/src/modules/display.ts +9 -9
  55. package/src/modules/execution.ts +62 -69
  56. package/src/modules/extension-status.ts +59 -64
  57. package/src/modules/fill.ts +10 -10
  58. package/src/modules/git/branch.ts +26 -26
  59. package/src/modules/git/commit.ts +21 -23
  60. package/src/modules/git/metrics.ts +22 -22
  61. package/src/modules/git/runtime.ts +299 -334
  62. package/src/modules/git/state.ts +17 -17
  63. package/src/modules/git/status.ts +77 -79
  64. package/src/modules/git/worktree.ts +10 -12
  65. package/src/modules/github-pr.ts +20 -20
  66. package/src/modules/helpers.ts +3 -3
  67. package/src/modules/index.ts +21 -21
  68. package/src/modules/inspection.ts +105 -108
  69. package/src/modules/languages.ts +52 -59
  70. package/src/modules/model.ts +61 -67
  71. package/src/modules/package.ts +12 -12
  72. package/src/modules/provider.ts +25 -24
  73. package/src/modules/render.ts +131 -141
  74. package/src/modules/style-rules.ts +21 -0
  75. package/src/modules/thinking.ts +31 -26
  76. package/src/modules/time.ts +10 -13
  77. package/src/modules/tokens.ts +13 -13
  78. package/src/modules/truncation.ts +14 -17
  79. package/src/modules/turn.ts +9 -9
  80. package/src/modules/types.ts +133 -132
  81. package/src/modules/workspace-helpers.ts +4 -7
  82. package/src/pi-starship.ts +567 -603
  83. package/src/presets/catalog.ts +113 -113
  84. package/src/runtime/cloud.ts +122 -150
  85. package/src/runtime/command.ts +106 -108
  86. package/src/runtime/deployment.ts +150 -179
  87. package/src/runtime/development.ts +107 -124
  88. package/src/runtime/execution.ts +110 -124
  89. package/src/runtime/github-pr.ts +223 -252
  90. package/src/runtime/helpers.ts +186 -199
  91. package/src/runtime/languages.ts +149 -180
  92. package/src/runtime/package.ts +74 -87
  93. package/src/runtime/refresh-controller.ts +82 -86
  94. package/src/runtime/types.ts +38 -38
  95. package/src/runtime/workspace.ts +108 -116
  96. package/src/usage.ts +40 -40
  97. package/dist/chunks/chunk-EOGXAMTA.js.map +0 -7
  98. package/dist/chunks/chunk-P4XMFSQW.js.map +0 -7
  99. package/dist/chunks/chunk-UX6PBXVK.js.map +0 -7
  100. package/dist/chunks/cloud-BKHYWCTA.js.map +0 -7
  101. package/dist/chunks/commands-53ZO2JUK.js.map +0 -7
  102. package/dist/chunks/deployment-RKKOEQQ2.js.map +0 -7
  103. package/dist/chunks/development-BERD42HW.js.map +0 -7
  104. package/dist/chunks/execution-42JTEY3N.js.map +0 -7
  105. package/dist/chunks/languages-RMP6DW7H.js.map +0 -7
  106. package/dist/chunks/package-LG5H7BBM.js.map +0 -7
@@ -79,7 +79,13 @@ Create a separate draft without changing the active document, then make the smal
79
79
 
80
80
  When the active document exists, also keep an untouched baseline file containing the exact bytes initially inspected.
81
81
 
82
- When it is missing, use the explicit `--expect-missing` state instead of creating a baseline.
82
+ Before replacing that document, the apply script saves the baseline permanently under `<directory containing pi-starship.toml>/pi-starship/` with a local-time name such as `pi-starship-202609130742.toml`.
83
+
84
+ For the default settings path, this backup directory is `<getAgentDir()>/pi-starship/`.
85
+
86
+ If that minute's backup name exists when checked, publication stops without changing the active document; this check does not lock out another process before rename, and retained backups are never deliberately removed by this workflow.
87
+
88
+ When the active document is missing, use the explicit `--expect-missing` state instead of creating a baseline or backup.
83
89
 
84
90
  Resolve the bundled scripts relative to this `SKILL.md`, validate the draft, and publish it through the guarded atomic apply script:
85
91
 
@@ -94,15 +100,23 @@ node "$skill_dir/scripts/apply.mjs" "$draft_path" "$config_path" "$expected_stat
94
100
 
95
101
  The apply script stages the proposed bytes in the destination directory, validates that staged file, and immediately re-reads the active path.
96
102
 
97
- It rejects publication when the active bytes differ from the baseline or when a supposedly missing document has appeared, then renames the staged file over the unchanged path.
103
+ It rejects publication when the active bytes differ from the baseline or when a supposedly missing document has appeared.
104
+
105
+ For an existing document, it writes and flushes the backup to a private temporary file, confirms that the minute's final backup name is absent, atomically renames the completed backup into place, and flushes the backup directory and its parent directory before renaming the staged configuration over the unchanged active path.
106
+
107
+ It removes its owned temporary backup after a recoverable write or publication failure; if cleanup also fails, it reports the primary failure and every cleanup failure while preserving the active document.
108
+
109
+ If configuration publication fails after the backup is durable, it reports the retained backup path and preserves the active document.
98
110
 
99
111
  This comparison does not lock out other processes after the re-read, so do not claim cross-process synchronization.
100
112
 
101
113
  Fix every TOML syntax error and rerun the validator unless the user explicitly requested an invalid test fixture, which must not replace the active document.
102
114
 
103
- Remove the separate draft and baseline after a successful publication, then re-read the saved document and review the exact change for accidental replacement or unrelated edits.
115
+ Remove the separate draft and temporary baseline after a successful publication, but keep the durable timestamped backup.
116
+
117
+ Then re-read the saved document and review the exact change for accidental replacement or unrelated edits.
104
118
 
105
- Report the edited path, the effective layout or module change, and the validator and atomic-publication results.
119
+ Report the edited path, durable backup path when one was created, effective layout or module change, and validator and atomic-publication results.
106
120
 
107
121
  External edits do not update an active footer immediately.
108
122
 
@@ -1,6 +1,6 @@
1
1
  # Configuration and Format Reference
2
2
 
3
- Use this authoritative public reference for configuration location and persistence, presets, complete-document examples, format grammar, styles, palettes, and state-selected styles.
3
+ Use this authoritative public reference for configuration location and persistence, presets, complete-document examples, format grammar, styles, palettes, content-selected styles, and state-selected styles.
4
4
 
5
5
  ## ⚙️ Settings
6
6
 
@@ -29,11 +29,18 @@ Saving requires separate confirmation, then atomically updates the file and acti
29
29
  Manual TOML edits load at the next `session_start`, including `/reload` and session replacement.
30
30
  Cancellation, disposal, invalid drafts, write failures, and runtime application failures preserve the previous file and footer.
31
31
 
32
+ The bundled `configuring-pi-starship` skill uses a separate external-edit workflow.
33
+ Before its apply script replaces an existing document, it preserves the inspected document under `<getAgentDir()>/pi-starship/pi-starship-YYYYMMDDHHmm.toml`; these backups use local time and remain after a successful apply.
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
+ 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
+ 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.
38
+
32
39
  The shallow main menu also exposes **Presets**, **Explain footer**, **Modules**, **Configuration**, **Help**, and **Restore built-in…**.
33
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.
34
41
  Modules opens a bounded searchable inspector for every registered module.
35
42
  Its textual states distinguish **Showing**, **Empty**, **Disabled**, **Not in format**, and **Unavailable** only when the current footer cannot provide an inspection snapshot.
36
- Module detail shows the current preview when available, description, root reference and reachability, format variables, style fields, display rules, and the known reason for absent output.
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.
37
44
  Both views are read-only and do not create or update the settings document.
38
45
 
39
46
  Configuration contains **Overview**, **Effective configuration**, **Settings document**, and **Reload from disk** on one nested level.
@@ -90,6 +97,7 @@ There is no `/starship preset` textual route and no remote preset download.
90
97
  ```toml
91
98
  format = """
92
99
  $brand\
100
+ $provider\
93
101
  $model\
94
102
  $thinking\
95
103
  $directory\
@@ -107,6 +115,21 @@ truncation_length = 36
107
115
  truncation_symbol = "…"
108
116
  truncation_direction = "middle"
109
117
 
118
+ [provider]
119
+ style = "bold green"
120
+
121
+ [[provider.style_rules]]
122
+ provider = "openai"
123
+ style = "bold blue"
124
+
125
+ [[model.style_rules]]
126
+ provider = "openai"
127
+ style = "bold blue"
128
+
129
+ [[thinking.style_rules]]
130
+ provider = "openai"
131
+ style = "bold blue"
132
+
110
133
  [directory]
111
134
  style = "cyan bold"
112
135
 
@@ -195,6 +218,7 @@ The exact accepted style fields, display arrays, module-specific options, defaul
195
218
  `disabled` must be boolean.
196
219
  A standard `style` field must be a valid style string.
197
220
  `thinking` accepts `style` plus `style_off`, `style_minimal`, `style_low`, `style_medium`, `style_high`, `style_xhigh`, and `style_max`.
221
+ `provider`, `model`, and `thinking` additionally accept the ordered `style_rules` arrays described under [Content-selected styles](#content-selected-styles).
198
222
  `git_metrics` accepts `added_style` and `deleted_style` instead of `style`.
199
223
  `username` accepts `style_user` and `style_root` instead of `style`.
200
224
  `context` and `cost` accept `display` arrays instead of a direct `style` field.
@@ -245,6 +269,8 @@ Detection fallback and replacement behavior differs by module and is specified i
245
269
  | Unknown format or style variable | Warn and render that variable empty. |
246
270
  | Invalid literal group style | Warn and render that group unstyled. |
247
271
  | Invalid module style field | Warn and restore only that style field's module default. |
272
+ | Invalid `style_rules` value | Warn and use an empty rule array for that module. |
273
+ | Invalid style-rule entry | Warn and discard only that entry. |
248
274
  | Invalid palette color | Warn and omit only that palette entry. |
249
275
  | Invalid module option | Warn and restore only that option's default. |
250
276
  | Invalid display entry | Warn and discard only that entry; restore defaults if none remain. |
@@ -304,6 +330,48 @@ An invalid root format falls back to the built-in root format; an invalid module
304
330
  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"`.
305
331
  Context, cost, Git metrics, and username use the state/multi-style defaults below.
306
332
 
333
+ ### Content-selected styles
334
+
335
+ `provider`, `model`, and `thinking` can replace their `$style` value with the first matching entry from an ordered `style_rules` array.
336
+ The built-in root format omits `provider`, so add `$provider` to a custom root format or use `$all` when provider output should be visible:
337
+
338
+ ```toml
339
+ format = "$provider$model$thinking"
340
+
341
+ [provider]
342
+ style = "bold green"
343
+
344
+ [[provider.style_rules]]
345
+ provider = "openai"
346
+ style = "bold blue"
347
+
348
+ [[provider.style_rules]]
349
+ style = "bold white" # catch-all because it declares no selectors
350
+ ```
351
+
352
+ Matching is exact and case-sensitive.
353
+ Every selector declared by a rule must match, rules are checked in document order, and the first complete match wins.
354
+ A rule containing only `style` is a catch-all, so later entries cannot win after it.
355
+ When a declared runtime value is unavailable, that rule does not match.
356
+ If no rule matches, the module keeps its existing selected style: ordinary `style` for `provider` and `model`, and the matching non-empty `style_<level>` or `style` fallback for `thinking`.
357
+ A selected rule changes only `$style`, so a custom module format without `$style` has no visible style change.
358
+
359
+ The exact selectors are:
360
+
361
+ | Module | Selector | Compared value |
362
+ | --- | --- | --- |
363
+ | `provider` | `provider` | Raw Pi provider ID. |
364
+ | `model` | `provider` | Raw Pi provider ID. |
365
+ | `model` | `model` | Raw Pi model ID. |
366
+ | `thinking` | `provider` | Raw Pi provider ID. |
367
+ | `thinking` | `level` | Current Pi thinking-level string. |
368
+
369
+ Provider and model aliases, built-in model shortening, configured truncation, and terminal display sanitization do not change these raw selector values.
370
+ Style-rule styles use the selected palette and the same style grammar as other style fields.
371
+ An unknown field, unsupported selector, non-string selector, missing style, or invalid style warns and discards only that rule; valid sibling rules remain ordered and active.
372
+ An invalid non-array `style_rules` value warns and restores the empty default.
373
+ `style_rules` on any other module is an unknown setting.
374
+
307
375
  ### Thinking level styles
308
376
 
309
377
  `thinking` can override its appearance for `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` independently:
@@ -16,6 +16,7 @@ Every `[module]` table accepts these fields:
16
16
 
17
17
  Most modules also accept `style` as listed below.
18
18
  Modules with state-selected or multiple style fields list those exact fields instead.
19
+ `provider`, `model`, and `thinking` additionally accept an ordered `style_rules` array whose default is empty; each module section lists its exact selectors.
19
20
  Unknown fields warn and remain inactive.
20
21
  A wrong type or out-of-range option warns and uses that field's default.
21
22
 
@@ -62,6 +63,12 @@ Accepted style fields:
62
63
  | --- | --- |
63
64
  | `style` | `"bold blue"` |
64
65
 
66
+ Accepted style-rule selectors (`style_rules` default: `[]`):
67
+
68
+ | Selector | Matched value |
69
+ | --- | --- |
70
+ | `provider` | Raw Pi provider ID. |
71
+
65
72
  Additional options:
66
73
 
67
74
  | Option | Type | Default | Constraints and meaning |
@@ -84,6 +91,13 @@ Accepted style fields:
84
91
  | --- | --- |
85
92
  | `style` | `"bold blue"` |
86
93
 
94
+ Accepted style-rule selectors (`style_rules` default: `[]`):
95
+
96
+ | Selector | Matched value |
97
+ | --- | --- |
98
+ | `provider` | Raw Pi provider ID. |
99
+ | `model` | Raw Pi model ID. |
100
+
87
101
  Additional options:
88
102
 
89
103
  | Option | Type | Default | Constraints and meaning |
@@ -116,6 +130,13 @@ Accepted style fields:
116
130
  | `style_xhigh` | `""` |
117
131
  | `style_max` | `""` |
118
132
 
133
+ Accepted style-rule selectors (`style_rules` default: `[]`):
134
+
135
+ | Selector | Matched value |
136
+ | --- | --- |
137
+ | `provider` | Raw Pi provider ID. |
138
+ | `level` | Current Pi thinking-level string. |
139
+
119
140
  ### `directory`
120
141
 
121
142
  Current working directory.
@@ -217,6 +217,8 @@ provider_aliases = { "openai-codex" = "codex", "amazon-bedrock" = "bedrock" }
217
217
 
218
218
  An empty alias hides only the provider text.
219
219
  Provider names and aliases are stripped of terminal controls at render time.
220
+ The `provider`, `model`, and `thinking` modules match `style_rules` against raw provider/model IDs and thinking levels before aliases, built-in model shortening, configured truncation, or display sanitization.
221
+ A selector whose runtime value is unavailable does not match; exact selector fields and precedence are documented in [Configuration and Format](configuration.md#content-selected-styles).
220
222
  For example, `middle` can retain both a Hugging Face model family and its variant, while `start` is useful when a llama.cpp server reports an absolute model path.
221
223
  pi-starship treats model IDs as opaque strings and does not parse paths, repositories, GGUF suffixes, or quantization names.
222
224
 
@@ -4,61 +4,62 @@ import { randomUUID } from "node:crypto";
4
4
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join } from "node:path";
6
6
  import { parse } from "smol-toml";
7
+ import { backupExpectedDocument } from "./backup.mjs";
7
8
  import { formatDisplayValue, formatError } from "./script-support.mjs";
8
9
 
9
10
  const [draftPath, destinationPath, expectedPath, ...extraArguments] = process.argv.slice(2);
10
11
 
11
12
  if (!draftPath || !destinationPath || !expectedPath || extraArguments.length > 0) {
12
- console.error(
13
- "Usage: node scripts/apply.mjs <draft-path> <absolute-pi-starship.toml-path> <expected-path|--expect-missing>",
14
- );
15
- process.exitCode = 2;
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;
16
17
  } else if (!isAbsolute(destinationPath) || basename(destinationPath) !== "pi-starship.toml") {
17
- console.error("The destination must be an absolute path named pi-starship.toml.");
18
- process.exitCode = 2;
18
+ console.error("The destination must be an absolute path named pi-starship.toml.");
19
+ process.exitCode = 2;
19
20
  } else {
20
- let temporaryPath;
21
- try {
22
- const draft = await readFile(draftPath, "utf8");
23
- const expectMissing = expectedPath === "--expect-missing";
24
- const expected = expectMissing ? undefined : await readFile(expectedPath, "utf8");
25
- await mkdir(dirname(destinationPath), { recursive: true });
26
- temporaryPath = join(dirname(destinationPath), `.pi-starship.toml.${randomUUID()}.tmp`);
27
- await writeFile(temporaryPath, draft, { encoding: "utf8", flag: "wx" });
28
- parse(await readFile(temporaryPath, "utf8"));
29
- await assertDestinationUnchanged(destinationPath, expectMissing, expected);
30
- await rename(temporaryPath, destinationPath);
31
- temporaryPath = undefined;
32
- console.log(`Applied valid TOML atomically to ${formatDisplayValue(destinationPath)}`);
33
- } catch (error) {
34
- console.error(
35
- `Draft was not applied to ${formatDisplayValue(destinationPath)}: ${formatError(error)}`,
36
- );
37
- process.exitCode = 1;
38
- } finally {
39
- if (temporaryPath) {
40
- try {
41
- await rm(temporaryPath, { force: true });
42
- } catch {
43
- // Cleanup is best-effort and must not obscure the original failure.
44
- }
45
- }
46
- }
21
+ let temporaryPath;
22
+ let backupPath;
23
+ try {
24
+ const draft = await readFile(draftPath, "utf8");
25
+ const expectMissing = expectedPath === "--expect-missing";
26
+ const expected = expectMissing ? undefined : await readFile(expectedPath);
27
+ await mkdir(dirname(destinationPath), { recursive: true });
28
+ 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);
34
+ 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)}`);
37
+ } 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
+ if (temporaryPath) {
43
+ try {
44
+ await rm(temporaryPath, { force: true });
45
+ } catch {
46
+ // Cleanup is best-effort and must not obscure the original failure.
47
+ }
48
+ }
49
+ }
47
50
  }
48
51
 
49
52
  async function assertDestinationUnchanged(destinationPath, expectMissing, expected) {
50
- let current;
51
- try {
52
- current = await readFile(destinationPath, "utf8");
53
- } catch (error) {
54
- if (error && typeof error === "object" && error.code === "ENOENT") {
55
- if (expectMissing) return;
56
- throw new Error("The active pi-starship.toml was removed after inspection.");
57
- }
58
- throw error;
59
- }
60
- if (!expectMissing && current === expected) return;
61
- throw new Error(
62
- "The active pi-starship.toml changed after inspection; the newer file was preserved.",
63
- );
53
+ let current;
54
+ try {
55
+ current = await readFile(destinationPath);
56
+ } catch (error) {
57
+ if (error && typeof error === "object" && error.code === "ENOENT") {
58
+ if (expectMissing) return;
59
+ throw new Error("The active pi-starship.toml was removed after inspection.");
60
+ }
61
+ throw error;
62
+ }
63
+ if (!expectMissing && expected !== undefined && current.equals(expected)) return;
64
+ throw new Error("The active pi-starship.toml changed after inspection; the newer file was preserved.");
64
65
  }
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, open, rename, rm } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { formatDisplayValue, formatError } from "./script-support.mjs";
5
+
6
+ const PRIVATE_DIRECTORY_MODE = 0o700;
7
+ const PRIVATE_FILE_MODE = 0o600;
8
+ const MAX_EMBEDDED_ERROR_LENGTH = 240;
9
+ const MAX_NESTED_DIRECTORY_ERROR_LENGTH = 80;
10
+
11
+ export async function backupExpectedDocument(destinationPath, expected, options = {}) {
12
+ const backupDirectory = join(dirname(destinationPath), "pi-starship");
13
+ const backupPath = join(backupDirectory, `pi-starship-${localTimestamp(options.now ?? new Date())}.toml`);
14
+ const temporaryPath = join(backupDirectory, `.pi-starship-${randomUUID()}.tmp`);
15
+ const inspectPath = options.inspectPath ?? lstat;
16
+ const makeDirectory = options.makeDirectory ?? mkdir;
17
+ const openFile = options.openFile ?? open;
18
+ const removeFile = options.removeFile ?? rm;
19
+ const renameFile = options.renameFile ?? rename;
20
+ const syncDirectory = options.syncDirectory ?? syncDirectoryEntry;
21
+
22
+ await makeDirectory(backupDirectory, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
23
+
24
+ let handle;
25
+ let ownsTemporaryPath = false;
26
+ let backupPublished = false;
27
+ try {
28
+ handle = await openFile(temporaryPath, "wx", PRIVATE_FILE_MODE);
29
+ ownsTemporaryPath = true;
30
+ await handle.writeFile(expected);
31
+ await handle.sync();
32
+ await handle.close();
33
+ handle = undefined;
34
+ await assertBackupMissing(backupPath, inspectPath);
35
+ await renameFile(temporaryPath, backupPath);
36
+ ownsTemporaryPath = false;
37
+ backupPublished = true;
38
+ await syncDirectory(backupDirectory);
39
+ await syncDirectory(dirname(backupDirectory));
40
+ return backupPath;
41
+ } catch (error) {
42
+ const cleanupErrors = [];
43
+ if (handle) {
44
+ try {
45
+ await handle.close();
46
+ } catch (closeError) {
47
+ cleanupErrors.push({ operation: "closing the temporary backup", error: closeError });
48
+ }
49
+ }
50
+ if (ownsTemporaryPath) {
51
+ try {
52
+ await removeFile(temporaryPath, { force: true });
53
+ } catch (removeError) {
54
+ cleanupErrors.push({ operation: "removing the temporary backup", error: removeError });
55
+ }
56
+ }
57
+ if (cleanupErrors.length > 0) {
58
+ const diagnostics = cleanupErrors
59
+ .map(({ operation, error: cleanupError }) => `${operation}: ${formatEmbeddedError(cleanupError)}`)
60
+ .join("; ");
61
+ throw new Error(
62
+ `Backup creation failed: ${formatEmbeddedError(error)}. Cleanup also failed (${diagnostics}). The active file was preserved.`,
63
+ );
64
+ }
65
+ if (backupPublished) {
66
+ throw new Error(
67
+ `Backup was retained at ${formatDisplayValue(backupPath)}, but its directory durability check failed: ${formatEmbeddedError(error)}. The active file was preserved.`,
68
+ );
69
+ }
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ async function syncDirectoryEntry(directoryPath) {
75
+ if (process.platform === "win32") return;
76
+
77
+ const handle = await open(directoryPath, "r");
78
+ let syncError;
79
+ try {
80
+ await handle.sync();
81
+ } catch (error) {
82
+ syncError = error;
83
+ }
84
+
85
+ try {
86
+ await handle.close();
87
+ } catch (closeError) {
88
+ if (syncError) {
89
+ throw new Error(
90
+ `Directory sync failed: ${formatEmbeddedError(syncError, MAX_NESTED_DIRECTORY_ERROR_LENGTH)}. Closing the directory also failed: ${formatEmbeddedError(closeError, MAX_NESTED_DIRECTORY_ERROR_LENGTH)}.`,
91
+ );
92
+ }
93
+ throw closeError;
94
+ }
95
+
96
+ if (syncError) throw syncError;
97
+ }
98
+
99
+ async function assertBackupMissing(backupPath, inspectPath) {
100
+ try {
101
+ await inspectPath(backupPath);
102
+ } catch (error) {
103
+ if (error && typeof error === "object" && error.code === "ENOENT") return;
104
+ throw error;
105
+ }
106
+ throw new Error(`Backup already exists at ${formatDisplayValue(backupPath)}; the active file was preserved.`);
107
+ }
108
+
109
+ function formatEmbeddedError(error, maximumLength = MAX_EMBEDDED_ERROR_LENGTH) {
110
+ const diagnostic = formatError(error);
111
+ return diagnostic.length > maximumLength ? `${diagnostic.slice(0, maximumLength - 1)}…` : diagnostic;
112
+ }
113
+
114
+ function localTimestamp(date) {
115
+ return [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
116
+ .map((value, index) => String(value).padStart(index === 0 ? 4 : 2, "0"))
117
+ .join("");
118
+ }
@@ -4,8 +4,8 @@ import { resolve } from "node:path";
4
4
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
5
 
6
6
  if (process.argv.length > 2) {
7
- console.error("Usage: node scripts/config-path.mjs");
8
- process.exitCode = 2;
7
+ console.error("Usage: node scripts/config-path.mjs");
8
+ process.exitCode = 2;
9
9
  } else {
10
- process.stdout.write(`${JSON.stringify(resolve(getAgentDir(), "pi-starship.toml"))}\n`);
10
+ process.stdout.write(`${JSON.stringify(resolve(getAgentDir(), "pi-starship.toml"))}\n`);
11
11
  }
@@ -5,16 +5,16 @@ const MAX_ERROR_SOURCE_LENGTH = 8000;
5
5
  const MAX_DISPLAY_VALUE_LENGTH = 500;
6
6
 
7
7
  export function formatError(error) {
8
- const raw = error instanceof Error ? error.message : String(error);
9
- return sanitizeAndBound(raw, MAX_ERROR_LENGTH, MAX_ERROR_SOURCE_LENGTH);
8
+ const raw = error instanceof Error ? error.message : String(error);
9
+ return sanitizeAndBound(raw, MAX_ERROR_LENGTH, MAX_ERROR_SOURCE_LENGTH);
10
10
  }
11
11
 
12
12
  export function formatDisplayValue(value) {
13
- return JSON.stringify(sanitizeAndBound(String(value), MAX_DISPLAY_VALUE_LENGTH, 4000));
13
+ return JSON.stringify(sanitizeAndBound(String(value), MAX_DISPLAY_VALUE_LENGTH, 4000));
14
14
  }
15
15
 
16
16
  function sanitizeAndBound(value, maximumLength, maximumSourceLength) {
17
- const result = sanitizeTerminalText(value.slice(0, maximumSourceLength));
18
- const truncated = value.length > maximumSourceLength || result.length > maximumLength;
19
- return truncated ? `${result.slice(0, Math.max(0, maximumLength - 1))}…` : result;
17
+ const result = sanitizeTerminalText(value.slice(0, maximumSourceLength));
18
+ const truncated = value.length > maximumSourceLength || result.length > maximumLength;
19
+ return truncated ? `${result.slice(0, Math.max(0, maximumLength - 1))}…` : result;
20
20
  }
@@ -7,24 +7,24 @@ import { formatDisplayValue, formatError } from "./script-support.mjs";
7
7
  const [filePath, ...extraArguments] = process.argv.slice(2);
8
8
 
9
9
  if (!filePath || extraArguments.length > 0) {
10
- console.error("Usage: node scripts/validate.mjs <absolute-pi-starship.toml-path>");
11
- process.exitCode = 2;
10
+ console.error("Usage: node scripts/validate.mjs <absolute-pi-starship.toml-path>");
11
+ process.exitCode = 2;
12
12
  } else {
13
- let document;
14
- try {
15
- document = await readFile(filePath, "utf8");
16
- } catch (error) {
17
- console.error(`Unable to read ${formatDisplayValue(filePath)}: ${formatError(error)}`);
18
- process.exitCode = 1;
19
- }
13
+ let document;
14
+ try {
15
+ document = await readFile(filePath, "utf8");
16
+ } catch (error) {
17
+ console.error(`Unable to read ${formatDisplayValue(filePath)}: ${formatError(error)}`);
18
+ process.exitCode = 1;
19
+ }
20
20
 
21
- if (document !== undefined) {
22
- try {
23
- parse(document);
24
- console.log(`Valid TOML: ${formatDisplayValue(filePath)}`);
25
- } catch (error) {
26
- console.error(`Invalid TOML in ${formatDisplayValue(filePath)}: ${formatError(error)}`);
27
- process.exitCode = 1;
28
- }
29
- }
21
+ if (document !== undefined) {
22
+ try {
23
+ parse(document);
24
+ console.log(`Valid TOML: ${formatDisplayValue(filePath)}`);
25
+ } catch (error) {
26
+ console.error(`Invalid TOML in ${formatDisplayValue(filePath)}: ${formatError(error)}`);
27
+ process.exitCode = 1;
28
+ }
29
+ }
30
30
  }