@osdlc/wayfinder 0.7.3 → 0.8.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 (121) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/CONTRIBUTING.md +6 -0
  3. package/README.md +295 -150
  4. package/SECURITY.md +19 -5
  5. package/dist/actions.d.ts +23 -0
  6. package/dist/actions.js +97 -0
  7. package/dist/app.d.ts +1 -13
  8. package/dist/app.js +1 -13
  9. package/dist/args.d.ts +11 -6
  10. package/dist/args.js +25 -7
  11. package/dist/cache.d.ts +2 -4
  12. package/dist/cache.js +5 -10
  13. package/dist/catalog.d.ts +30 -3
  14. package/dist/catalog.js +87 -11
  15. package/dist/clean-command.d.ts +65 -36
  16. package/dist/clean-command.js +372 -226
  17. package/dist/cli.d.ts +24 -57
  18. package/dist/cli.js +139 -568
  19. package/dist/commands/browse.d.ts +128 -0
  20. package/dist/commands/browse.js +151 -0
  21. package/dist/commands/index.d.ts +25 -0
  22. package/dist/commands/index.js +71 -0
  23. package/dist/commands/list.d.ts +208 -0
  24. package/dist/commands/list.js +127 -0
  25. package/dist/commands/query.d.ts +166 -0
  26. package/dist/commands/query.js +73 -0
  27. package/dist/commands/run.d.ts +114 -0
  28. package/dist/commands/run.js +139 -0
  29. package/dist/commands/shared.d.ts +152 -0
  30. package/dist/commands/shared.js +209 -0
  31. package/dist/config-command.d.ts +27 -43
  32. package/dist/config-command.js +129 -330
  33. package/dist/config-keys.d.ts +25 -0
  34. package/dist/config-keys.js +29 -0
  35. package/dist/config.d.ts +271 -257
  36. package/dist/config.js +610 -460
  37. package/dist/core/copy-text.d.ts +30 -0
  38. package/dist/core/copy-text.js +50 -0
  39. package/dist/core/filter.d.ts +55 -0
  40. package/dist/core/filter.js +59 -0
  41. package/dist/core/run.d.ts +22 -0
  42. package/dist/core/run.js +59 -0
  43. package/dist/core/saved-view.d.ts +59 -0
  44. package/dist/core/saved-view.js +119 -0
  45. package/dist/core/session.d.ts +262 -0
  46. package/dist/core/session.js +589 -0
  47. package/dist/core/skills.d.ts +53 -0
  48. package/dist/core/skills.js +54 -0
  49. package/dist/core/unknowns.d.ts +72 -0
  50. package/dist/core/unknowns.js +68 -0
  51. package/dist/devlink.d.ts +3 -0
  52. package/dist/devlink.js +5 -2
  53. package/dist/document-schemas.generated.d.ts +22 -0
  54. package/dist/document-schemas.generated.js +916 -0
  55. package/dist/documents.d.ts +432 -0
  56. package/dist/documents.js +163 -0
  57. package/dist/groups.d.ts +22 -26
  58. package/dist/groups.js +13 -29
  59. package/dist/guide.d.ts +26 -13
  60. package/dist/guide.js +119 -103
  61. package/dist/index.d.ts +112 -0
  62. package/dist/index.js +58 -0
  63. package/dist/keys.d.ts +51 -0
  64. package/dist/keys.js +273 -0
  65. package/dist/page.d.ts +18 -8
  66. package/dist/page.js +28 -17
  67. package/dist/providers-command.d.ts +81 -20
  68. package/dist/providers-command.js +33 -75
  69. package/dist/schema.d.ts +48 -0
  70. package/dist/schema.js +61 -0
  71. package/dist/serve/auth.d.ts +46 -0
  72. package/dist/serve/auth.js +82 -0
  73. package/dist/serve/catalog-share.d.ts +51 -0
  74. package/dist/serve/catalog-share.js +116 -0
  75. package/dist/serve/index.d.ts +98 -0
  76. package/dist/serve/index.js +251 -0
  77. package/dist/serve/routes.d.ts +60 -0
  78. package/dist/serve/routes.js +186 -0
  79. package/dist/serve/terminal-input.d.ts +50 -0
  80. package/dist/serve/terminal-input.js +108 -0
  81. package/dist/skills.d.ts +19 -0
  82. package/dist/skills.js +54 -0
  83. package/dist/terminal-text.d.ts +8 -0
  84. package/dist/terminal-text.js +19 -6
  85. package/dist/tool-info.d.ts +24 -0
  86. package/dist/tool-info.js +17 -0
  87. package/dist/trust-command.d.ts +15 -27
  88. package/dist/trust-command.js +110 -208
  89. package/dist/trust-store.d.ts +5 -10
  90. package/dist/trust-store.js +9 -42
  91. package/dist/tui/app.d.ts +180 -0
  92. package/dist/tui/app.js +1278 -0
  93. package/dist/tui/copy.d.ts +29 -0
  94. package/dist/tui/copy.js +39 -0
  95. package/dist/tui/index.d.ts +33 -0
  96. package/dist/tui/index.js +97 -0
  97. package/dist/tui/keys-input.d.ts +27 -0
  98. package/dist/tui/keys-input.js +87 -0
  99. package/dist/tui/settings.d.ts +94 -0
  100. package/dist/tui/settings.js +198 -0
  101. package/dist/tui/style.d.ts +62 -0
  102. package/dist/tui/style.js +77 -0
  103. package/dist/version.d.ts +6 -0
  104. package/dist/version.js +7 -0
  105. package/dist/vocabulary.d.ts +89 -0
  106. package/dist/vocabulary.js +153 -0
  107. package/dist/web/main.js +1965 -568
  108. package/dist/web/page.html +39 -33
  109. package/dist/web/styles.css +457 -329
  110. package/dist/xdg.d.ts +76 -4
  111. package/dist/xdg.js +77 -5
  112. package/package.json +28 -9
  113. package/schema/config.json +133 -0
  114. package/dist/http.d.ts +0 -22
  115. package/dist/http.js +0 -149
  116. package/dist/origin-owner.d.ts +0 -19
  117. package/dist/origin-owner.js +0 -85
  118. package/dist/serve.d.ts +0 -98
  119. package/dist/serve.js +0 -671
  120. package/dist/tui.d.ts +0 -177
  121. package/dist/tui.js +0 -840
@@ -1,86 +1,131 @@
1
1
  /**
2
- * The `clean` subcommand: the three stores wayfinder keeps outside your
3
- * repositories (cache, trust, config). `--cache` and `--trust` also clear
4
- * the old waypost cache and trust store. An old store is listed only when it
5
- * holds something.
2
+ * `way clean`: the data wayfinder keeps outside your repositories. Bare
3
+ * `clean` only reports what each store is, where it is, and whether anything
4
+ * is in it. A flag names what to remove; with no flag nothing is removed.
6
5
  *
7
- * ## Nothing is removed unless asked
6
+ * | flag | store |
7
+ * |---|---|
8
+ * | `--cache` | stored probe results: derived, costs one slow probe |
9
+ * | `--trust` | the repositories you trusted: consent, asked again |
10
+ * | `--user-config` | your user config: the only store a person wrote, so it needs `--yes` |
11
+ * | `--dev` | `way dev` link state, and the `way dev install` shims on PATH |
12
+ * | `--legacy` | files kept under the tool's name before its first release |
8
13
  *
9
- * Bare `clean` only reports: what each store is, where it is, and whether
10
- * anything is in it. A `--dry-run` flag would put the safe behaviour behind a
11
- * flag people forget. Instead the flags name what to remove, and with no flag
12
- * nothing is removed.
14
+ * `--everything` is every one of them, and needs `--yes`. A store that is only
15
+ * listed when it holds something (shims, old files) is left out of the report
16
+ * when it is empty. Once a store is gone, the directories above it are removed
17
+ * while they are empty, up to the base directory (`~/.config`, say).
13
18
  *
14
- * ## Why `--config` alone needs `--yes`
19
+ * Nothing inside a repository is touched: `wayfinder.config.json` belongs to
20
+ * the project. A user config that `WAYFINDER_CONFIG` names is named with the
21
+ * variable in the report and again before it is removed, since it may live in
22
+ * a dotfiles repository.
15
23
  *
16
- * The three stores are not equally easy to replace, and the check follows
17
- * that:
18
- *
19
- * - The cache is derived. Deleting it costs one slow probe.
20
- * - The trust store is consent. Deleting it means answering the trust
21
- * question again for each repository. That is annoying, but nothing is lost.
22
- * - The config is the only one a person wrote. Nothing regenerates it.
23
- *
24
- * So `--config` (and `--all`, which includes it) also needs `--yes`.
25
- *
26
- * ## What it will not touch
27
- *
28
- * Anything inside a repository. `wayfinder.config.json` is a project file that
29
- * belongs to whoever wrote it, not to this tool's data. Only paths under the
30
- * user's home (or their XDG overrides) are removed.
31
- *
32
- * `stdout`, `stderr`, `env` and `home` are injected, so a test cannot read or
33
- * delete the developer's real stores.
24
+ * Clean removes only what it owns. A file store must be a file (a symbolic
25
+ * link is removed, not its target), a directory store a directory, and no
26
+ * store may be the home directory, a directory above it or a filesystem root.
27
+ * A store whose path is, holds or sits in another flag's store is removed
28
+ * only with `--yes`.
29
+ * A file `WAYFINDER_CONFIG` names is removed only when its `$schema` names
30
+ * wayfinder's config schema, which every file wayfinder writes has.
31
+ */
32
+ import { lstat, readFile, readdir, rm, rmdir, stat } from 'node:fs/promises';
33
+ import { dirname, join, relative, isAbsolute, resolve } from 'node:path';
34
+ import { z } from 'zod';
35
+ import { UsageError, commandKit, outcome, } from '@osdlc/cli-tool/command';
36
+ import { defaultBinDir, readShimTarget, stateDir } from '@osdlc/cli-tool/devlink';
37
+ import { EXIT } from '@osdlc/cli-tool/exit';
38
+ import { APP, BIN, CONFIG_ENV_VAR } from "./app.js";
39
+ import { commandEnv } from "./config-command.js";
40
+ import { configLocations } from "./config.js";
41
+ import { WAYFINDER_SPEC } from "./devlink.js";
42
+ import { terminalSafe } from "./terminal-text.js";
43
+ import { appDirs, appTieredDirs, pre08Bases } from "./xdg.js";
44
+ /** The tool's name before its first release. Used only to find and remove its files. */
45
+ const OLD_NAME = 'waypost';
46
+ const KEYS = ['cache', 'trust', 'config', 'dev', 'legacy'];
47
+ /**
48
+ * The flag that names a store. The user config's is `--user-config`, since
49
+ * the app's global `--config` loads tool modules.
50
+ */
51
+ const FLAG_OF = {
52
+ cache: 'cache',
53
+ trust: 'trust',
54
+ config: 'userConfig',
55
+ dev: 'dev',
56
+ legacy: 'legacy',
57
+ };
58
+ const StoreReportSchema = z.object({
59
+ key: z.enum(KEYS),
60
+ flag: z.string(),
61
+ what: z.string(),
62
+ path: z.string(),
63
+ /** Bytes stored, or null when nothing is. A failed removal keeps its size, with `removed: false`. */
64
+ bytes: z.number().nullable(),
65
+ removed: z.boolean(),
66
+ /** The variable that named the path, when one did. */
67
+ envVar: z.string().optional(),
68
+ });
69
+ /** `way clean`'s output. */
70
+ export const CleanOutputSchema = z.object({
71
+ /** `report` for a bare `clean`, `remove` when a flag named something to remove. */
72
+ mode: z.enum(['report', 'remove']),
73
+ stores: z.array(StoreReportSchema),
74
+ });
75
+ /**
76
+ * Bytes under a path, or null when it does not exist. Symbolic links are not
77
+ * followed. With `shallow`, a directory is not walked: a file store's path
78
+ * may name one by mistake.
34
79
  */
35
- import { readdir, rm, rmdir, stat } from 'node:fs/promises';
36
- import { dirname } from 'node:path';
37
- import { BIN } from "./app.js";
38
- import { cacheDir, legacyCacheDir } from "./cache.js";
39
- import { LEGACY_TRUST_STORE_TOOL, TRUST_STORE_TOOL, configLocations } from "./config.js";
40
- import { EXIT } from '@osdlc/cli-tool';
41
- import { homeDir, trustStoreDir } from '@osdlc/trust-repo';
42
- import { jsonText } from "./terminal-text.js";
43
- function usage() {
44
- return `${BIN} clean — remove the data this tool stores outside your repositories
45
-
46
- usage: ${BIN} clean [options]
47
-
48
- (no options) show each store, where it is, and whether it holds anything
49
- --cache remove stored probe results (derived; costs one slow probe)
50
- --trust forget which repositories you have trusted
51
- --config remove your user configuration file (needs --yes)
52
- --all all three (needs --yes)
53
- --yes confirm removing something that cannot be regenerated
54
- --json the same answer as one JSON object, for a script or agent
55
- -h, --help this text
56
-
57
- Nothing is removed without one of --cache, --trust, --config or --all.
58
- Nothing inside a repository is ever touched: a project's own config file
59
- belongs to that project, not to this tool.
60
- `;
80
+ async function weigh(path, shallow = false) {
81
+ const info = await lstat(path).catch(() => null);
82
+ if (info === null)
83
+ return null;
84
+ if (!info.isDirectory() || shallow)
85
+ return info.size;
86
+ let total = 0;
87
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
88
+ total += (await weigh(join(path, entry.name))) ?? 0;
89
+ }
90
+ return total;
61
91
  }
62
- /** Bytes under a path, or null when it does not exist. */
63
- async function weigh(path, file) {
92
+ /** The largest user config clean reads to look for the `$schema` marker. */
93
+ const MARKER_READ_LIMIT = 1024 * 1024;
94
+ /** True when the JSON file at `path` has a `$schema` naming wayfinder's config schema. */
95
+ async function writtenByWayfinder(path) {
96
+ const info = await stat(path).catch(() => null);
97
+ if (info === null || !info.isFile() || info.size > MARKER_READ_LIMIT)
98
+ return false;
64
99
  try {
65
- const info = await stat(path);
66
- if (file)
67
- return info.size;
68
- let total = 0;
69
- const walk = async (dir) => {
70
- for (const entry of await readdir(dir, { withFileTypes: true })) {
71
- const child = `${dir}/${entry.name}`;
72
- if (entry.isDirectory())
73
- await walk(child);
74
- else
75
- total += (await stat(child)).size;
76
- }
77
- };
78
- await walk(path);
79
- return total;
100
+ const value = JSON.parse(await readFile(path, 'utf8'));
101
+ const schema = value?.$schema;
102
+ return typeof schema === 'string' && SCHEMA_MARKER.test(schema);
80
103
  }
81
104
  catch {
82
- return null;
105
+ return false;
106
+ }
107
+ }
108
+ /** A `$schema` URL for any release of wayfinder's config schema. */
109
+ const SCHEMA_MARKER = /\/@osdlc\/wayfinder@[^/]+\/schema\/config\.json$/;
110
+ /** Why clean will not remove `store`, which exists, or null when it may. */
111
+ async function refusal(store, home) {
112
+ const path = resolve(store.path);
113
+ const up = relative(path, resolve(home));
114
+ if (dirname(path) === path || up === '' || (!up.startsWith('..') && !isAbsolute(up))) {
115
+ return 'it is the home directory, a directory above it or a filesystem root';
116
+ }
117
+ const info = await lstat(path);
118
+ if (store.file) {
119
+ if (!info.isFile() && !info.isSymbolicLink())
120
+ return 'it is not a file';
121
+ if (store.envVar !== undefined && !(await writtenByWayfinder(path))) {
122
+ return `its "$schema" does not name ${APP}'s config schema, so ${APP} did not write it; remove it yourself`;
123
+ }
124
+ }
125
+ else if (!info.isDirectory()) {
126
+ return 'it is not a directory';
83
127
  }
128
+ return null;
84
129
  }
85
130
  function humanBytes(bytes) {
86
131
  if (bytes < 1024)
@@ -89,185 +134,286 @@ function humanBytes(bytes) {
89
134
  return `${Math.round(bytes / 1024)} KB`;
90
135
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
91
136
  }
92
- function storesFor(env, home) {
93
- // This command touches only the user config path, which does not depend on
94
- // the root. The project layer is out of scope. `home` is passed as the root
95
- // because the call needs one and no repository is involved.
96
- const user = configLocations(home, env, home).user;
97
- return [
137
+ /** Remove the empty directories above `path`, up to and not including `base`. */
138
+ async function pruneEmptyParents(path, base) {
139
+ let dir = dirname(path);
140
+ for (;;) {
141
+ const rel = relative(base, dir);
142
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel))
143
+ return;
144
+ const entries = await readdir(dir).catch(() => null);
145
+ if (entries === null || entries.length > 0)
146
+ return;
147
+ await rmdir(dir).catch(() => undefined);
148
+ dir = dirname(dir);
149
+ }
150
+ }
151
+ /** True when `a` and `b` are the same path or one is inside the other. */
152
+ function overlaps(a, b) {
153
+ const inside = (outer, inner) => {
154
+ const rel = relative(resolve(outer), resolve(inner));
155
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
156
+ };
157
+ return inside(a, b) || inside(b, a);
158
+ }
159
+ /**
160
+ * The first chosen store whose path is, holds or sits in another flag's
161
+ * store, with that store. Stores under one flag are removed together, so
162
+ * they are not compared.
163
+ */
164
+ function overlapOf(stores, chosen) {
165
+ for (const store of stores) {
166
+ if (!chosen.has(store.key))
167
+ continue;
168
+ const other = stores.find((o) => o.key !== store.key && overlaps(o.path, store.path));
169
+ if (other !== undefined)
170
+ return [store, other];
171
+ }
172
+ return undefined;
173
+ }
174
+ /** Every store, in report order. */
175
+ function storesFor(env, home, platform) {
176
+ const at = { env, home, ...(platform !== undefined ? { platform } : {}) };
177
+ const dirs = appDirs(at);
178
+ const user = configLocations(home, env, home);
179
+ const devDirs = appTieredDirs(at);
180
+ const stores = [
98
181
  {
99
182
  key: 'cache',
100
- flag: '--cache',
101
183
  what: 'stored probe results',
102
- path: cacheDir(env, home),
103
- file: false,
104
- },
105
- {
106
- key: 'cache',
107
- flag: '--cache',
108
- what: 'stored probe results under the old waypost name',
109
- path: legacyCacheDir(env, home),
184
+ path: dirs.cache,
110
185
  file: false,
111
- legacy: true,
186
+ base: dirs.bases.cache,
112
187
  },
113
188
  {
114
189
  key: 'trust',
115
- flag: '--trust',
116
190
  what: 'repositories you have trusted',
117
- path: trustStoreDir(TRUST_STORE_TOOL, env, home),
191
+ path: dirs.trustStore,
118
192
  file: false,
193
+ base: dirs.bases.state,
119
194
  },
120
195
  {
121
- key: 'trust',
122
- flag: '--trust',
123
- what: 'repositories you trusted under the old waypost name',
124
- path: trustStoreDir(LEGACY_TRUST_STORE_TOOL, env, home),
196
+ key: 'config',
197
+ what: 'your user configuration',
198
+ // `dirs` and not `user.user`, so an injected platform moves this store too.
199
+ path: user.userFromEnv ? user.user : dirs.userConfig,
200
+ file: true,
201
+ // A file the variable names is not under wayfinder's directories, so
202
+ // nothing above it is removed.
203
+ base: user.userFromEnv ? null : dirs.bases.config,
204
+ ...(user.userEnvVar !== null ? { envVar: user.userEnvVar } : {}),
205
+ },
206
+ {
207
+ key: 'dev',
208
+ what: `${BIN} dev link state`,
209
+ path: stateDir(WAYFINDER_SPEC, { dirs: devDirs, legacyDirs: null }),
125
210
  file: false,
126
- legacy: true,
211
+ base: devDirs.bases.config,
127
212
  },
128
- { key: 'config', flag: '--config', what: 'your user configuration', path: user, file: true },
129
213
  ];
130
- }
131
- /** A store's reported fields. `file` is internal and is left out. */
132
- function reportOf(store, bytes, removed) {
133
- return { key: store.key, flag: store.flag, what: store.what, path: store.path, bytes, removed };
134
- }
135
- function parse(argv) {
136
- const chosen = new Set();
137
- let help = false;
138
- let yes = false;
139
- let json = false;
140
- for (const arg of argv) {
141
- switch (arg) {
142
- case '-h':
143
- case '--help':
144
- help = true;
145
- break;
146
- case '--yes':
147
- yes = true;
148
- break;
149
- case '--json':
150
- json = true;
151
- break;
152
- case '--cache':
153
- chosen.add('cache');
154
- break;
155
- case '--trust':
156
- chosen.add('trust');
157
- break;
158
- case '--config':
159
- chosen.add('config');
160
- break;
161
- case '--all':
162
- chosen.add('cache').add('trust').add('config');
163
- break;
164
- default:
165
- return { error: `unknown option: ${arg}` };
166
- }
214
+ // Only a file `way dev install` wrote: one with devlink's shim marker.
215
+ const binDir = defaultBinDir({ ...env, HOME: home });
216
+ for (const name of [WAYFINDER_SPEC.name, ...(WAYFINDER_SPEC.aliases ?? [])]) {
217
+ const path = join(binDir, name);
218
+ if (readShimTarget(path) === null)
219
+ continue;
220
+ stores.push({
221
+ key: 'dev',
222
+ what: `the ${name} shim`,
223
+ path,
224
+ file: true,
225
+ base: null,
226
+ optional: true,
227
+ });
167
228
  }
168
- return { help, yes, json, chosen };
169
- }
170
- export async function runCleanCommand(toolName, argv, io) {
171
- const parsed = parse(argv);
172
- if ('error' in parsed) {
173
- io.stderr(`${toolName}: ${parsed.error}\n\n${usage()}`);
174
- return EXIT.usage;
229
+ // Old releases' paths come from the rules those releases used, never from
230
+ // the current `WAYFINDER_*` overrides, which could point them at a live store.
231
+ const old = pre08Bases(env, home);
232
+ const legacy = [];
233
+ for (const [base, what] of [
234
+ [old.config, 'config'],
235
+ [old.state, 'trust store'],
236
+ [old.cache, 'cache'],
237
+ ]) {
238
+ legacy.push({
239
+ key: 'legacy',
240
+ what: `the ${what} from before the rename`,
241
+ path: join(base, OLD_NAME),
242
+ file: false,
243
+ base,
244
+ optional: true,
245
+ });
175
246
  }
176
- if (parsed.help) {
177
- io.stdout(usage());
178
- return EXIT.ok;
247
+ const os = platform ?? process.platform;
248
+ // Link state before 0.8, on macOS only: the native convention's config home.
249
+ if (os === 'darwin') {
250
+ const base = join(home, 'Library', 'Application Support');
251
+ legacy.push({
252
+ key: 'legacy',
253
+ what: `${BIN} dev link state from before 0.8`,
254
+ path: join(base, WAYFINDER_SPEC.name),
255
+ file: false,
256
+ base,
257
+ optional: true,
258
+ });
179
259
  }
180
- const env = io.env ?? process.env;
181
- const home = io.home ?? homeDir();
182
- const stores = storesFor(env, home);
183
- // A bare `clean` prints the report and removes nothing.
184
- if (parsed.chosen.size === 0) {
185
- const reports = [];
186
- for (const store of stores) {
187
- const bytes = await weigh(store.path, store.file);
188
- if (store.legacy === true && bytes === null)
189
- continue;
190
- reports.push(reportOf(store, bytes, false));
191
- }
192
- if (parsed.json) {
193
- io.stdout(`${jsonText({ stores: reports }, 2)}\n`);
194
- return EXIT.ok;
195
- }
196
- const lines = [`${toolName} stores three things outside your repositories:\n`];
197
- for (const report of reports) {
198
- const held = report.bytes === null ? 'nothing stored' : humanBytes(report.bytes);
199
- lines.push(` ${report.flag.padEnd(9)} ${report.what}`);
200
- lines.push(` ${' '.repeat(9)} ${report.path} (${held})`);
260
+ // Windows before 0.8 used the XDG paths; 0.8 uses %APPDATA% and %LOCALAPPDATA%.
261
+ if (os === 'win32') {
262
+ for (const [base, what] of [
263
+ [old.config, 'user config'],
264
+ [old.state, 'trust store'],
265
+ [old.cache, 'cache'],
266
+ ]) {
267
+ legacy.push({
268
+ key: 'legacy',
269
+ what: `the ${what} from before 0.8`,
270
+ path: join(base, APP),
271
+ file: false,
272
+ base,
273
+ optional: true,
274
+ });
201
275
  }
202
- lines.push(`\nPass a flag above to remove one, or --all for every one.`);
203
- lines.push(`Nothing was removed.\n`);
204
- io.stdout(lines.join('\n'));
205
- return EXIT.ok;
206
276
  }
207
- if (parsed.chosen.has('config') && !parsed.yes) {
208
- io.stderr(`${toolName}: removing your user configuration needs --yes.\n` +
209
- `Nothing else here is written by hand, so nothing else asks.\n`);
210
- return EXIT.usage;
277
+ // An old path that is, holds or sits in a current store is not old.
278
+ const live = stores.map((s) => s.path);
279
+ for (const store of legacy) {
280
+ if (!live.some((path) => overlaps(path, store.path)))
281
+ stores.push(store);
211
282
  }
212
- const reports = [];
213
- let removed = 0;
214
- let failed = false;
215
- for (const store of stores) {
216
- if (!parsed.chosen.has(store.key))
217
- continue;
218
- const size = await weigh(store.path, store.file);
219
- if (size === null) {
220
- if (store.legacy === true)
221
- continue;
222
- reports.push(reportOf(store, null, false));
223
- if (!parsed.json)
224
- io.stdout(`${store.what}: nothing stored at ${store.path}\n`);
225
- continue;
226
- }
227
- try {
228
- await rm(store.path, { recursive: true, force: true });
229
- // A config file leaves its directory behind. Remove the directory when it
230
- // is now empty, and leave it when it is not, since a future version may
231
- // keep other files there.
232
- if (store.file) {
233
- const dir = dirname(store.path);
283
+ return stores;
284
+ }
285
+ function reportOf(store, bytes, removed) {
286
+ return {
287
+ key: store.key,
288
+ flag: store.key === 'config' ? '--user-config' : `--${store.key}`,
289
+ what: store.what,
290
+ path: store.path,
291
+ bytes,
292
+ removed,
293
+ ...(store.envVar !== undefined ? { envVar: store.envVar } : {}),
294
+ };
295
+ }
296
+ const FLAGS = {
297
+ cache: { kind: 'boolean', help: 'remove stored probe results (derived; costs one slow probe)' },
298
+ trust: { kind: 'boolean', help: 'forget which repositories you have trusted' },
299
+ userConfig: { kind: 'boolean', help: 'remove your user configuration file (needs --yes)' },
300
+ dev: {
301
+ kind: 'boolean',
302
+ help: `remove ${BIN} dev link state and the shims ${BIN} dev install put on PATH`,
303
+ },
304
+ legacy: {
305
+ kind: 'boolean',
306
+ help: "remove files kept under the tool's name before its first release",
307
+ },
308
+ everything: { kind: 'boolean', help: 'every store above (needs --yes)' },
309
+ yes: { kind: 'boolean', help: 'confirm removing something that cannot be regenerated' },
310
+ };
311
+ /**
312
+ * The `clean` command. Mount it as `clean: cleanCommand({ globals })`.
313
+ * A call with a flag that removes something is `cli-only`: the MCP and HTTP
314
+ * adapters refuse it. A bare `clean`, the report, is open to them.
315
+ */
316
+ export function cleanCommand(options = {}) {
317
+ const { globals, platform, ...rest } = options;
318
+ const env = commandEnv(rest);
319
+ const kit = commandKit({ globals: globals ?? {} });
320
+ const chosenOf = (flags) => new Set(flags['everything'] === true ? KEYS : KEYS.filter((k) => flags[FLAG_OF[k]] === true));
321
+ return kit.command({
322
+ summary: 'remove the data this tool stores outside your repositories',
323
+ description: 'With no flag, clean reports each store, where it is and what it holds, and removes ' +
324
+ 'nothing. Nothing inside a repository is touched: a project config file belongs to the ' +
325
+ `project. A user config that ${CONFIG_ENV_VAR} names is named before it is removed.`,
326
+ flags: FLAGS,
327
+ output: CleanOutputSchema,
328
+ kind: 'clean',
329
+ destructive: true,
330
+ exits: { 1: 'a store could not be removed' },
331
+ exposureOf: ({ flags }) => (chosenOf(flags).size > 0 ? 'cli-only' : 'all'),
332
+ async run({ flags }, ctx) {
333
+ const chosen = chosenOf(flags);
334
+ const home = env.home(ctx);
335
+ const stores = storesFor(ctx.env, home, platform);
336
+ if (chosen.size === 0) {
337
+ const reports = [];
338
+ for (const store of stores) {
339
+ const bytes = await weigh(store.path, store.file);
340
+ if (store.optional === true && bytes === null)
341
+ continue;
342
+ reports.push(reportOf(store, bytes, false));
343
+ }
344
+ return { mode: 'report', stores: reports };
345
+ }
346
+ // An override can put one store inside another, such as the cache at
347
+ // `~/.config`. Removing the outer one would remove the inner one too.
348
+ const overlap = flags.yes === true ? undefined : overlapOf(stores, chosen);
349
+ if (overlap !== undefined) {
350
+ const [a, b] = overlap;
351
+ throw new UsageError(`not removing ${a.what} (${a.path}): it overlaps ${b.what} (${b.path}), ` +
352
+ 'since one path is or holds the other. Check the WAYFINDER_* and XDG_* variables, ' +
353
+ 'or pass --yes to remove it anyway');
354
+ }
355
+ const config = stores.find((s) => s.key === 'config');
356
+ if (chosen.has('config') && flags.yes !== true) {
357
+ throw new UsageError(`removing your user configuration (${config?.path ?? ''}${config?.envVar !== undefined ? `, named by ${config.envVar}` : ''}) needs --yes`);
358
+ }
359
+ const reports = [];
360
+ for (const store of stores) {
361
+ if (!chosen.has(store.key))
362
+ continue;
363
+ const size = await weigh(store.path, store.file);
364
+ if (size === null) {
365
+ if (store.optional !== true)
366
+ reports.push(reportOf(store, null, false));
367
+ continue;
368
+ }
369
+ const refused = await refusal(store, home);
370
+ if (refused !== null) {
371
+ ctx.warn(`not removing ${store.path}: ${refused}`);
372
+ reports.push(reportOf(store, size, false));
373
+ return outcome({ mode: 'remove', stores: reports }, EXIT.error);
374
+ }
375
+ if (store.envVar !== undefined) {
376
+ ctx.note(`removing ${store.path}, which ${store.envVar} names`);
377
+ }
234
378
  try {
235
- if ((await readdir(dir)).length === 0)
236
- await rmdir(dir);
379
+ await rm(store.path, store.file ? { force: true } : { recursive: true, force: true });
237
380
  }
238
- catch {
239
- // Not required. The file is gone, which is what was asked.
381
+ catch (err) {
382
+ ctx.warn(`could not remove ${store.path}: ${err instanceof Error ? err.message : String(err)}`);
383
+ // A store that would not delete is a reason to stop deleting the others.
384
+ reports.push(reportOf(store, size, false));
385
+ return outcome({ mode: 'remove', stores: reports }, EXIT.error);
240
386
  }
387
+ if (store.base !== null)
388
+ await pruneEmptyParents(store.path, store.base);
389
+ reports.push(reportOf(store, size, true));
241
390
  }
242
- reports.push(reportOf(store, size, true));
243
- if (!parsed.json) {
244
- io.stdout(`removed ${store.what} (${humanBytes(size)}) from ${store.path}\n`);
391
+ if (chosen.has('trust') && reports.some((r) => r.key === 'trust' && r.removed)) {
392
+ ctx.note('trusted repositories will ask again the next time you read them');
245
393
  }
246
- removed += 1;
247
- }
248
- catch (err) {
249
- io.stderr(`${toolName}: could not remove ${store.path}: ${String(err)}\n`);
250
- // Record the failure and stop. A store that would not delete is a reason
251
- // to stop deleting the others.
252
- reports.push(reportOf(store, size, false));
253
- failed = true;
254
- break;
394
+ return { mode: 'remove', stores: reports };
395
+ },
396
+ text: (output) => cleanText(output),
397
+ });
398
+ }
399
+ function cleanText(output) {
400
+ const from = (r) => (r.envVar !== undefined ? `, from ${r.envVar}` : '');
401
+ if (output.mode === 'report') {
402
+ const lines = [`${APP} stores these outside your repositories:`, ''];
403
+ const width = Math.max(0, ...output.stores.map((r) => r.flag.length));
404
+ for (const r of output.stores) {
405
+ const held = r.bytes === null ? 'nothing stored' : humanBytes(r.bytes);
406
+ lines.push(` ${r.flag.padEnd(width)} ${r.what}`);
407
+ lines.push(` ${' '.repeat(width)} ${terminalSafe(r.path)} (${held}${from(r)})`);
255
408
  }
409
+ lines.push('', 'Pass a flag above to remove one, or --everything for every one.', 'Nothing was removed.', '');
410
+ return lines.join('\n');
256
411
  }
257
- // One document, printed once, so a --json caller parses a single object
258
- // whether the run finished or stopped on a failure.
259
- if (parsed.json)
260
- io.stdout(`${jsonText({ stores: reports }, 2)}\n`);
261
- if (failed)
262
- return EXIT.error;
263
- if (removed > 0 && parsed.chosen.has('trust')) {
264
- // A side note, not the answer, so under --json it goes to stderr and
265
- // stdout stays one JSON object.
266
- const note = 'Trusted repositories will ask again the next time you read them.\n';
267
- if (parsed.json)
268
- io.stderr(note);
269
- else
270
- io.stdout(`\n${note}`);
271
- }
272
- return EXIT.ok;
412
+ return output.stores
413
+ .map((r) => r.removed
414
+ ? `removed ${r.what} (${humanBytes(r.bytes ?? 0)}) from ${terminalSafe(r.path)}\n`
415
+ : r.bytes === null
416
+ ? `${r.what}: nothing stored at ${terminalSafe(r.path)}\n`
417
+ : `${r.what}: not removed: ${terminalSafe(r.path)}\n`)
418
+ .join('');
273
419
  }