@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/config.js CHANGED
@@ -4,163 +4,137 @@
4
4
  * project structure, whether execution is allowed, extra tools) are set once,
5
5
  * per user and per project. Flags are for one-off changes.
6
6
  *
7
+ * {@link WayfinderConfigSchema} is the one description of the file. Validation,
8
+ * the settable keys, the key order of a written file and `schema/config.json`
9
+ * all come from it.
10
+ *
7
11
  * ## Layers, lowest precedence first
8
12
  *
9
- * 1. `DEFAULT_CONFIG` — the built-in defaults.
10
- * 2. USER — `$XDG_CONFIG_HOME/wayfinder/config.json`, or `~/.config/wayfinder/config.json`
11
- * when `XDG_CONFIG_HOME` is unset or relative.
12
- * 3. PROJECT — `wayfinder.config.json` at the root `findRoot` resolves.
13
+ * 1. {@link DEFAULT_CONFIG}: the built-in defaults.
14
+ * 2. USER: `<config>/wayfinder/config.json` (see `xdg.ts`), or the file
15
+ * `WAYFINDER_CONFIG` names.
16
+ * 3. PROJECT: `wayfinder.config.json` at the project root.
13
17
  * 4. CLI flags, applied by the caller. {@link collectOptionsFromConfig}
14
18
  * returns the options a caller spreads its own flags on top of.
15
19
  *
16
- * `allowExec` is an exception to this order. The project layer may lower it to
17
- * `false`, since a repository asking not to be run is safe to honour. It can
18
- * never raise it to `true`. `wayfinder.config.json` lives inside the repository
19
- * being scanned, so honouring `allowExec: true` from it would let a repository
20
- * authorize running its own code. So `allowExec: true` is removed from the
21
- * project layer before merging, with a warning. Only the user layer and the CLI
22
- * flags can turn execution on. To give a repository lasting permission, run
23
- * `way trust`, which records the consent outside the repository.
20
+ * The project file lives inside the repository being scanned, so it may not
21
+ * set what would let a repository authorize itself, or what is a person's own
22
+ * choice. Each of these is dropped from the project layer before the merge,
23
+ * with a warning, and `config set --project` refuses to write it:
24
+ *
25
+ * - `allowExec: true`. A project may lower `allowExec` to `false`, never
26
+ * raise it. Run `way trust` to give a repository lasting permission.
27
+ * - `trust`, whole. A repository must not pre-authorize itself, or any group
28
+ * of repositories that includes it.
29
+ * - `open`, `theme` and `skills`, which say how a person likes to work.
24
30
  *
25
31
  * `tools` is gated too, because a tool module is code. User-layer entries
26
32
  * always load; project-layer entries load only when the repository is trusted
27
33
  * and execution is allowed (see `tools.ts`).
28
34
  *
29
- * `trust` is a stricter exception. It has no lower setting a project could
30
- * choose, so the whole project-layer `trust` block is dropped, with a warning
31
- * when it is not empty. A repository must not be able to pre-authorize itself,
32
- * or any group of repositories that includes it. Only the user layer's `trust`
33
- * reaches `@osdlc/trust-repo`'s `policyExecGate`, which combines it with the
34
- * marker store that `way trust` writes to. See that package's README for the
35
- * glob dialect, and `origin-owner.ts` for the origin-remote lookup that
36
- * `trust.owners` uses.
37
- *
38
- * XDG paths are used on every platform, macOS included, as `gh` does. A
39
- * developer with a dotfiles repository expects this file beside their other
40
- * tool config.
41
- *
42
35
  * `WAYFINDER_CONFIG=/path/to/file` changes only where the user layer is read
43
- * from. The named file is read instead of the XDG path. The project layer is
44
- * still read from the project root and still merges on top. Naming a file that
45
- * does not exist is an error, not an empty layer: an env var that points at
46
- * nothing is a typo. A relative value is ignored with a warning, and the XDG
47
- * path is read instead.
48
- *
49
- * ## The old waypost names
50
- *
51
- * The tool was called waypost before its first release. Each old name is still
52
- * read when its new one is absent, so an existing setup keeps working:
53
- * `WAYPOST_CONFIG` when `WAYFINDER_CONFIG` is unset, `<config>/waypost/config.json`
54
- * when `<config>/wayfinder/config.json` does not exist, and `waypost.config.json`
55
- * when `wayfinder.config.json` does not exist. A file found this way is also the
56
- * one `config set` edits, so a setting never lands in a file that is not read.
57
- * Each fallback adds a warning that names the new location. When both the old
58
- * and the new file exist, the new one is read and a warning says the old one
59
- * is ignored.
36
+ * from. Naming a file that does not exist is an error, not an empty layer. A
37
+ * relative value is ignored with a warning, since from the project root it
38
+ * would name a file in the repository.
60
39
  *
61
40
  * ## Merge rule
62
41
  *
63
42
  * Objects merge key by key. Everything else, scalars and arrays alike,
64
- * replaces the lower value whole. Arrays replace because each array setting
65
- * answers "which ones, in what order". A project that says `order: ["just"]`
66
- * means that list, not that list appended to the user's.
67
- *
68
- * user { runners: { disabled: ["cargo"], order: ["moon"] } }
69
- * project { runners: { order: ["just"] } }
70
- * result { runners: { disabled: ["cargo"], order: ["just"] } }
43
+ * replaces the lower value whole. A project that says `order: ["just"]` means
44
+ * that list, not that list appended to the user's.
71
45
  *
72
46
  * ## Unknown keys and broken files
73
47
  *
74
- * An unknown key is a warning naming the file and the key, and the rest of the
75
- * file still loads. A config written for a newer version must not break an
76
- * older one. A malformed file, or a value of the wrong type for a known key, is
77
- * a {@link ConfigError} naming the file and the problem. There is no silent
78
- * fallback: a setting that quietly did not apply is worse than one that refused
79
- * to load.
48
+ * An unknown key is a warning naming the file and the key, with the closest
49
+ * known key, and the rest of the file still loads: a file written for a newer
50
+ * version must not break an older one. A malformed file, or a value of the
51
+ * wrong type for a known key, is a {@link ConfigError} naming the file and the
52
+ * problem. `$schema` is accepted and ignored.
80
53
  */
81
- import { existsSync } from 'node:fs';
82
- import { mkdir, writeFile } from 'node:fs/promises';
83
- import { dirname, isAbsolute, join, resolve } from 'node:path';
84
- import { readParsedFile } from '@osdlc/config-layers';
85
- import { homeDir, resolveTrustRoot, } from '@osdlc/trust-repo';
86
- import { APP, BIN, CONFIG_ENV_VAR, LEGACY_APP, LEGACY_CONFIG_ENV_VAR, LEGACY_PROJECT_CONFIG_FILENAME, PROJECT_CONFIG_FILENAME, } from "./app.js";
87
- import { originOwner } from "./origin-owner.js";
88
- import { expandTilde } from "./xdg.js";
89
- export { CONFIG_ENV_VAR, PROJECT_CONFIG_FILENAME };
90
- /** Directory under `$XDG_CONFIG_HOME` holding the USER layer. */
91
- export const USER_CONFIG_DIR = APP;
92
- /** The `tool` key of the trust store (`$XDG_STATE_HOME/<tool>/trusted/`). */
93
- export const TRUST_STORE_TOOL = APP;
94
- /** The old {@link USER_CONFIG_DIR}, read when the new user file does not exist. */
95
- export const LEGACY_USER_CONFIG_DIR = LEGACY_APP;
96
- /** The old {@link TRUST_STORE_TOOL}. Its grants are still honoured; see `trust-store.ts`. */
97
- export const LEGACY_TRUST_STORE_TOOL = LEGACY_APP;
98
- /** The USER layer's filename inside {@link USER_CONFIG_DIR}. */
99
- export const USER_CONFIG_FILENAME = 'config.json';
54
+ import { constants, existsSync } from 'node:fs';
55
+ import { lstat, open, readlink, realpath } from 'node:fs/promises';
56
+ import { dirname, isAbsolute, join as joinPath, resolve } from 'node:path';
57
+ import { z } from 'zod';
58
+ import { closestMatches } from '@osdlc/config-layers/did-you-mean';
59
+ import { atomicWriteAsync } from '@osdlc/etag-write';
60
+ import { expandTrustPath, homeDir, } from '@osdlc/trust-repo';
61
+ import { originOwner } from '@osdlc/trust-repo/git';
62
+ import { APP, BIN, CONFIG_ENV_VAR, PROJECT_CONFIG_FILENAME } from "./app.js";
63
+ import { THEME_VALUES } from "./config-keys.js";
64
+ import { appDirs, expandTilde, pre08Bases, USER_CONFIG_FILENAME } from "./xdg.js";
65
+ import { SKILLS_SETTING_VALUES } from "./core/skills.js";
66
+ export { CONFIG_ENV_VAR, PROJECT_CONFIG_FILENAME, USER_CONFIG_FILENAME };
100
67
  /**
101
- * The built-in defaults layer.
102
- *
103
- * Every leaf is present, so {@link LoadedConfig.sources} has an entry for
104
- * every key. A key set in no file is attributed to this layer.
68
+ * The URL a written file's `$schema` names: the schema this release line ships
69
+ * in `schema/config.json`. Raise it with each minor release.
105
70
  */
106
- export const DEFAULT_CONFIG = {
107
- runners: { disabled: [], order: [] },
108
- allowExec: false,
109
- discovery: 'auto',
110
- excludePaths: [],
111
- trust: { paths: [], owners: [] },
112
- tools: [],
113
- };
71
+ export const CONFIG_SCHEMA_URL = 'https://unpkg.com/@osdlc/wayfinder@0.8/schema/config.json';
72
+ const strings = (description) => z.array(z.string()).describe(description);
73
+ /** One set of trust rules: globs over the resolved root, and origin owners. */
74
+ const TrustRulesSchema = z.object({
75
+ paths: strings('Glob patterns over the repository root, symlinks resolved: *, ?, ** and a trailing /** for ' +
76
+ 'descendants only. A leading ~ is your home.').optional(),
77
+ owners: strings('Origin remote owners, as host/owner, or a bare owner for github.com/owner. Case-insensitive.').optional(),
78
+ });
79
+ /** The `discovery` values. */
80
+ export const DISCOVERY_VALUES = ['git', 'walk', 'auto'];
81
+ /** The `open` values: what the bare `way` command opens. */
82
+ export const OPEN_VALUES = ['tui', 'web'];
83
+ export { THEME_VALUES } from "./config-keys.js";
114
84
  /**
115
- * A configuration file that cannot be honoured — unparseable, or holding a
116
- * value of the wrong type.
85
+ * The configuration file, as a Zod schema. Every key is optional; the defaults
86
+ * are {@link DEFAULT_CONFIG}.
117
87
  */
118
- export class ConfigError extends Error {
119
- /**
120
- * The file the error is about. Empty when the error concerns a value handed
121
- * in directly, as {@link setConfigValue} does with a bad key or value.
122
- */
123
- file;
124
- constructor(message, file) {
125
- super(message);
126
- this.name = 'ConfigError';
127
- this.file = file;
128
- }
88
+ export const WayfinderConfigSchema = z
89
+ .object({
90
+ $schema: z.string().describe('The JSON Schema this file follows. Ignored by wayfinder.'),
91
+ runners: z
92
+ .object({
93
+ disabled: strings('Runner ids to skip entirely.'),
94
+ order: strings('Preferred display order. Runners not named follow alphabetically.'),
95
+ })
96
+ .partial()
97
+ .describe('Which runners are read, and in what order they are shown.'),
98
+ allowExec: z
99
+ .boolean()
100
+ .describe('Whether runners that must run a subprocess may be read. Execution also needs a trusted ' +
101
+ 'repository. A project file may only set false.'),
102
+ discovery: z
103
+ .enum(DISCOVERY_VALUES)
104
+ .describe('How directories are found: git-tracked files, a directory walk, or auto.'),
105
+ excludePaths: strings('Paths to leave out of discovery. A bare name matches any path segment; a value with a ' +
106
+ 'slash matches a path from the root and the tree beneath it.'),
107
+ trust: TrustRulesSchema.extend({
108
+ tools: z
109
+ .record(z.string().min(1), TrustRulesSchema)
110
+ .describe('Rules that trust one tool each, keyed by tool id. They are checked after the ' +
111
+ 'top-level rules.')
112
+ .optional(),
113
+ }).describe('Repositories trusted without a marker. User config only: a project file cannot set it.'),
114
+ tools: strings('Modules that export extra tools. A relative path resolves against the file that names it.'),
115
+ open: z
116
+ .enum(OPEN_VALUES)
117
+ .describe('What the bare way command opens: the terminal UI or the web view. User config only.'),
118
+ theme: z.enum(THEME_VALUES).describe('The web view theme. User config only.'),
119
+ skills: z
120
+ .enum(SKILLS_SETTING_VALUES)
121
+ .describe("Which agent skills the Skills group lists: the repository's (project), those and your " +
122
+ "own and your plugins' (all), or none (off). User config only."),
123
+ })
124
+ .partial()
125
+ .describe('wayfinder configuration: wayfinder.config.json or the user config file.');
126
+ /** The schema's JSON Schema, as shipped in `schema/config.json`. */
127
+ export function configJsonSchema() {
128
+ const { $schema, ...schema } = z.toJSONSchema(WayfinderConfigSchema, { io: 'input' });
129
+ return { $schema, $id: CONFIG_SCHEMA_URL, title: 'wayfinder configuration', ...schema };
130
+ }
131
+ // ── Schema walking ──────────────────────────────────────────────────────────
132
+ function unwrap(schema) {
133
+ let s = schema;
134
+ while (s instanceof z.ZodOptional)
135
+ s = s.unwrap();
136
+ return s;
129
137
  }
130
- /**
131
- * Every settable key, by dotted path. Validation, {@link setConfigValue} and
132
- * the known-key check all read this one list, so a setting cannot be accepted
133
- * in one place and rejected in another.
134
- */
135
- const FIELDS = {
136
- 'runners.disabled': 'string-array',
137
- 'runners.order': 'string-array',
138
- allowExec: 'boolean',
139
- discovery: 'discovery',
140
- excludePaths: 'string-array',
141
- 'trust.paths': 'string-array',
142
- 'trust.owners': 'string-array',
143
- tools: 'string-array',
144
- };
145
- /**
146
- * Every settable key, in schema order — the dotted names `config set` accepts.
147
- *
148
- * Derived from {@link FIELDS}, so anything that lists the keys (the `guide`
149
- * command's config section) stays in step with the schema.
150
- */
151
- export const CONFIG_KEYS = Object.keys(FIELDS);
152
- const DISCOVERY_VALUES = ['git', 'walk', 'auto'];
153
- /**
154
- * Key order for writing: schema order, not alphabetical, so a written file
155
- * reads like the documented schema. Keys not listed here are unknown to this
156
- * version. They are written after the known ones, in the order the file
157
- * already had them.
158
- */
159
- const KEY_ORDER = {
160
- '': ['runners', 'allowExec', 'discovery', 'excludePaths', 'trust', 'tools'],
161
- runners: ['disabled', 'order'],
162
- trust: ['paths', 'owners'],
163
- };
164
138
  function isPlainObject(value) {
165
139
  return typeof value === 'object' && value !== null && !Array.isArray(value);
166
140
  }
@@ -171,179 +145,234 @@ function describe(value) {
171
145
  return 'an array';
172
146
  return `a ${typeof value}`;
173
147
  }
174
- /** Check one leaf against its declared type, returning it narrowed. */
175
- function coerceField(key, value, file) {
176
- const type = FIELDS[key];
177
- const where = file === '' ? '' : `${file}: `;
178
- switch (type) {
179
- case 'boolean':
180
- if (typeof value !== 'boolean') {
181
- throw new ConfigError(`${where}${key} must be true or false, got ${describe(value)}`, file);
182
- }
183
- return value;
184
- case 'string-array': {
185
- if (!Array.isArray(value)) {
186
- throw new ConfigError(`${where}${key} must be an array of strings, got ${describe(value)}`, file);
187
- }
188
- // Name the offending element, not the container: "got an array" reads as
189
- // a contradiction when an array is exactly what was asked for.
190
- const bad = value.findIndex((item) => typeof item !== 'string');
191
- if (bad !== -1) {
192
- throw new ConfigError(`${where}${key} must be an array of strings, got ${describe(value[bad])} at index ${bad}`, file);
193
- }
194
- return [...value];
148
+ /** What a leaf expects, in words: `true or false`, `one of git, walk, auto`. */
149
+ function expectation(schema) {
150
+ const s = unwrap(schema);
151
+ if (s instanceof z.ZodBoolean)
152
+ return 'true or false';
153
+ if (s instanceof z.ZodEnum)
154
+ return `one of ${s.options.join(', ')}`;
155
+ if (s instanceof z.ZodArray)
156
+ return 'an array of strings';
157
+ if (s instanceof z.ZodString)
158
+ return 'a string';
159
+ return 'an object';
160
+ }
161
+ const join = (prefix, key) => (prefix === '' ? key : `${prefix}.${key}`);
162
+ /**
163
+ * The schema node a dotted key names, or undefined. A record (`trust.tools`)
164
+ * takes any key, so `trust.tools.mise.paths` names a node.
165
+ */
166
+ function schemaAt(key) {
167
+ if (key === '' || key === '$schema')
168
+ return undefined;
169
+ let node = WayfinderConfigSchema;
170
+ for (const segment of key.split('.')) {
171
+ const s = unwrap(node);
172
+ if (s instanceof z.ZodObject) {
173
+ const next = s.shape[segment];
174
+ if (next === undefined || !Object.hasOwn(s.shape, segment))
175
+ return undefined;
176
+ node = next;
177
+ }
178
+ else if (s instanceof z.ZodRecord) {
179
+ if (!s.keyType.safeParse(segment).success)
180
+ return undefined;
181
+ node = s.valueType;
182
+ }
183
+ else {
184
+ return undefined;
195
185
  }
196
- case 'discovery':
197
- if (typeof value !== 'string' ||
198
- !DISCOVERY_VALUES.includes(value)) {
199
- throw new ConfigError(`${where}${key} must be one of ${DISCOVERY_VALUES.join(', ')}, got ${JSON.stringify(value)}`, file);
200
- }
201
- return value;
202
- default:
203
- throw new ConfigError(`${where}unknown setting: ${key}`, file);
204
186
  }
187
+ return node;
205
188
  }
206
- function unknownKeyWarning(file, key) {
207
- return `${file}: unknown setting "${key}" (ignored)`;
189
+ /** The dotted leaf keys under `schema`: an object is walked, anything else (a record too) is a leaf. */
190
+ function leafKeys(schema, prefix) {
191
+ const s = unwrap(schema);
192
+ if (!(s instanceof z.ZodObject))
193
+ return [prefix];
194
+ return Object.entries(s.shape).flatMap(([key, child]) => key === '$schema' ? [] : leafKeys(child, join(prefix, key)));
208
195
  }
209
196
  /**
210
- * Resolve where each layer's file lives. `env` and `home` are injectable so a
211
- * test does not read the developer's own `~/.config`. The only other input is
212
- * whether a file exists, which picks between a new name and its old waypost
213
- * name (see the module docblock).
214
- *
215
- * Rules for a path taken from the environment:
216
- *
217
- * A leading `~` is expanded against `home`. A shell expands it before exec, but
218
- * `.env` loaders, direnv and CI YAML pass the literal tilde through. Without
219
- * this, `~/config.json` would silently become `<somewhere>/~/config.json`.
197
+ * Every setting, in schema order: the dotted names `config list` shows and
198
+ * `config set` accepts. `trust.tools` is one setting whose value is an
199
+ * object; `config set` also takes a key under it, such as
200
+ * `trust.tools.mise.paths`.
201
+ */
202
+ export const CONFIG_KEYS = leafKeys(WayfinderConfigSchema, '');
203
+ export { CLI_ONLY_KEYS, USER_ONLY_KEYS } from "./config-keys.js";
204
+ /** Whether `key` is `top` or a key under it. */
205
+ function under(key, top) {
206
+ return key === top || key.startsWith(`${top}.`);
207
+ }
208
+ /**
209
+ * Why the project file may not hold `value` at `key`, in a few words, or null
210
+ * when it may. `config explain` shows it beside an ignored project value.
211
+ */
212
+ export function projectIgnoreReason(key, value) {
213
+ if (under(key, 'trust'))
214
+ return 'a repository cannot grant itself trust';
215
+ if (under(key, 'open') || under(key, 'theme') || under(key, 'skills')) {
216
+ return 'a personal setting, for the user config';
217
+ }
218
+ if (key === 'allowExec' && value === true)
219
+ return 'a repository cannot turn execution on';
220
+ return null;
221
+ }
222
+ /**
223
+ * Why `value` may not be written at `key` in the project file, or null when
224
+ * it may. `config set --project` and the web view's save both ask this.
225
+ */
226
+ export function projectWriteRefusal(key, value) {
227
+ const reason = projectIgnoreReason(key, value);
228
+ if (reason === null)
229
+ return null;
230
+ const fix = key === 'allowExec'
231
+ ? `run "${BIN} trust" to trust this repository`
232
+ : 'set it in your user config';
233
+ return `${key === 'allowExec' ? 'allowExec: true' : key} cannot be set in a project file: ${reason}; ${fix}`;
234
+ }
235
+ // ── Errors and locations ────────────────────────────────────────────────────
236
+ /**
237
+ * A configuration file that cannot be honoured: unparseable, or holding a
238
+ * value of the wrong type.
239
+ */
240
+ export class ConfigError extends Error {
241
+ /**
242
+ * The file the error is about. Empty when the error concerns a value handed
243
+ * in directly, as {@link setConfigValue} does with a bad key or value.
244
+ */
245
+ file;
246
+ constructor(message, file) {
247
+ super(message);
248
+ this.name = 'ConfigError';
249
+ this.file = file;
250
+ }
251
+ }
252
+ /**
253
+ * Where each layer's file lives. `env` and `home` are injectable so a test
254
+ * does not read the developer's own config. Nothing is read.
220
255
  *
221
- * A relative `XDG_CONFIG_HOME` is ignored, as the XDG spec says. A relative
222
- * `WAYFINDER_CONFIG` is ignored too, and `userEnvIgnored` says so. Resolved
223
- * against the root, or against the cwd, which is usually the root, it would
224
- * name a file inside the repository being scanned, and the user layer can
225
- * turn execution on and load tools.
256
+ * A leading `~` in {@link CONFIG_ENV_VAR} is expanded against `home`: `.env`
257
+ * loaders, direnv and CI YAML pass a literal tilde through. A relative value
258
+ * is ignored and `userEnvIgnored` says so.
226
259
  */
227
260
  export function configLocations(root, env = process.env, home = homeDir()) {
228
- const base = resolve(root);
229
- const fromVar = (name) => {
230
- const value = env[name]?.trim();
231
- return value !== undefined && value !== '' ? value : null;
232
- };
233
- const named = fromVar(CONFIG_ENV_VAR);
234
- const legacyNamed = named === null ? fromVar(LEGACY_CONFIG_ENV_VAR) : null;
235
- const namedVar = named !== null ? CONFIG_ENV_VAR : legacyNamed !== null ? LEGACY_CONFIG_ENV_VAR : null;
236
- const envValue = named ?? legacyNamed;
237
- const expanded = envValue === null ? null : expandTilde(envValue, home);
238
- const envPath = expanded !== null && isAbsolute(expanded) ? expanded : null;
239
- const userEnvVar = envPath !== null ? namedVar : null;
240
- const userEnvIgnored = namedVar !== null && envValue !== null && envPath === null
241
- ? { variable: namedVar, value: envValue }
242
- : null;
243
- const xdg = expandTilde(env['XDG_CONFIG_HOME']?.trim() ?? '', home);
244
- const configHome = isAbsolute(xdg) ? xdg : join(home, '.config');
245
- const xdgUser = preferNew(join(configHome, USER_CONFIG_DIR, USER_CONFIG_FILENAME), join(configHome, LEGACY_USER_CONFIG_DIR, USER_CONFIG_FILENAME));
246
- const project = preferNew(join(base, PROJECT_CONFIG_FILENAME), join(base, LEGACY_PROJECT_CONFIG_FILENAME));
261
+ const raw = env[CONFIG_ENV_VAR]?.trim();
262
+ const named = raw !== undefined && raw !== '' ? raw : null;
263
+ const expanded = named === null ? null : expandTilde(named, home);
264
+ const envPath = expanded !== null && isAbsolute(expanded) ? resolve(expanded) : null;
247
265
  return {
248
- user: envPath !== null ? resolve(envPath) : xdgUser.path,
266
+ user: envPath ?? appDirs({ env, home }).userConfig,
249
267
  userFromEnv: envPath !== null,
250
- userEnvVar,
251
- userLegacy: envPath === null && xdgUser.legacy,
252
- userIgnored: envPath === null ? xdgUser.ignored : null,
253
- userEnvIgnored,
254
- project: project.path,
255
- projectLegacy: project.legacy,
256
- projectIgnored: project.ignored,
268
+ userEnvVar: envPath !== null ? CONFIG_ENV_VAR : null,
269
+ userEnvIgnored: named !== null && envPath === null ? { variable: CONFIG_ENV_VAR, value: named } : null,
270
+ project: resolve(root, PROJECT_CONFIG_FILENAME),
257
271
  };
258
272
  }
259
273
  /**
260
- * The new path, unless only the old one exists. `ignored` names the old file
261
- * when both exist, so the caller can say it is not read.
274
+ * The warning for a Windows user config left where releases before 0.8 kept
275
+ * it (`~\.config\wayfinder\config.json`), when there is none at the new
276
+ * path. That file is not read, so its settings, `allowExec: false` among
277
+ * them, no longer apply. Null when there is nothing to say.
262
278
  */
263
- function preferNew(path, legacy) {
264
- const hasNew = existsSync(path);
265
- const hasLegacy = existsSync(legacy);
266
- if (!hasNew && hasLegacy)
267
- return { path: legacy, legacy: true, ignored: null };
268
- return { path, legacy: false, ignored: hasNew && hasLegacy ? legacy : null };
279
+ export function movedUserConfigWarning(locations, env, home, platform = process.platform) {
280
+ if (platform !== 'win32' || locations.userFromEnv)
281
+ return null;
282
+ const old = joinPath(pre08Bases(env, home).config, APP, USER_CONFIG_FILENAME);
283
+ if (resolve(old) === resolve(locations.user) || !existsSync(old))
284
+ return null;
285
+ if (existsSync(locations.user))
286
+ return null;
287
+ return (`${old}: this user config is from before 0.8 and is no longer read, so none of its ` +
288
+ `settings apply; move it to ${locations.user}`);
269
289
  }
290
+ /** The warning for a relative {@link CONFIG_ENV_VAR} that was ignored, or null. */
291
+ export function envIgnoredWarning(locations) {
292
+ if (locations.userEnvIgnored === null)
293
+ return null;
294
+ const { variable, value } = locations.userEnvIgnored;
295
+ return (`${variable}=${value} is ignored because it is not an absolute path; ` +
296
+ `use an absolute path or ~/. Reading ${locations.user} instead`);
297
+ }
298
+ // ── Validation ──────────────────────────────────────────────────────────────
270
299
  /**
271
- * Validate a parsed JSON document against schema v1.
272
- *
273
- * Throws {@link ConfigError} on a type error. Returns the known keys plus one
274
- * warning per unknown key. Because the result holds only known keys, the write
275
- * path never goes through this shape (see {@link readRawConfigFile}).
300
+ * Check `value` against `schema` at `key`, returning it with unknown keys
301
+ * removed. Unknown keys add a warning; a wrong value throws.
276
302
  */
277
- export function validateConfig(raw, file) {
278
- if (!isPlainObject(raw)) {
279
- throw new ConfigError(`${file}: expected a JSON object, got ${describe(raw)}`, file);
303
+ function check(schema, value, key, file, warnings) {
304
+ const where = file === '' ? '' : `${file}: `;
305
+ const s = unwrap(schema);
306
+ if (s instanceof z.ZodObject) {
307
+ if (!isPlainObject(value)) {
308
+ throw new ConfigError(key === ''
309
+ ? `${where}expected a JSON object, got ${describe(value)}`
310
+ : `${where}${key} must be an object, got ${describe(value)}`, file);
311
+ }
312
+ const shape = s.shape;
313
+ const out = {};
314
+ for (const [inner, innerValue] of Object.entries(value)) {
315
+ if (innerValue === undefined)
316
+ continue;
317
+ const child = Object.hasOwn(shape, inner) ? shape[inner] : undefined;
318
+ if (child === undefined) {
319
+ const close = closestMatches(inner, Object.keys(shape).filter((k) => k !== '$schema')).map((k) => join(key, k));
320
+ warnings.push(`${where}unknown setting "${join(key, inner)}" (ignored)` +
321
+ (close.length > 0 ? `; did you mean ${close.join(', ')}?` : ''));
322
+ continue;
323
+ }
324
+ out[inner] = check(child, innerValue, join(key, inner), file, warnings);
325
+ }
326
+ return out;
280
327
  }
281
- const warnings = [];
282
- const config = {};
283
- for (const [key, value] of Object.entries(raw)) {
284
- if (value === undefined)
285
- continue;
286
- switch (key) {
287
- case 'runners': {
288
- if (!isPlainObject(value)) {
289
- throw new ConfigError(`${file}: runners must be an object, got ${describe(value)}`, file);
290
- }
291
- const runners = {};
292
- for (const [inner, innerValue] of Object.entries(value)) {
293
- if (innerValue === undefined)
294
- continue;
295
- if (inner === 'disabled' || inner === 'order') {
296
- runners[inner] = coerceField(`runners.${inner}`, innerValue, file);
297
- }
298
- else {
299
- warnings.push(unknownKeyWarning(file, `runners.${inner}`));
300
- }
301
- }
302
- config.runners = runners;
303
- break;
328
+ if (s instanceof z.ZodRecord) {
329
+ if (!isPlainObject(value)) {
330
+ throw new ConfigError(`${where}${key} must be an object, got ${describe(value)}`, file);
331
+ }
332
+ const out = {};
333
+ for (const [inner, innerValue] of Object.entries(value)) {
334
+ if (innerValue === undefined)
335
+ continue;
336
+ if (!s.keyType.safeParse(inner).success) {
337
+ throw new ConfigError(`${where}${key} has an empty key`, file);
304
338
  }
305
- case 'allowExec':
306
- config.allowExec = coerceField('allowExec', value, file);
307
- break;
308
- case 'discovery':
309
- config.discovery = coerceField('discovery', value, file);
310
- break;
311
- case 'excludePaths':
312
- config.excludePaths = coerceField('excludePaths', value, file);
313
- break;
314
- case 'trust': {
315
- if (!isPlainObject(value)) {
316
- throw new ConfigError(`${file}: trust must be an object, got ${describe(value)}`, file);
317
- }
318
- const trust = {};
319
- for (const [inner, innerValue] of Object.entries(value)) {
320
- if (innerValue === undefined)
321
- continue;
322
- if (inner === 'paths' || inner === 'owners') {
323
- trust[inner] = coerceField(`trust.${inner}`, innerValue, file);
324
- }
325
- else {
326
- warnings.push(unknownKeyWarning(file, `trust.${inner}`));
327
- }
328
- }
329
- config.trust = trust;
330
- break;
339
+ // Assigning `__proto__` would set the object's prototype, not a key.
340
+ if (inner === '__proto__') {
341
+ warnings.push(`${where}"${join(key, inner)}" is not a usable key (ignored)`);
342
+ continue;
331
343
  }
332
- case 'tools':
333
- config.tools = coerceField('tools', value, file);
334
- break;
335
- default:
336
- warnings.push(unknownKeyWarning(file, key));
344
+ out[inner] = check(s.valueType, innerValue, join(key, inner), file, warnings);
337
345
  }
346
+ return out;
338
347
  }
339
- return { config, warnings };
348
+ const parsed = s.safeParse(value);
349
+ if (parsed.success)
350
+ return parsed.data;
351
+ // Name the offending element, not the container: "got an array" reads as a
352
+ // contradiction when an array is what was asked for.
353
+ if (s instanceof z.ZodArray && Array.isArray(value)) {
354
+ const bad = value.findIndex((item) => !s.element.safeParse(item).success);
355
+ throw new ConfigError(`${where}${key} must be ${expectation(s)}, got ${describe(value[bad])} at index ${bad}`, file);
356
+ }
357
+ const got = s instanceof z.ZodEnum ? JSON.stringify(value) : describe(value);
358
+ throw new ConfigError(`${where}${key} must be ${expectation(s)}, got ${got}`, file);
340
359
  }
341
360
  /**
342
- * Deep-copy a value so the result shares no mutable structure with its source.
343
- * A shallow spread is not enough. Every `loadConfig` merges on top of the
344
- * exported `DEFAULT_CONFIG` object, so a shared branch would let a caller that
345
- * mutates `effective` corrupt the defaults for every later load.
361
+ * Validate a parsed JSON document against {@link WayfinderConfigSchema}.
362
+ *
363
+ * Throws {@link ConfigError} on a wrong value. Returns the known keys (without
364
+ * `$schema`) plus one warning per unknown key. Because the result holds only
365
+ * known keys, the write path never goes through this shape (see
366
+ * {@link readRawConfigFile}).
346
367
  */
368
+ export function validateConfig(raw, file) {
369
+ const warnings = [];
370
+ const checked = check(WayfinderConfigSchema, raw, '', file, warnings);
371
+ const { $schema: _schema, ...config } = checked;
372
+ return { config: config, warnings };
373
+ }
374
+ // ── Merge ───────────────────────────────────────────────────────────────────
375
+ /** A deep copy that shares no object or array with `value`. */
347
376
  function cloneValue(value) {
348
377
  if (Array.isArray(value))
349
378
  return value.map(cloneValue);
@@ -358,67 +387,119 @@ function cloneValue(value) {
358
387
  function deepMerge(base, over) {
359
388
  const out = {};
360
389
  for (const key of new Set([...Object.keys(base), ...Object.keys(over)])) {
361
- const under = base[key];
390
+ const below = base[key];
362
391
  const above = over[key];
363
- if (above === undefined) {
364
- out[key] = cloneValue(under);
365
- }
366
- else if (isPlainObject(under) && isPlainObject(above)) {
367
- out[key] = deepMerge(under, above);
368
- }
369
- else {
392
+ if (above === undefined)
393
+ out[key] = cloneValue(below);
394
+ else if (isPlainObject(below) && isPlainObject(above))
395
+ out[key] = deepMerge(below, above);
396
+ else
370
397
  out[key] = cloneValue(above);
371
- }
372
398
  }
373
399
  return out;
374
400
  }
375
401
  /**
376
402
  * Merge `over` onto `base` per the module's rule: objects key by key, scalars
377
- * and arrays replaced whole.
378
- *
379
- * Neither argument is changed, and the result shares no object or array with
380
- * either, including branches `over` does not mention. Mutating a loaded config
381
- * must not change `DEFAULT_CONFIG`.
403
+ * and arrays replaced whole. Neither argument is changed, and the result
404
+ * shares no object or array with either, so mutating a loaded config cannot
405
+ * change {@link DEFAULT_CONFIG}.
382
406
  */
383
407
  export function mergeConfig(base, over) {
384
408
  return deepMerge(base, over);
385
409
  }
386
410
  /**
387
- * One layer file as a plain object, read with `@osdlc/config-layers`'s
388
- * `readParsedFile`. `null` when the file does not exist. A file that is
389
- * unreadable, not JSON, or not an object throws {@link ConfigError} naming it.
411
+ * The built-in defaults layer. Every setting is present, so
412
+ * {@link LoadedConfig.sources} has an entry for each one.
413
+ *
414
+ * `allowExec: true` does not mean "run this repository's code". The
415
+ * repository must also be trusted, and a configured `false` still means no
416
+ * execution.
390
417
  */
391
- async function readJsonFile(file) {
392
- const read = readParsedFile(file, 'json');
393
- switch (read.kind) {
394
- case 'absent':
418
+ export const DEFAULT_CONFIG = {
419
+ runners: { disabled: [], order: [] },
420
+ allowExec: true,
421
+ discovery: 'auto',
422
+ excludePaths: [],
423
+ trust: { paths: [], owners: [], tools: {} },
424
+ tools: [],
425
+ open: 'tui',
426
+ theme: 'system',
427
+ skills: 'project',
428
+ };
429
+ // ── Files ───────────────────────────────────────────────────────────────────
430
+ /** The largest config file read. A real one is a few kilobytes. */
431
+ const MAX_CONFIG_BYTES = 1024 * 1024;
432
+ /**
433
+ * One layer file's text, or null when it does not exist. The project file is
434
+ * repository content, so only a regular file of at most
435
+ * {@link MAX_CONFIG_BYTES} is read: a committed link to `/dev/zero` or a FIFO
436
+ * must not hang or fill memory. Opened non-blocking, so a FIFO does not wait
437
+ * for a writer.
438
+ */
439
+ async function readConfigText(file) {
440
+ let handle;
441
+ try {
442
+ handle = await open(file, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
443
+ }
444
+ catch (err) {
445
+ if (err.code === 'ENOENT')
395
446
  return null;
396
- case 'unreadable':
397
- throw new ConfigError(`${file}: cannot be read — ${read.message}`, file);
398
- case 'unparsable':
399
- throw new ConfigError(`${file}: invalid JSON — ${read.message}`, file);
400
- case 'ok':
401
- if (!isPlainObject(read.value)) {
402
- throw new ConfigError(`${file}: expected a JSON object, got ${describe(read.value)}`, file);
403
- }
404
- return read.value;
447
+ throw new ConfigError(`${file}: cannot be read — ${err.message}`, file);
448
+ }
449
+ try {
450
+ const info = await handle.stat();
451
+ if (!info.isFile()) {
452
+ throw new ConfigError(`${file}: cannot be read — it is not a regular file`, file);
453
+ }
454
+ const buffer = Buffer.alloc(MAX_CONFIG_BYTES + 1);
455
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
456
+ if (bytesRead > MAX_CONFIG_BYTES) {
457
+ throw new ConfigError(`${file}: cannot be read — it is larger than 1 MB`, file);
458
+ }
459
+ return buffer.subarray(0, bytesRead).toString('utf8');
460
+ }
461
+ catch (err) {
462
+ if (err instanceof ConfigError)
463
+ throw err;
464
+ throw new ConfigError(`${file}: cannot be read — ${err.message}`, file);
465
+ }
466
+ finally {
467
+ await handle.close();
405
468
  }
406
469
  }
407
470
  /**
408
- * The file's parsed object, unvalidated and with every key intact.
409
- *
410
- * `set` and `unset` edit this object, not the validated shape, because
411
- * validation drops unknown keys. Writing a validated document back would
412
- * silently delete a setting a newer version had written. `null` when the file
413
- * does not exist.
471
+ * One layer file as a plain object. `null` when the file does not exist. A
472
+ * file that is unreadable, not JSON, or not an object throws
473
+ * {@link ConfigError} naming it.
474
+ */
475
+ async function readJsonFile(file) {
476
+ const text = await readConfigText(file);
477
+ if (text === null)
478
+ return null;
479
+ let value;
480
+ try {
481
+ value = JSON.parse(text);
482
+ }
483
+ catch (err) {
484
+ throw new ConfigError(`${file}: invalid JSON — ${err.message}`, file);
485
+ }
486
+ if (!isPlainObject(value)) {
487
+ throw new ConfigError(`${file}: expected a JSON object, got ${describe(value)}`, file);
488
+ }
489
+ return value;
490
+ }
491
+ /**
492
+ * The file's parsed object, unvalidated and with every key intact. `set` and
493
+ * `unset` edit this object, not the validated shape, because validation drops
494
+ * unknown keys: writing a validated document back would delete a setting a
495
+ * newer version had written. `null` when the file does not exist.
414
496
  */
415
497
  export async function readRawConfigFile(file) {
416
498
  return readJsonFile(file);
417
499
  }
418
500
  /**
419
501
  * Read, parse and validate one layer. `null` when the file does not exist,
420
- * which is normal and not an error. A file that exists and is broken throws
421
- * {@link ConfigError}.
502
+ * which is normal. A file that exists and is broken throws {@link ConfigError}.
422
503
  */
423
504
  export async function readConfigFile(file) {
424
505
  const raw = await readJsonFile(file);
@@ -426,142 +507,221 @@ export async function readConfigFile(file) {
426
507
  return null;
427
508
  return validateConfig(raw, file);
428
509
  }
429
- function orderedKeys(record, section) {
430
- const canonical = KEY_ORDER[section] ?? [];
431
- const known = canonical.filter((key) => key in record);
432
- const rest = Object.keys(record).filter((key) => !canonical.includes(key));
433
- return [...known, ...rest];
434
- }
435
- function stabilize(record, section) {
510
+ /** `record` with known keys in schema order, unknown keys after them in their own order. */
511
+ function stabilize(record, schema) {
512
+ const s = unwrap(schema);
436
513
  const out = {};
437
- for (const key of orderedKeys(record, section)) {
514
+ if (s instanceof z.ZodRecord) {
515
+ for (const [key, value] of Object.entries(record)) {
516
+ out[key] = isPlainObject(value) ? stabilize(value, s.valueType) : value;
517
+ }
518
+ return out;
519
+ }
520
+ const shape = s instanceof z.ZodObject ? s.shape : {};
521
+ const known = Object.keys(shape).filter((key) => key in record);
522
+ const rest = Object.keys(record).filter((key) => !Object.hasOwn(shape, key));
523
+ for (const key of [...known, ...rest]) {
438
524
  const value = record[key];
439
- const child = section === '' ? key : `${section}.${key}`;
440
- out[key] =
441
- isPlainObject(value) && KEY_ORDER[child] !== undefined ? stabilize(value, child) : value;
525
+ const child = Object.hasOwn(shape, key) ? shape[key] : undefined;
526
+ out[key] = child !== undefined && isPlainObject(value) ? stabilize(value, child) : value;
442
527
  }
443
528
  return out;
444
529
  }
445
530
  /**
446
- * Write a configuration file: known keys in schema order, unknown keys after
447
- * them in the order they already had, two-space indent, trailing newline.
448
- * Parent directories are created.
531
+ * Write a configuration file atomically: a temporary file, then a rename, so
532
+ * a crash or two saves at once never leave a truncated file. Known keys come
533
+ * in schema order, unknown keys after them in the order they had, with a
534
+ * two-space indent and a trailing newline. A file with no `$schema` gets
535
+ * {@link CONFIG_SCHEMA_URL}. Parent directories are created.
449
536
  *
450
- * The order is fixed so that writing an unchanged document produces an
451
- * unchanged file. A config under version control should not show a diff
452
- * because a key moved.
453
- *
454
- * Accepts a raw record as well as a {@link TaskConfig}, so an edit can keep
455
- * unknown keys.
537
+ * Writing an unchanged document gives an unchanged file, so a config under
538
+ * version control shows no diff because a key moved. Accepts a raw record, so
539
+ * an edit can keep unknown keys.
456
540
  */
457
541
  export async function writeConfigFile(file, config) {
458
- const body = JSON.stringify(stabilize(config, ''), null, 2);
459
- await mkdir(dirname(file), { recursive: true });
460
- await writeFile(file, `${body}\n`, 'utf-8');
542
+ const record = config;
543
+ const withSchema = '$schema' in record ? record : { $schema: CONFIG_SCHEMA_URL, ...record };
544
+ const body = JSON.stringify(stabilize(withSchema, WayfinderConfigSchema), null, 2);
545
+ await atomicWriteAsync(file, `${body}\n`);
461
546
  }
462
- function leafPaths(value, prefix) {
463
- if (!isPlainObject(value))
464
- return [prefix];
465
- return Object.entries(value).flatMap(([key, inner]) => leafPaths(inner, prefix === '' ? key : `${prefix}.${key}`));
547
+ /**
548
+ * The project layer with what a project may not set removed, and a warning
549
+ * for each removal that could have mattered.
550
+ */
551
+ function projectRules(project, locations) {
552
+ const warnings = [];
553
+ const out = { ...project };
554
+ if (project.allowExec === true) {
555
+ // Warned even when the user layer also says true: the file's setting is
556
+ // never honoured, and its author might rely on it.
557
+ warnings.push(`${locations.project}: allowExec: true is ignored in a project file — a repository cannot grant itself permission to run subprocesses; run "${BIN} trust" to trust this repository`);
558
+ delete out['allowExec'];
559
+ }
560
+ if (project.trust !== undefined) {
561
+ // Dropped whole: even an empty `paths: []` would replace the user's list
562
+ // in the merge. Warned only when it granted something.
563
+ const t = project.trust;
564
+ const grants = (t.paths?.length ?? 0) > 0 ||
565
+ (t.owners?.length ?? 0) > 0 ||
566
+ Object.keys(t.tools ?? {}).length > 0;
567
+ if (grants) {
568
+ warnings.push(`${locations.project}: trust is ignored in a project file — a repository cannot grant ` +
569
+ `itself trust; set it in your user config (${locations.user}) instead`);
570
+ }
571
+ delete out['trust'];
572
+ }
573
+ for (const key of ['open', 'theme', 'skills']) {
574
+ if (project[key] !== undefined) {
575
+ warnings.push(`${locations.project}: ${key} is ignored in a project file — it is a personal setting; ` +
576
+ `set it in your user config (${locations.user}) instead`);
577
+ delete out[key];
578
+ }
579
+ }
580
+ return { project: out, warnings };
466
581
  }
467
582
  /**
468
- * Load every layer and merge them. `env` and `home` are injectable for the same
469
- * reason {@link configLocations} takes them.
583
+ * Load every layer and merge them. `env` and `home` are injectable for the
584
+ * same reason {@link configLocations} takes them.
470
585
  */
471
586
  export async function loadConfig(root, env = process.env, home = homeDir()) {
472
587
  const locations = configLocations(root, env, home);
473
588
  const userRead = await readConfigFile(locations.user);
474
589
  if (userRead === null && locations.userFromEnv) {
475
- throw new ConfigError(`${locations.user}: ${locations.userEnvVar ?? CONFIG_ENV_VAR} names a file that does not exist`, locations.user);
590
+ throw new ConfigError(`${locations.user}: ${CONFIG_ENV_VAR} names a file that does not exist`, locations.user);
476
591
  }
477
592
  const projectRead = await readConfigFile(locations.project);
593
+ const warnings = [];
594
+ const ignored = envIgnoredWarning(locations);
595
+ if (ignored !== null)
596
+ warnings.push(ignored);
597
+ const moved = movedUserConfigWarning(locations, env, home);
598
+ if (moved !== null)
599
+ warnings.push(moved);
600
+ warnings.push(...(userRead?.warnings ?? []), ...(projectRead?.warnings ?? []));
478
601
  const user = userRead?.config ?? null;
479
- let project = projectRead?.config ?? null;
480
- const warnings = [...(userRead?.warnings ?? []), ...(projectRead?.warnings ?? [])];
481
- warnings.push(...legacyWarnings(locations));
482
- // A repository cannot grant itself permission to run its own code. Lowering
483
- // to false is honoured. Raising to true is dropped here, before the merge and
484
- // before `sources`, so `config list` names the layer that really supplied the
485
- // value, not the ignored file.
486
- //
487
- // Not in validateConfig: that check is the same for every layer and is also
488
- // used by `config set`. This rule depends on which layer a value came from.
489
- if (project?.allowExec === true) {
490
- // Warn even when the user layer already said true. The file's setting is
491
- // never honoured, and without a warning its author might rely on it in a
492
- // repo where it has no effect.
493
- warnings.push(`${locations.project}: allowExec: true is ignored in a project file — a repository cannot grant itself permission to run subprocesses; run "${BIN} trust" to trust this repository`);
494
- const { allowExec: _ignored, ...rest } = project;
495
- project = rest;
496
- }
497
- // A stricter version of the same rule: a project-layer `trust` block is
498
- // dropped whole, whatever it holds. A repository must not pre-authorize
499
- // itself or any group of repositories. Even an empty `paths: []` would
500
- // otherwise replace the user's list in the merge. Only a non-empty block is
501
- // warned about, since an empty one granted nothing.
502
- if (project?.trust !== undefined) {
503
- if ((project.trust.paths?.length ?? 0) > 0 || (project.trust.owners?.length ?? 0) > 0) {
504
- warnings.push(`${locations.project}: trust is ignored in a project file — a repository cannot grant ` +
505
- `itself trust; set trust.paths/trust.owners in your user config (${locations.user}) instead`);
506
- }
507
- const { trust: _ignoredTrust, ...rest } = project;
508
- project = rest;
602
+ let project = null;
603
+ if (projectRead !== null) {
604
+ const ruled = projectRules(projectRead.config, locations);
605
+ project = ruled.project;
606
+ warnings.push(...ruled.warnings);
509
607
  }
510
608
  const effective = mergeConfig(mergeConfig(DEFAULT_CONFIG, user ?? {}), project ?? {});
511
609
  const sources = new Map();
512
- for (const key of leafPaths(effective, '')) {
513
- const layer = project !== null && getConfigValue(project, key) !== undefined
610
+ for (const key of CONFIG_KEYS) {
611
+ sources.set(key, project !== null && getConfigValue(project, key) !== undefined
514
612
  ? 'project'
515
613
  : user !== null && getConfigValue(user, key) !== undefined
516
614
  ? 'user'
517
- : 'default';
518
- sources.set(key, layer);
615
+ : 'default');
519
616
  }
520
617
  return {
521
618
  effective,
522
619
  layers: { default: DEFAULT_CONFIG, user, project },
620
+ files: { user, project: projectRead?.config ?? null },
523
621
  sources,
524
622
  locations,
525
623
  warnings,
526
624
  };
527
625
  }
528
- /** The warning for a relative `WAYFINDER_CONFIG` that was ignored, or null. */
529
- export function envIgnoredWarning(locations) {
530
- if (locations.userEnvIgnored === null)
531
- return null;
532
- const { variable, value } = locations.userEnvIgnored;
533
- return (`${variable}=${value} is ignored because it is not an absolute path; ` +
534
- `use an absolute path or ~/. Reading ${locations.user} instead`);
626
+ /** One setting of `loaded`. */
627
+ function settingOf(loaded, key) {
628
+ const source = loaded.sources.get(key) ?? 'default';
629
+ return {
630
+ key,
631
+ value: getConfigValue(loaded.effective, key),
632
+ source,
633
+ file: source === 'user'
634
+ ? loaded.locations.user
635
+ : source === 'project'
636
+ ? loaded.locations.project
637
+ : null,
638
+ };
535
639
  }
536
- /** One warning per old waypost name in use, naming the new one, and one for an ignored env path. */
537
- function legacyWarnings(locations) {
538
- const out = [];
539
- const ignored = envIgnoredWarning(locations);
540
- if (ignored !== null)
541
- out.push(ignored);
542
- if (locations.userEnvVar === LEGACY_CONFIG_ENV_VAR) {
543
- out.push(`${LEGACY_CONFIG_ENV_VAR} is the old name; set ${CONFIG_ENV_VAR} instead`);
544
- }
545
- if (locations.userLegacy) {
546
- const target = join(dirname(dirname(locations.user)), USER_CONFIG_DIR, USER_CONFIG_FILENAME);
547
- out.push(`${locations.user}: read from the old waypost location; move it to ${target}`);
548
- }
549
- if (locations.userIgnored !== null) {
550
- out.push(`${locations.userIgnored} is ignored because ${locations.user} exists; merge it and delete it`);
551
- }
552
- if (locations.projectLegacy) {
553
- out.push(`${locations.project}: the old file name; rename it to ${PROJECT_CONFIG_FILENAME}`);
640
+ /**
641
+ * Read every layer for `root` and return each setting's effective value and
642
+ * source. Throws {@link ConfigError} for a broken file.
643
+ */
644
+ export async function readSettings(root, env = process.env, home = homeDir()) {
645
+ return settingsFrom(await loadConfig(root, env, home));
646
+ }
647
+ /** {@link Settings} from a config already loaded. */
648
+ function settingsFrom(loaded) {
649
+ return {
650
+ loaded,
651
+ settings: CONFIG_KEYS.map((key) => settingOf(loaded, key)),
652
+ allowExec: settingOf(loaded, 'allowExec'),
653
+ open: settingOf(loaded, 'open'),
654
+ theme: settingOf(loaded, 'theme'),
655
+ runnerOrder: settingOf(loaded, 'runners.order'),
656
+ skills: settingOf(loaded, 'skills'),
657
+ warnings: loaded.warnings,
658
+ };
659
+ }
660
+ /**
661
+ * Write `value` at `key` in one layer's file, atomically, keeping every other
662
+ * key. Throws {@link ConfigError} with an empty `file` for an unknown key, a
663
+ * wrong value, or a key the project file may not hold (see
664
+ * {@link projectWriteRefusal}); throws one naming the file when the file is
665
+ * broken. Returns the file and the value as written, and warnings for unknown
666
+ * keys inside the value.
667
+ */
668
+ export async function writeSetting(target, key, value) {
669
+ const node = schemaAt(key);
670
+ if (node === undefined)
671
+ throw new ConfigError(`unknown setting: ${key}`, '');
672
+ const warnings = [];
673
+ const checked = check(node, value, key, '', warnings);
674
+ if (target.layer === 'project') {
675
+ const refused = projectWriteRefusal(key, checked);
676
+ if (refused !== null)
677
+ throw new ConfigError(refused, '');
554
678
  }
555
- if (locations.projectIgnored !== null) {
556
- out.push(`${locations.projectIgnored} is ignored because ${PROJECT_CONFIG_FILENAME} exists; merge it and delete it`);
679
+ const file = fileOf(target);
680
+ const document = setConfigValue((await readRawConfigFile(file)) ?? {}, key, checked);
681
+ // The whole document is checked before it is written. A failure here is a
682
+ // bad value already in the file, so the error names the file.
683
+ validateConfig(document, file);
684
+ await writeConfigFile(await writePath(target, file), document);
685
+ return { file, value: checked, warnings };
686
+ }
687
+ /** Remove `key` from one layer's file. `removed: false` when it was not set there. */
688
+ export async function removeSetting(target, key) {
689
+ const file = fileOf(target);
690
+ const document = await readRawConfigFile(file);
691
+ if (document === null || getConfigValue(document, key) === undefined) {
692
+ return { file, removed: false };
557
693
  }
558
- return out;
694
+ await writeConfigFile(await writePath(target, file), unsetConfigValue(document, key));
695
+ return { file, removed: true };
559
696
  }
560
- /** Read a dotted path — `"runners.order"`, `"allowExec"`. `undefined` when absent. */
697
+ /**
698
+ * Where a write to `file` goes. The atomic write renames a new file into
699
+ * place, which would replace a link with a regular file. A user config is
700
+ * often a link into a dotfiles repository, so for the user layer the write
701
+ * goes to the link's target. A project file that is a link is replaced, not
702
+ * followed: the repository chose the link, and its target may be outside it.
703
+ */
704
+ async function writePath(target, file) {
705
+ if (target.layer !== 'user')
706
+ return file;
707
+ const info = await lstat(file).catch(() => null);
708
+ if (info === null || !info.isSymbolicLink())
709
+ return file;
710
+ return realpath(file).catch(async () => resolve(dirname(file), await readlink(file)));
711
+ }
712
+ function fileOf(target) {
713
+ // Locations, not a load: where to write must not depend on the other layer
714
+ // parsing, and `--user` must work when WAYFINDER_CONFIG names a file that
715
+ // does not exist yet.
716
+ const locations = configLocations(target.root, target.env, target.home);
717
+ return target.layer === 'user' ? locations.user : locations.project;
718
+ }
719
+ // ── Dotted paths ────────────────────────────────────────────────────────────
720
+ /** Read a dotted path: `"runners.order"`, `"allowExec"`. `undefined` when absent. */
561
721
  export function getConfigValue(config, key) {
562
722
  let cursor = config;
563
723
  for (const segment of key.split('.')) {
564
- if (!isPlainObject(cursor))
724
+ if (!isPlainObject(cursor) || !Object.hasOwn(cursor, segment))
565
725
  return undefined;
566
726
  cursor = cursor[segment];
567
727
  }
@@ -572,24 +732,23 @@ export function getConfigValue(config, key) {
572
732
  * Missing intermediate objects are created, so `set` works on an empty file.
573
733
  *
574
734
  * Throws {@link ConfigError} for an unknown key, a value of the wrong type, or
575
- * an existing intermediate value that is not an object, rather than writing a
576
- * file that will fail to load. Given a raw record, it returns a raw record with
577
- * its unknown keys untouched.
735
+ * an existing intermediate value that is not an object. Given a raw record, it
736
+ * returns a raw record with its unknown keys untouched.
578
737
  */
579
738
  export function setConfigValue(config, key, value) {
580
- if (!(key in FIELDS)) {
739
+ const node = schemaAt(key);
740
+ if (node === undefined)
581
741
  throw new ConfigError(`unknown setting: ${key}`, '');
582
- }
583
- const checked = coerceField(key, value, '');
742
+ const checked = check(node, value, key, '', []);
584
743
  const segments = key.split('.');
585
744
  const root = { ...config };
586
745
  let cursor = root;
587
746
  let walked = '';
588
747
  for (const segment of segments.slice(0, -1)) {
589
- walked = walked === '' ? segment : `${walked}.${segment}`;
748
+ walked = join(walked, segment);
590
749
  const existing = cursor[segment];
591
750
  // A container of the wrong type means the file is broken. Replacing it
592
- // would silently delete whatever the user meant by it.
751
+ // would delete whatever the user meant by it.
593
752
  if (existing !== undefined && !isPlainObject(existing)) {
594
753
  throw new ConfigError(`cannot set ${key}: ${walked} is ${describe(existing)}, not an object`, '');
595
754
  }
@@ -601,29 +760,25 @@ export function setConfigValue(config, key, value) {
601
760
  return root;
602
761
  }
603
762
  /**
604
- * Remove a dotted path, returning a new document. A container left empty by the
605
- * removal is removed too, so unsetting the last `runners.*` key does not leave
606
- * `"runners": {}` behind.
607
- *
608
- * Unlike `set`, any key may be unset, including one this version does not
609
- * know, so a stale setting can be removed.
763
+ * Remove a dotted path, returning a new document. A container left empty by
764
+ * the removal is removed too. Any key may be unset, including one this
765
+ * version does not know, so a stale setting can be removed.
610
766
  */
611
767
  export function unsetConfigValue(config, key) {
612
768
  const segments = key.split('.');
613
769
  const record = config;
614
770
  const head = segments[0];
615
- if (!(head in record))
771
+ if (!Object.hasOwn(record, head))
616
772
  return { ...record };
773
+ const out = { ...record };
617
774
  if (segments.length === 1) {
618
- const out = { ...record };
619
775
  delete out[head];
620
776
  return out;
621
777
  }
622
778
  const child = record[head];
623
779
  if (!isPlainObject(child))
624
- return { ...record };
780
+ return out;
625
781
  const pruned = unsetConfigValue(child, segments.slice(1).join('.'));
626
- const out = { ...record };
627
782
  if (Object.keys(pruned).length === 0)
628
783
  delete out[head];
629
784
  else
@@ -631,9 +786,8 @@ export function unsetConfigValue(config, key) {
631
786
  return out;
632
787
  }
633
788
  /**
634
- * Parse a value typed on a command line. It is parsed as JSON first, so
635
- * `true`, `3` and `["a","b"]` keep their types. A bare word that is not valid
636
- * JSON is kept as a string, so `moon` need not be typed as `"moon"`.
789
+ * Parse a value typed on a command line: JSON first, so `true` and
790
+ * `["a","b"]` keep their types, else the bare string.
637
791
  */
638
792
  export function parseConfigValue(raw) {
639
793
  try {
@@ -643,6 +797,11 @@ export function parseConfigValue(raw) {
643
797
  return raw;
644
798
  }
645
799
  }
800
+ /** The key a typed key names, or undefined when it names no setting. */
801
+ export function resolveConfigKey(key) {
802
+ return schemaAt(key) === undefined ? undefined : key;
803
+ }
804
+ // ── Uses of the config ──────────────────────────────────────────────────────
646
805
  /**
647
806
  * The {@link WayOptions} fields this configuration controls. Only keys the
648
807
  * config sets are present, so a caller spreads its own flags after it.
@@ -660,42 +819,33 @@ export function collectOptionsFromConfig(config) {
660
819
  options.excludePaths = [...config.excludePaths];
661
820
  return options;
662
821
  }
663
- /** `config.trust`, defaulted to the empty policy `@osdlc/trust-repo` expects. */
664
- export function trustPolicyFromConfig(config) {
665
- return { paths: config.trust?.paths ?? [], owners: config.trust?.owners ?? [] };
666
- }
667
822
  /**
668
- * Expand a `trust.paths` entry's leading `~` against `home`, then resolve
669
- * symlinks in the pattern's static prefix (the part before the first glob
670
- * character) with `resolveTrustRoot`.
671
- *
672
- * This is the `expandPath` that `policyExecGate` and `policyDecision` take.
673
- * Without it, a pattern written as a person typed it (`/tmp/…`, which on macOS
674
- * is really `/private/tmp/…`) would never match the resolved root that
675
- * `policyDecision` compares it with.
823
+ * `config.trust` as the policy `@osdlc/trust-repo` expects: the top-level
824
+ * rules, and `trust.tools` as its per-scope rules.
676
825
  */
677
- export async function expandTrustPath(raw, home) {
678
- const abs = resolve(expandTilde(raw, home));
679
- const globAt = abs.search(/[*?]/);
680
- if (globAt === -1)
681
- return resolveTrustRoot(abs);
682
- const slash = abs.lastIndexOf('/', globAt);
683
- const prefix = await resolveTrustRoot(slash <= 0 ? '/' : abs.slice(0, slash));
684
- return prefix + abs.slice(slash);
826
+ export function trustPolicyFromConfig(config) {
827
+ const tools = config.trust?.tools ?? {};
828
+ const scopes = {};
829
+ for (const [id, rules] of Object.entries(tools)) {
830
+ scopes[id] = { paths: rules.paths ?? [], owners: rules.owners ?? [] };
831
+ }
832
+ return {
833
+ paths: config.trust?.paths ?? [],
834
+ owners: config.trust?.owners ?? [],
835
+ ...(Object.keys(scopes).length > 0 ? { scopes } : {}),
836
+ };
685
837
  }
686
838
  /**
687
- * The options every `@osdlc/trust-repo` gate call takes: {@link expandTrustPath}
688
- * against `home`, and the {@link originOwner} lookup that `trust.owners` needs.
689
- * Built in one place, so a call site cannot leave out `ownerOf` and silently
690
- * stop honouring `trust.owners`.
839
+ * The options every `@osdlc/trust-repo` gate call takes: `expandTrustPath`
840
+ * against `home`, and the git-backed `originOwner` lookup that `trust.owners`
841
+ * needs. Built in one place, so a call site cannot leave out `ownerOf`.
691
842
  */
692
843
  export function trustPolicyOptions(home) {
693
844
  return { expandPath: (raw) => expandTrustPath(raw, home), ownerOf: originOwner };
694
845
  }
695
846
  /**
696
847
  * Sort runner-keyed items for display: the ids named in `order` first, in that
697
- * order, then everything else alphabetically. Alphabetical rather than
698
- * registry order, so adding a tool does not reorder the list.
848
+ * order, then everything else alphabetically.
699
849
  */
700
850
  export function orderRunners(items, order) {
701
851
  const rank = new Map((order ?? []).map((id, index) => [id, index]));