@osdlc/wayfinder 0.7.4 → 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 +214 -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
package/dist/cli.js CHANGED
@@ -1,616 +1,187 @@
1
1
  /**
2
2
  * `way`: browse and run every task in a repository.
3
3
  *
4
+ * The commands are a `@osdlc/cli-tool` command tree (`commands/index.ts`).
5
+ * This module is the entry point: it runs `dev`, which parses its own
6
+ * arguments, maps the old surface flags onto commands, and hands the rest to
7
+ * the tree.
8
+ *
4
9
  * wayfinder's `allowExec` default is `true`. You usually run it in your own
5
10
  * repository, and a task browser that cannot see the build graph is of little
6
- * use. `--no-exec` turns execution off.
7
- *
8
- * The default alone does not allow execution. The repository must also be
9
- * trusted. `@osdlc/trust-repo`'s `policyExecGate` combines the configured value
10
- * with the marker store and the user file's `trust.paths`/`trust.owners`
11
- * policy. Execution happens only once a person, or a policy they configured,
12
- * has trusted this repository. A configured `false` means no execution, however
13
- * trusted the repository is.
11
+ * use. `--no-exec` turns execution off. The default alone does not allow
12
+ * execution: the repository must also be trusted (see `core/session.ts`).
14
13
  */
15
- import { EXIT, defineCli, processIo } from '@osdlc/cli-tool';
14
+ import { EXIT, processContext, processIo } from '@osdlc/cli-tool';
15
+ import { errorDocument } from '@osdlc/cli-tool/command';
16
16
  import { runDevCli } from '@osdlc/cli-tool/devlink';
17
- import { tasks as allTasks, } from '@osdlc/system-model/detect';
18
- import { humanAge, humanMs } from '@osdlc/system-model/duration';
19
- import { matchEntry, terms as searchTerms } from '@osdlc/system-model/match';
20
- import { homeDir, policyExecGate, withheldHint } from '@osdlc/trust-repo';
21
- import { APP, BIN, PROJECT_CONFIG_FILENAME } from "./app.js";
22
- import { cacheDir } from "./cache.js";
23
- import { collectAndCache, freshStates, fromStore, makeProject, orderedCatalog, readCachedCatalog, } from "./catalog.js";
24
- import { runCleanCommand } from "./clean-command.js";
25
- import { ConfigError, collectOptionsFromConfig, loadConfig, trustPolicyFromConfig, trustPolicyOptions, } from "./config.js";
26
- import { appTrustStore } from "./trust-store.js";
27
- import { runConfigCommand, takeConfigDir } from "./config-command.js";
17
+ import { installGroupSignalForwarding } from '@osdlc/command-seam';
18
+ import { homeDir } from '@osdlc/trust-repo';
19
+ import { APP, BIN } from "./app.js";
20
+ import { createWayApp } from "./commands/index.js";
21
+ import { GLOBALS } from "./commands/shared.js";
28
22
  import { WAYFINDER_SPEC, checkoutRoot } from "./devlink.js";
29
- import { catalogGroups } from "./groups.js";
30
- import { runGuideCommand } from "./guide.js";
31
- import { runProvidersCommand } from "./providers-command.js";
32
- import { serve } from "./serve.js";
33
- import { loadTools, ToolModuleError } from "./tools.js";
34
- import { runTrustCommand } from "./trust-command.js";
35
- import { jsonText, safeJsonStdout, safeStderr, safeStdout, terminalSafe } from "./terminal-text.js";
36
- import { runTui } from "./tui.js";
37
- /** The prose under the flag list in the complete help. */
38
- const PROSE = `Defaults come from ${PROJECT_CONFIG_FILENAME} in the project root and from the user file
39
- "${BIN} config path" names; a flag given here beats both. --exclude REPLACES the
40
- configured runners.disabled rather than adding to it.
41
-
42
- "${BIN} query" is the terminal UI's search from a shell: the same matcher, the
43
- same ranking, one command line per result. Terms are ANDed and matched fuzzily,
44
- a leading ' forces one term to match exactly, and --exact does that to all of
45
- them. --json prints the matching tasks instead of their command lines, --cached
46
- and every collection flag above apply, and an exit code of 1 means the search
47
- matched nothing.
48
-
49
- --json and --list re-probe every time, so a script reading them gets what the
50
- repository currently has; --cached asks for the stored answer instead and names
51
- the stale runners on stderr. The terminal UI and --serve always start from the
52
- store and refresh behind you — an interactive surface is worth painting at once.
53
-
54
- Reading some runners means running them, so a repository must be trusted before
55
- they are collected — "${BIN} trust" records that, once, per repository. A
56
- repository cannot trust itself: allowExec in ${PROJECT_CONFIG_FILENAME} cannot raise the
57
- gate.
58
-
59
- --config loads a module of extra tools for this run, beside the built-ins and
60
- any the config's "tools" key names; "${BIN} providers" lists them all.
61
-
62
- In the terminal UI:
63
- enter run ^y copy tab runner ^e exact ^t services ^s trust ^r refresh esc quit
64
- `;
65
- /**
66
- * The surface and subcommand names, for both help levels. A generated flag
67
- * list cannot say which surface you are choosing, or name a subcommand that
68
- * has its own flag list.
69
- */
70
- const SURFACES = `surfaces
71
- ${BIN} the terminal UI; Enter runs the selected task
72
- ${BIN} query <terms> the tasks matching a search, best match first
73
- ${BIN} --serve the same catalog as a live page
74
- ${BIN} --json | --list the whole catalog, for a script or an agent
75
-
76
- subcommands
77
- config read and write the layered settings file; see config --help
78
- trust allow this repository's runners to be read by running them; see trust --help
79
- providers the registered tools, built-in and your own; see providers --help
80
- guide how to use and extend this tool, in Markdown; see guide --help
81
- clean remove the data this tool stores outside your repositories; see clean --help`;
23
+ import { flushViews } from "./core/saved-view.js";
24
+ import { safeJsonStdout, safeStderr, safeStdout } from "./terminal-text.js";
82
25
  /**
83
- * wayfinder's own `true` default for exec is applied in {@link main}, below
84
- * the config layer. So `exec` and the collection lists are absent unless
85
- * given, per `TristateFlag` in `@osdlc/cli-tool`. `autoHelp` is off for the
86
- * reason `CliDecl.autoHelp` gives: `help` and `all` are declared below as
87
- * ordinary flags.
26
+ * Exit quietly when the reader of `stream` goes away, as `way list --json |
27
+ * head -1` does: the rest of the output has nowhere to go, which is not an
28
+ * error. Any other write error is thrown as before.
88
29
  */
89
- const cli = defineCli({
90
- name: BIN,
91
- summary: 'Browse and run every task in this repository.',
92
- autoHelp: false,
93
- flags: {
94
- serve: { kind: 'boolean', help: 'a live page in the browser instead of the terminal UI' },
95
- json: {
96
- kind: 'boolean',
97
- help: 'print the catalog and exit, no UI; with query, the matching tasks themselves',
98
- },
99
- list: {
100
- kind: 'boolean',
101
- help: 'print one command line per task and exit; with query, the default form',
102
- },
103
- port: {
104
- kind: 'string',
105
- valueName: 'N',
106
- hidden: true,
107
- help: 'fixed port for --serve (default: an OS-assigned one)',
108
- },
109
- open: {
110
- kind: 'boolean',
111
- negatable: true,
112
- hidden: true,
113
- help: 'print the URL rather than opening a browser',
114
- },
115
- cached: {
116
- kind: 'boolean',
117
- hidden: true,
118
- help: 'answer --json/--list from the last stored probe, not a new one',
119
- },
120
- exact: {
121
- kind: 'boolean',
122
- hidden: true,
123
- help: 'with query: terms match as substrings, not subsequences',
124
- },
125
- services: {
126
- kind: 'boolean',
127
- hidden: true,
128
- help: 'with query: only tasks that run until you stop them',
129
- },
130
- exec: {
131
- kind: 'tristate',
132
- help: 'allow runners that must run a subprocess (moon), this run only',
133
- offHelp: 'skip them, overriding a configured allowExec: true',
134
- },
135
- only: { kind: 'list', valueName: 'a,b', hidden: true, help: 'restrict to these runners' },
136
- exclude: {
137
- kind: 'list',
138
- valueName: 'a,b',
139
- hidden: true,
140
- help: 'skip these runners, REPLACING the configured runners.disabled',
141
- },
142
- excludePath: {
143
- kind: 'list',
144
- valueName: 'P',
145
- commaSeparated: false,
146
- hidden: true,
147
- help: 'skip a path; repeatable. A bare name matches any segment, a value with a slash matches a path from the root',
148
- },
149
- discovery: {
150
- kind: 'enum',
151
- choices: ['git', 'walk', 'auto'],
152
- valueName: 'M',
153
- hidden: true,
154
- help: 'how to find directories. Default: auto',
155
- },
156
- dir: {
157
- kind: 'string',
158
- short: 'C',
159
- valueName: 'PATH',
160
- help: 'the directory to inspect (default: cwd)',
161
- },
162
- config: {
163
- kind: 'list',
164
- valueName: 'MODULE',
165
- commaSeparated: false,
166
- help: 'load extra tools from a module, this run only; repeatable',
167
- },
168
- help: {
169
- kind: 'boolean',
170
- short: 'h',
171
- help: 'the short form: the ways in, and where the rest is',
172
- },
173
- all: { kind: 'boolean', help: 'with --help: this text, every flag and every note' },
174
- },
175
- positionals: [{ name: 'dir-or-terms', variadic: true, help: 'a directory, or query terms' }],
176
- shortEpilogue: `${SURFACES}
177
-
178
- Some runners can only be read by running them, so a repository must be
179
- trusted before they are collected — "${BIN} trust", once, per repository.
180
- Until then they are withheld and every surface says so.
181
-
182
- ${BIN} --help --all every flag, the defaults, and the notes
183
- ${BIN} guide how it works, by topic`,
184
- epilogue: `${SURFACES}
185
-
186
- ${PROSE}`,
187
- });
188
- /** The complete help. */
189
- const USAGE = cli.help();
30
+ export function quietOnBrokenPipe(stream, exit = (code) => process.exit(code)) {
31
+ stream.on('error', (err) => {
32
+ if (err.code !== 'EPIPE')
33
+ throw err;
34
+ exit(0);
35
+ });
36
+ }
190
37
  /**
191
- * The default, short help. Every fact in it is also stated in the complete
192
- * help, and it names the longer forms. The trust paragraph is here because a
193
- * reader who does not know about trust sees a shorter catalog and no reason why.
38
+ * Refuse a command line before the tree runs: a line on stderr, and with
39
+ * `--json` before any `--` the error document on stdout, as the tree does.
194
40
  */
195
- const SHORT_USAGE = cli.help({ all: false });
41
+ function usageError(io, argv, message) {
42
+ const hint = `"${BIN} --help" lists the commands`;
43
+ io.stderr(`${BIN}: ${message}\n ${hint}\n`);
44
+ const dash = argv.indexOf('--');
45
+ const head = dash === -1 ? argv : argv.slice(0, dash);
46
+ if (head.includes('--json')) {
47
+ io.stdout(`${JSON.stringify(errorDocument('usage', message, EXIT.usage, hint), null, 2)}\n`);
48
+ }
49
+ return EXIT.usage;
50
+ }
51
+ /** An app that only renders help, for the guide. It never runs a command. */
52
+ const HELP = createWayApp({ home: '/', guide: () => GUIDE_TOOL });
53
+ /** The complete help: the root, then each command the tree runs, each in full. */
54
+ const COMPLETE_HELP = [[], ...HELP.treeWords.map((w) => [w])]
55
+ .map((path) => HELP.app.helpText(path, { full: true, width: 80 }))
56
+ .join('\n');
196
57
  /** What the `guide` command needs: the complete help, and what it cannot say. */
197
58
  export const GUIDE_TOOL = {
198
- usage: USAGE,
199
- extraUsage: `With no options ${BIN} draws a terminal UI: type to filter, and the key line
200
- at the foot of the usage above is the full set of bindings. Enter runs the
59
+ usage: COMPLETE_HELP,
60
+ extraUsage: `With no command ${BIN} draws a terminal UI: type to filter, and the key line
61
+ at the foot of the screen is the full set of bindings. Enter runs the
201
62
  selected task in this terminal, and the trust binding grants trust without
202
63
  leaving the UI.
203
64
 
204
65
  \`${BIN} query <terms>\` is that same search without the UI: it ranks the catalog
205
66
  with the matcher the terminal UI uses and prints one command line per match,
206
- exiting 1 when nothing matched.
67
+ exiting 1 when nothing matched. \`${BIN} run <id>\` runs one task by id.
207
68
 
208
- \`--serve\` swaps the terminal UI for a live page, opening a browser at an
69
+ \`${BIN} serve\` swaps the terminal UI for a live page, opening a browser at an
209
70
  OS-assigned port; \`--port N\` fixes the port and \`--no-open\` prints the URL
210
- rather than opening anything.
71
+ rather than opening anything. The old \`--serve\` flag still works.
211
72
 
212
73
  ${APP} supplies \`allowExec: true\` as its own default, below any config file:
213
74
  willing in principle, still gated on trust.`,
214
75
  };
76
+ /** The spellings of the global flags that take a value: `-C`, `--dir`, `--only`. */
77
+ const GLOBAL_VALUE_FLAGS = new Set(Object.entries(GLOBALS).flatMap(([name, decl]) => {
78
+ if (decl.kind === 'tristate')
79
+ return [];
80
+ const long = `--${name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
81
+ return 'short' in decl ? [long, `-${decl.short}`] : [long];
82
+ }));
83
+ /** Flags of the old surfaces that take a value. */
84
+ const ALIAS_VALUE_FLAGS = new Set(['--port']);
215
85
  /**
216
- * `query` is matched before the flags are parsed, like `config` and `trust`
217
- * (see {@link main}), because it changes what a positional means: search terms
218
- * instead of a directory. Every collection flag still applies after it, so it
219
- * is not a command with its own flag list.
220
- */
221
- export function parseArgs(argv, io, cwd = process.cwd()) {
222
- const isQuery = argv[0] === 'query';
223
- const parsed = cli.parse(isQuery ? argv.slice(1) : argv, io);
224
- if (parsed.status === 'help')
225
- return { error: 'unreachable: help is a declared flag here' };
226
- if (parsed.status === 'error')
227
- return { error: parsed.message };
228
- const v = parsed.values;
229
- // Under `query` these choose the output form, not the surface. Letting them
230
- // set the mode would silently drop the terms.
231
- const mode = isQuery
232
- ? 'query'
233
- : v.serve
234
- ? 'serve'
235
- : v.json
236
- ? 'json'
237
- : v.list
238
- ? 'list'
239
- : 'tui';
240
- const flags = {
241
- mode,
242
- dir: cwd,
243
- cached: v.cached,
244
- open: v.open,
245
- help: v.help,
246
- json: isQuery ? v.json : false,
247
- matchMode: v.exact ? 'exact' : 'fuzzy',
248
- servicesOnly: v.services,
249
- all: v.all,
250
- toolModules: v.config ?? [],
251
- };
252
- if (v.dir !== undefined)
253
- flags.dir = v.dir;
254
- if (v.exec !== undefined)
255
- flags.allowExec = v.exec;
256
- if (v.only !== undefined)
257
- flags.only = v.only.filter(Boolean);
258
- if (v.exclude !== undefined)
259
- flags.exclude = v.exclude.filter(Boolean);
260
- if (v.excludePath !== undefined)
261
- flags.excludePaths = v.excludePath;
262
- if (v.discovery !== undefined)
263
- flags.discovery = v.discovery;
264
- if (v.all && !v.help) {
265
- return { error: `--all says which help to print; pass it as "--help --all"` };
266
- }
267
- if (!isQuery) {
268
- if (v.exact)
269
- return { error: '--exact only applies to query' };
270
- if (v.services)
271
- return { error: '--services only applies to query' };
272
- }
273
- else {
274
- // The mode ternary above stops at `isQuery`, so nothing else would read a
275
- // serve flag under `query`.
276
- if (v.serve)
277
- return { error: '--serve does not apply to query' };
278
- if (v.port !== undefined)
279
- return { error: '--port only applies to --serve' };
280
- }
281
- if (v.port !== undefined) {
282
- // Check for digits before converting. `Number('')` and `Number(' ')` are
283
- // 0, `Number('0x10')` is 16 and `Number('1e3')` is 1000. Each is an integer
284
- // in range, so a bare `Number()` would accept a port nobody typed. Port 0
285
- // means "let the OS pick", which is what --port exists to prevent.
286
- if (!/^\d+$/.test(v.port.trim())) {
287
- return { error: '--port needs a port number' };
288
- }
289
- const port = Number.parseInt(v.port.trim(), 10);
290
- if (port < 0 || port > 65535) {
291
- return { error: '--port needs a port number' };
292
- }
293
- flags.port = port;
294
- }
295
- if (isQuery) {
296
- flags.terms = parsed.positionals;
297
- return flags;
298
- }
299
- if (parsed.positionals.length > 1)
300
- return { error: 'expected at most one directory' };
301
- // A positional directory beats -C.
302
- if (parsed.positionals[0] !== undefined)
303
- flags.dir = parsed.positionals[0];
304
- return flags;
305
- }
306
- /**
307
- * wayfinder's own defaults, applied only where no config file answered.
308
- *
309
- * One constant, read in two places. {@link main} resolves the run with it, and
310
- * `config list` / `config get` receive it, so they report the value this tool
311
- * really uses rather than the library default.
312
- *
313
- * `allowExec: true` does not mean "run this repository's code". The repository
314
- * must also be trusted, and a configured `false` still means no execution.
315
- */
316
- const WAYFINDER_DEFAULTS = { allowExec: true };
317
- /** `allowExec` from the config files, or wayfinder's default when none sets it. */
318
- function configuredAllowExec(cfg) {
319
- if (cfg.sources.get('allowExec') === 'default')
320
- return WAYFINDER_DEFAULTS.allowExec ?? true;
321
- return cfg.effective.allowExec ?? WAYFINDER_DEFAULTS.allowExec ?? true;
322
- }
323
- /**
324
- * The single stderr line `--cached` prints, or null when there is nothing to
325
- * say. When this repo has never measured a runner's probe time, the line says
326
- * so rather than guessing a number.
86
+ * The index of the first word that is not a flag or a flag's value, before
87
+ * any `--`. -1 when there is none.
327
88
  */
328
- function cacheNote(rows) {
329
- const stale = rows.filter((r) => r.state === 'stale');
330
- const missed = rows.filter((r) => r.state === 'miss');
331
- if (stale.length === 0 && missed.length === 0)
332
- return null;
333
- const part = (row) => {
334
- const cost = row.estimateMs === null
335
- ? 'refresh cost not measured here yet'
336
- : `refresh usually about ${humanMs(row.estimateMs)}`;
337
- return `${row.runner} (${humanAge(row.ageMs)}, ${cost})`;
338
- };
339
- const parts = [];
340
- if (stale.length > 0)
341
- parts.push(`stale: ${stale.map(part).join(', ')}`);
342
- if (missed.length > 0) {
343
- parts.push(`not cached, probed now: ${missed.map((r) => r.runner).join(', ')}`);
89
+ function commandWordIndex(argv) {
90
+ for (let i = 0; i < argv.length; i++) {
91
+ const word = argv[i];
92
+ if (word === '--')
93
+ return -1;
94
+ if (!word.startsWith('-') || word === '-')
95
+ return i;
96
+ if (GLOBAL_VALUE_FLAGS.has(word) || ALIAS_VALUE_FLAGS.has(word))
97
+ i += 1;
344
98
  }
345
- return `${APP}: --cached: ${parts.join('; ')}\n`;
346
- }
347
- /** `--json`'s document: the catalog, its groups, and the cache verdict under `--cached`. */
348
- export function catalogJson(catalog, cache) {
349
- const doc = { ...catalog, groups: catalogGroups(catalog.reports) };
350
- return cache === undefined ? doc : { ...doc, cache };
99
+ return -1;
351
100
  }
101
+ /** The old surface flags, and the command line each one now is. */
102
+ const SURFACE_FLAGS = {
103
+ '--serve': ['serve'],
104
+ '--list': ['list'],
105
+ '--json': ['list', '--json'],
106
+ };
352
107
  /**
353
- * Load the tool modules this run names and build the project over them.
354
- * Returns an error message instead when a module cannot be used.
108
+ * Map the old surface flags onto commands, for this release: `--serve` is
109
+ * `serve`, `--list` is `list`, and `--json` alone is `list --json`. They
110
+ * apply only where no command word is given. Two of them together are
111
+ * refused, since each chooses a surface. `alias` names the flag that was
112
+ * mapped, so the caller can say it is deprecated.
355
113
  */
356
- async function projectFor(toolModules, cfg, home, projectAllowed) {
357
- try {
358
- const { tools, warnings } = await loadTools({
359
- flag: toolModules,
360
- cwd: process.cwd(),
361
- config: cfg,
362
- home,
363
- projectAllowed,
364
- });
365
- try {
366
- return { project: makeProject(tools.map((t) => t.def)), tools, warnings };
367
- }
368
- catch (err) {
369
- // Every tool here passed loadTools, so a registry refusal (such as an
370
- // ecosystem id a built-in already uses) comes from the modules.
371
- const modules = [...new Set(tools.map((t) => t.module))].join(', ');
372
- const message = err instanceof Error ? err.message : String(err);
373
- return { error: `${message} (from a tool module: ${modules})` };
374
- }
375
- }
376
- catch (err) {
377
- if (err instanceof ToolModuleError)
378
- return { error: err.message };
379
- throw err;
114
+ export function rewriteAliases(argv, commandWords) {
115
+ const at = commandWordIndex(argv);
116
+ const word = at === -1 ? undefined : argv[at];
117
+ if (word !== undefined && commandWords.includes(word)) {
118
+ // `query --list` asked for the default form of `query`.
119
+ if (word === 'query')
120
+ return { argv: argv.filter((w, i) => i <= at || w !== '--list') };
121
+ return { argv: [...argv] };
380
122
  }
123
+ const dash = argv.indexOf('--');
124
+ const head = dash === -1 ? argv : argv.slice(0, dash);
125
+ // `--version` and `--help` answer for the root, whatever else is given.
126
+ if (['--version', '--help', '-h'].some((flag) => head.includes(flag)))
127
+ return { argv: [...argv] };
128
+ const given = Object.keys(SURFACE_FLAGS).filter((flag) => head.includes(flag));
129
+ if (given.length === 0)
130
+ return { argv: [...argv] };
131
+ if (given.length > 1)
132
+ return { error: `${given.join(' and ')} each choose a surface; give one` };
133
+ const flag = given[0];
134
+ return { argv: [...SURFACE_FLAGS[flag], ...argv.filter((w) => w !== flag)], alias: flag };
381
135
  }
382
136
  /**
137
+ * Run `way` with `argv`, the words after the binary. Returns the exit code.
383
138
  * `env` and `home` are injectable so a test never reads the developer's own
384
139
  * config, cache or trust store. `io` defaults to the real process streams.
385
140
  */
386
141
  export async function main(argv, env = process.env, home = homeDir(), io = processIo) {
142
+ const real = io === processIo;
143
+ // Each probe runs in its own process group, so the terminal's Ctrl-C does
144
+ // not reach it. On SIGINT, SIGTERM or SIGHUP this kills every live probe
145
+ // group and exits with 128 + the signal. Only the real process installs it:
146
+ // a test that passes its own io keeps the process's signal handling.
147
+ if (real)
148
+ installGroupSignalForwarding();
149
+ if (real)
150
+ quietOnBrokenPipe(process.stdout);
387
151
  // Every stderr line is human text that can quote repository content.
388
152
  io = safeStderr(io);
389
- // Subcommands are matched before the flags are parsed, because their
390
- // arguments are not this parser's flags. The root is found with the
391
- // built-in tools only.
392
- const findRoot = (dir) => makeProject().findRoot(dir);
393
- const usageError = (message) => {
394
- io.stderr(`${APP}: ${message}\n\n${SHORT_USAGE}`);
395
- return EXIT.usage;
396
- };
397
- if (argv[0] === 'config' || argv[0] === 'trust' || argv[0] === 'providers') {
398
- // -C has to work here, so pointing at another directory shows that
399
- // directory's configuration, trust and tools.
400
- const taken = takeConfigDir(argv.slice(1));
401
- if ('error' in taken)
402
- return usageError(taken.error);
403
- const root = await findRoot(taken.dir ?? process.cwd());
404
- if (argv[0] === 'config') {
405
- return runConfigCommand(APP, root, taken.rest, {
406
- ...io,
407
- env,
408
- home,
409
- defaults: WAYFINDER_DEFAULTS,
410
- });
411
- }
412
- if (argv[0] === 'trust')
413
- return runTrustCommand(APP, root, taken.rest, { ...io, env, home });
414
- return runProvidersCommand(root, taken.rest, {
415
- ...io,
416
- env,
417
- home,
418
- configuredAllowExec,
419
- load: async (cfg, modules, projectAllowed) => projectFor(modules, cfg, home, projectAllowed),
420
- });
421
- }
422
- if (argv[0] === 'clean')
423
- return runCleanCommand(APP, argv.slice(1), { ...io, env, home });
424
- if (argv[0] === 'guide')
425
- return runGuideCommand(GUIDE_TOOL, argv.slice(1), io);
426
- // `dev` is a contributor tool, so the help does not list it. `self` is this
427
- // checkout, so `dev install` and a bare `dev link` know what to point at.
428
- if (argv[0] === 'dev') {
429
- const devArgs = argv.slice(1);
430
- return runDevCli(WAYFINDER_SPEC, devArgs, {
431
- io: devArgs.includes('--json') ? safeJsonStdout(io) : safeStdout(io),
153
+ const cwd = process.cwd();
154
+ // `dev` is a contributor tool that parses its own arguments, so help does
155
+ // not list it. `self` is this checkout, so `dev install` and a bare
156
+ // `dev link` know what to point at. Global flags before the word move after it.
157
+ const at = commandWordIndex(argv);
158
+ if (at !== -1 && argv[at] === 'dev') {
159
+ const rest = [...argv.slice(at + 1), ...argv.slice(0, at)];
160
+ return runDevCli(WAYFINDER_SPEC, rest, {
161
+ io: rest.includes('--json') ? safeJsonStdout(io) : safeStdout(io),
432
162
  env,
433
163
  self: checkoutRoot(),
434
164
  });
435
165
  }
436
- const parsed = parseArgs(argv, io);
437
- // A usage error prints the short help, so the error is easy to find.
438
- if ('error' in parsed)
439
- return usageError(parsed.error);
440
- if (parsed.help) {
441
- io.stdout(parsed.all ? USAGE : SHORT_USAGE);
442
- return EXIT.ok;
443
- }
444
- const root = await findRoot(parsed.dir);
445
- let cfg;
446
- try {
447
- cfg = await loadConfig(root, env, home);
448
- }
449
- catch (err) {
450
- if (err instanceof ConfigError) {
451
- io.stderr(`${APP}: ${err.message}\n`);
452
- return EXIT.error;
453
- }
454
- throw err;
455
- }
456
- for (const warning of cfg.warnings)
457
- io.stderr(`warning: ${warning}\n`);
458
- // Precedence for allowExec, highest first: --exec / --no-exec, then
459
- // allowExec in the project file (false only), then the user file, then
460
- // wayfinder's own default (true). Only `sources` tells "a file said false"
461
- // apart from "no file set it".
462
- const configured = configuredAllowExec(cfg);
463
- // Trust is decided here. Collection never reads the trust store.
464
- const trustStoreInstance = appTrustStore({ env, home });
465
- const gate = await policyExecGate(trustStoreInstance, trustPolicyFromConfig(cfg.effective), { root, configured, flag: parsed.allowExec }, trustPolicyOptions(home));
466
- // A project module runs code on import, so it needs execution allowed as
467
- // well as trust.
468
- const projectAllowed = gate.trusted && gate.allowExec;
469
- const built = await projectFor(parsed.toolModules, cfg, home, projectAllowed);
470
- const projectToolsPending = !projectAllowed && (cfg.layers.project?.tools?.length ?? 0) > 0;
471
- if ('error' in built) {
472
- io.stderr(`${APP}: ${built.error}\n`);
473
- return EXIT.error;
474
- }
475
- for (const warning of built.warnings)
476
- io.stderr(`warning: ${warning}\n`);
477
- const { project } = built;
478
- // The config's own allowExec was consumed above.
479
- const { allowExec: _consumed, ...configOptions } = collectOptionsFromConfig(cfg.effective);
480
- // Config first, flags second. --exclude REPLACES runners.disabled.
481
- const options = {
482
- ...configOptions,
483
- allowExec: gate.allowExec,
484
- // Only when trust is what is missing: when a file turned execution off,
485
- // trusting the repository would change nothing.
486
- ...(gate.reason === 'untrusted' ? { execWithheldHint: withheldHint(BIN) } : {}),
487
- ...(parsed.only ? { only: parsed.only } : {}),
488
- ...(parsed.exclude ? { exclude: parsed.exclude } : {}),
489
- ...(parsed.excludePaths ? { excludePaths: parsed.excludePaths } : {}),
490
- ...(parsed.discovery !== undefined ? { discovery: parsed.discovery } : {}),
491
- };
492
- // The config keys a flag already set. When the page saves the config,
493
- // `serve` re-reads the file's options and leaves these alone.
494
- const pinnedByFlag = [
495
- ...(parsed.exclude ? ['exclude'] : []),
496
- ...(parsed.excludePaths ? ['excludePaths'] : []),
497
- ...(parsed.discovery !== undefined ? ['discovery'] : []),
498
- ];
499
- // Printed once for all runners, and only by the non-interactive modes. The
500
- // TUI and the page show their own trust prompt.
501
- const reportWithheld = (catalog) => {
502
- const withheld = catalog.reports.filter((r) => r.skippedForExec).length;
503
- if (gate.reason !== 'untrusted' || withheld === 0)
504
- return;
505
- io.stderr(`${APP}: ${withheld} runner${withheld === 1 ? '' : 's'} not collected — ${withheldHint(BIN)}\n`);
506
- };
507
- const store = cacheDir(env, home);
508
- const order = cfg.effective.runners?.order;
509
- /**
510
- * The catalog for a data surface, plus the cache states when the store was
511
- * read. Probed fresh by default, since a script must not get an old answer
512
- * without being told. The probe still writes the store. --cached reads the
513
- * store and says so on stderr.
514
- */
515
- const dataCatalog = async () => {
516
- if (!parsed.cached) {
517
- const fresh = await collectAndCache(project, root, options, store);
518
- return { catalog: orderedCatalog(fresh, order), cache: undefined };
519
- }
520
- const stored = await readCachedCatalog(project, root, options, store);
521
- if (stored.catalog === null || !fromStore(stored)) {
522
- io.stderr(`${APP}: --cached: nothing cached for this repository yet — probed it fresh, and this run stores the result\n`);
523
- const fresh = await collectAndCache(project, root, options, store);
524
- return { catalog: orderedCatalog(fresh, order), cache: freshStates(fresh) };
525
- }
526
- // A miss is a runner with nothing stored. Only the missing runners are probed.
527
- const missing = stored.runners.filter((r) => r.state === 'miss').map((r) => r.runner);
528
- const merged = missing.length === 0
529
- ? stored.catalog
530
- : {
531
- ...stored.catalog,
532
- reports: [
533
- ...stored.catalog.reports,
534
- ...(await collectAndCache(project, root, { ...options, only: missing }, store))
535
- .reports,
536
- ],
537
- };
538
- // stderr, never stdout: --list stays pipeable and --json stays parseable.
539
- const note = cacheNote(stored.runners);
540
- if (note !== null)
541
- io.stderr(note);
542
- return { catalog: orderedCatalog(merged, order), cache: stored.runners };
543
- };
544
- switch (parsed.mode) {
545
- case 'serve':
546
- return serve({
547
- project,
548
- projectToolsPending,
549
- root,
550
- collectOptions: options,
551
- pinnedByFlag,
552
- open: parsed.open,
553
- runnerOrder: order,
554
- env,
555
- home,
556
- ...(parsed.port !== undefined ? { port: parsed.port } : {}),
557
- });
558
- case 'json': {
559
- const { catalog, cache } = await dataCatalog();
560
- io.stdout(`${jsonText(catalogJson(catalog, cache), 2)}\n`);
561
- reportWithheld(catalog);
562
- return EXIT.ok;
563
- }
564
- case 'list': {
565
- const { catalog } = await dataCatalog();
566
- const lines = allTasks(catalog).map((t) => terminalSafe(t.display));
567
- if (lines.length > 0)
568
- io.stdout(`${lines.join('\n')}\n`);
569
- reportWithheld(catalog);
570
- return EXIT.ok;
571
- }
572
- case 'query': {
573
- const { catalog } = await dataCatalog();
574
- // Joined and re-split, so a quoted "dep env" is two terms.
575
- const queryTerms = searchTerms((parsed.terms ?? []).join(' '));
576
- const hits = [];
577
- for (const task of allTasks(catalog)) {
578
- if (parsed.servicesOnly && !task.persistent.value)
579
- continue;
580
- // An empty query matches everything, as the TUI's empty entry line does.
581
- if (queryTerms.length === 0) {
582
- hits.push({ task, score: 0 });
583
- continue;
584
- }
585
- const m = matchEntry(task, queryTerms, parsed.matchMode);
586
- if (m !== null)
587
- hits.push({ task, score: m.score });
588
- }
589
- // Stable, so equal scores keep the catalog's own order.
590
- if (queryTerms.length > 0)
591
- hits.sort((a, b) => b.score - a.score);
592
- if (parsed.json) {
593
- io.stdout(`${jsonText(hits.map((h) => h.task), 2)}\n`);
594
- }
595
- else if (hits.length > 0) {
596
- io.stdout(`${hits.map((h) => terminalSafe(h.task.display)).join('\n')}\n`);
597
- }
598
- reportWithheld(catalog);
599
- // As with grep, a search with terms that matched nothing exits 1.
600
- return queryTerms.length > 0 && hits.length === 0 ? 1 : 0;
601
- }
602
- case 'tui':
603
- return runTui({
604
- project,
605
- projectToolsPending,
606
- root,
607
- options,
608
- runnerOrder: order,
609
- gate,
610
- env,
611
- home,
612
- });
166
+ const { app, words } = createWayApp({ home, guide: () => GUIDE_TOOL });
167
+ const aliased = rewriteAliases(argv, words);
168
+ if ('error' in aliased)
169
+ return usageError(io, argv, aliased.error);
170
+ if (aliased.alias !== undefined) {
171
+ const now = SURFACE_FLAGS[aliased.alias].join(' ');
172
+ io.stderr(`${BIN}: warning: ${aliased.alias} is deprecated and goes away in a later release; use "${BIN} ${now}"\n`);
613
173
  }
174
+ const code = await app.run(aliased.argv, {
175
+ // JSON keeps every value exact, with DEL, C1 and bidi controls escaped.
176
+ // Each command makes its own text output terminal-safe.
177
+ io: safeJsonStdout(io),
178
+ cwd,
179
+ env,
180
+ ...(real ? { terminal: processContext().terminal } : {}),
181
+ });
182
+ // The output is out; the saved view a command wrote ends before main does.
183
+ await flushViews();
184
+ return code;
614
185
  }
615
186
  // Runs when executed directly (devlink runs a checkout's `src/cli.ts` under
616
187
  // Bun); inert when imported by the bin.