@osdlc/wayfinder 0.0.1-stage → 0.7.1

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