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