noonsight 0.0.1 → 0.1.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 (114) hide show
  1. package/.claude-plugin/marketplace.json +19 -0
  2. package/.claude-plugin/plugin.json +14 -0
  3. package/README.md +271 -9
  4. package/dist/src/adapters/claude-code/classifier.js +138 -0
  5. package/dist/src/adapters/claude-code/code-edit.js +108 -0
  6. package/dist/src/adapters/claude-code/compat.js +31 -0
  7. package/dist/src/adapters/claude-code/definitions.js +347 -0
  8. package/dist/src/adapters/claude-code/fork.js +132 -0
  9. package/dist/src/adapters/claude-code/hook.js +652 -0
  10. package/dist/src/adapters/claude-code/install.js +186 -0
  11. package/dist/src/adapters/claude-code/launch.js +270 -0
  12. package/dist/src/adapters/claude-code/launcher.js +252 -0
  13. package/dist/src/adapters/claude-code/locations.js +115 -0
  14. package/dist/src/adapters/claude-code/managed.js +75 -0
  15. package/dist/src/adapters/claude-code/plugin-files.js +88 -0
  16. package/dist/src/adapters/claude-code/plugins.js +117 -0
  17. package/dist/src/adapters/claude-code/pointer.js +48 -0
  18. package/dist/src/adapters/claude-code/predict.js +271 -0
  19. package/dist/src/adapters/claude-code/routing.js +88 -0
  20. package/dist/src/adapters/claude-code/settings.js +189 -0
  21. package/dist/src/adapters/claude-code/subagents.js +666 -0
  22. package/dist/src/adapters/claude-code/triggers.js +88 -0
  23. package/dist/src/cli.js +157 -0
  24. package/dist/src/commands/accept.js +115 -0
  25. package/dist/src/commands/check.js +529 -0
  26. package/dist/src/commands/hook.js +73 -0
  27. package/dist/src/commands/init.js +29 -0
  28. package/dist/src/commands/install.js +370 -0
  29. package/dist/src/commands/models.js +213 -0
  30. package/dist/src/commands/receives.js +84 -0
  31. package/dist/src/commands/report.js +386 -0
  32. package/dist/src/commands/resolve.js +32 -0
  33. package/dist/src/commands/run.js +168 -0
  34. package/dist/src/commands/trust.js +70 -0
  35. package/dist/src/commands/usage.js +10 -0
  36. package/dist/src/commands/watch.js +154 -0
  37. package/dist/src/config/create.js +51 -0
  38. package/dist/src/config/json-schema.js +207 -0
  39. package/dist/src/config/load.js +758 -0
  40. package/dist/src/config/paths.js +42 -0
  41. package/dist/src/config/preset-changes.js +190 -0
  42. package/dist/src/config/project.js +354 -0
  43. package/dist/src/config/rewrite.js +112 -0
  44. package/dist/src/core/backtracking.js +330 -0
  45. package/dist/src/core/classify.js +66 -0
  46. package/dist/src/core/normalize.js +24 -0
  47. package/dist/src/core/overlap.js +39 -0
  48. package/dist/src/core/regex-sample.js +278 -0
  49. package/dist/src/core/resolve.js +201 -0
  50. package/dist/src/core/route.js +93 -0
  51. package/dist/src/core/scope.js +77 -0
  52. package/dist/src/core/triggers.js +30 -0
  53. package/dist/src/core/types.js +74 -0
  54. package/dist/src/state/agents.js +200 -0
  55. package/dist/src/state/claims.js +80 -0
  56. package/dist/src/state/files.js +84 -0
  57. package/dist/src/state/installs.js +29 -0
  58. package/dist/src/state/log.js +90 -0
  59. package/dist/src/state/node.js +35 -0
  60. package/dist/src/state/sessions.js +109 -0
  61. package/dist/src/state/triggers.js +57 -0
  62. package/dist/src/version.js +24 -0
  63. package/dist/src/watch/service.js +172 -0
  64. package/dist/src/watch/watcher.js +130 -0
  65. package/dist/src/wording.js +11 -0
  66. package/hooks/hooks.json +118 -0
  67. package/package.json +57 -7
  68. package/presets/claude/SOURCES.md +485 -0
  69. package/presets/claude/preset.json +432 -0
  70. package/presets/claude/rules/fable-5-2/code-ownership.md +1 -0
  71. package/presets/claude/rules/fable-5-2/finish-work.md +1 -0
  72. package/presets/claude/rules/fable-5-2/low-context-report.md +1 -0
  73. package/presets/claude/rules/fable-5-2/progress-updates.md +1 -0
  74. package/presets/claude/rules/haiku-5-5/carry-through.md +1 -0
  75. package/presets/claude/rules/haiku-5-5/search-recent-facts.md +1 -0
  76. package/presets/claude/rules/haiku-5-5/verify-changes.md +1 -0
  77. package/presets/claude/rules/opus-5-5/explore-before-acting.md +1 -0
  78. package/presets/claude/rules/opus-5-5/progress-updates.md +1 -0
  79. package/presets/claude/rules/opus-5-5/unattended-run.md +1 -0
  80. package/presets/claude/rules/sonnet-5-5/carry-through.md +1 -0
  81. package/presets/claude/rules/sonnet-5-5/check-current-facts.md +1 -0
  82. package/presets/claude/rules/sonnet-5-5/ideas-first.md +1 -0
  83. package/presets/claude/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  84. package/presets/claude/rules/sonnet-5-5/stay-in-scope.md +1 -0
  85. package/presets/claude/rules/sonnet-5-5/verify-changes.md +1 -0
  86. package/presets/claude/versions/1.3.0/preset.json +432 -0
  87. package/presets/claude/versions/1.3.0/rules/fable-5-2/code-ownership.md +1 -0
  88. package/presets/claude/versions/1.3.0/rules/fable-5-2/finish-work.md +1 -0
  89. package/presets/claude/versions/1.3.0/rules/fable-5-2/low-context-report.md +1 -0
  90. package/presets/claude/versions/1.3.0/rules/fable-5-2/progress-updates.md +1 -0
  91. package/presets/claude/versions/1.3.0/rules/haiku-5-5/carry-through.md +1 -0
  92. package/presets/claude/versions/1.3.0/rules/haiku-5-5/search-recent-facts.md +1 -0
  93. package/presets/claude/versions/1.3.0/rules/haiku-5-5/verify-changes.md +1 -0
  94. package/presets/claude/versions/1.3.0/rules/opus-5-5/explore-before-acting.md +1 -0
  95. package/presets/claude/versions/1.3.0/rules/opus-5-5/progress-updates.md +1 -0
  96. package/presets/claude/versions/1.3.0/rules/opus-5-5/unattended-run.md +1 -0
  97. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/carry-through.md +1 -0
  98. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/check-current-facts.md +1 -0
  99. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/ideas-first.md +1 -0
  100. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  101. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/stay-in-scope.md +1 -0
  102. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/verify-changes.md +1 -0
  103. package/schema/noonsight-project.schema.json +394 -0
  104. package/schema/noonsight.schema.json +425 -0
  105. package/schema/preset.schema.json +194 -0
  106. package/scripts/noonsight +68 -0
  107. package/skills/accept/SKILL.md +11 -0
  108. package/skills/check/SKILL.md +11 -0
  109. package/skills/models/SKILL.md +11 -0
  110. package/skills/report/SKILL.md +11 -0
  111. package/skills/resolve/SKILL.md +12 -0
  112. package/skills/setup/SKILL.md +15 -0
  113. package/skills/trust/SKILL.md +12 -0
  114. package/skills/untrust/SKILL.md +12 -0
@@ -0,0 +1,758 @@
1
+ // Reads the configuration, the preset and every rule file, checks all of it, and builds the value
2
+ // the core resolves against. A configuration with any problem is refused whole and no partial
3
+ // configuration is ever applied. Problems are reported in passes: schema problems first, then
4
+ // preset problems, then every remaining problem together.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { backtrackingRisk } from '../core/backtracking.js';
8
+ import { NO_SCOPE_ANSWER } from '../core/classify.js';
9
+ import { normalizeModel } from '../core/normalize.js';
10
+ import { deliveryText, envelope, selectRules } from '../core/resolve.js';
11
+ import { ANY_SCOPE, DEFAULT_CLASSIFIER_SETTINGS, DEFAULT_ROUTING_SETTINGS, DEFAULT_SESSION_SETTINGS, DEFAULT_SUBAGENT_SETTINGS, DELIVERY_TEXT_LIMIT, MATCHER_FLAGS, ALL_PLACES, PLACE_ALIASES, PLACES, placeName, ROUTE_ALIASES, ROUTE_TARGETS, RULES_TEXT_LIMIT, SWITCH_NOTE_RESERVE, TRIGGERS, } from '../core/types.js';
12
+ import { assertSupported, validateSchema } from './json-schema.js';
13
+ import { presetsDir as defaultPresetsDir, SCHEMA_DIR } from './paths.js';
14
+ import { DEFAULT_PROJECT_ALLOW, mergeProject, projectRules } from './project.js';
15
+ export class ConfigError extends Error {
16
+ file;
17
+ problems;
18
+ constructor(file, problems) {
19
+ super(`configuration refused (${file}):\n${problems.map((p) => ` - ${p}`).join('\n')}`);
20
+ this.file = file;
21
+ this.problems = problems;
22
+ this.name = 'ConfigError';
23
+ }
24
+ }
25
+ /** The preset a configuration draws from when it names none. */
26
+ export const DEFAULT_PRESET = 'claude';
27
+ /** What a configuration does on a preset update when it names no policy. */
28
+ export const DEFAULT_PRESET_CHANGE_POLICY = 'warn';
29
+ /** Where a preset keeps the earlier versions the package still ships, inside its own directory. */
30
+ export const PRESET_VERSIONS_DIR = 'versions';
31
+ /** Read and check one installed preset on its own; a missing or failing preset throws a ConfigError. */
32
+ export function readPreset(name, options = {}, env = process.env) {
33
+ const dir = options.presetsDir ?? defaultPresetsDir(env);
34
+ const problems = [];
35
+ const preset = loadPreset(name, path.join(dir, name), null, true, problems);
36
+ if (preset === null || problems.length)
37
+ throw new ConfigError(path.join(dir, name, 'preset.json'), problems);
38
+ return preset;
39
+ }
40
+ /**
41
+ * Read and check one version of a preset: the installed preset when it is that version, else the
42
+ * copy of that version the package keeps. Returns null when the package ships neither; a copy that
43
+ * fails its checks throws a ConfigError.
44
+ */
45
+ export function readPresetVersion(name, version, options = {}, env = process.env) {
46
+ const dir = options.presetsDir ?? defaultPresetsDir(env);
47
+ const installed = readPreset(name, options, env);
48
+ if (installed.version === version)
49
+ return installed;
50
+ const problems = [];
51
+ const copy = loadPreset(name, versionDir(dir, name, version), version, false, problems);
52
+ if (problems.length)
53
+ throw new ConfigError(path.join(versionDir(dir, name, version), 'preset.json'), problems);
54
+ return copy;
55
+ }
56
+ /** The directory of the copy of one earlier version of a preset. */
57
+ function versionDir(presetsDir, name, version) {
58
+ return path.join(presetsDir, name, PRESET_VERSIONS_DIR, version);
59
+ }
60
+ export function loadConfig(file, options = {}, env = process.env) {
61
+ return loadConfigDetails(file, options, env).config;
62
+ }
63
+ /**
64
+ * As loadConfig, and also returns the preset and each model as the file declares it. With a project
65
+ * file, the project is laid over the configuration when the configuration's "projects.allow" and this
66
+ * account's trust let it; a project with any problem is left out, and the configuration applies alone.
67
+ * Only a problem of the configuration itself throws.
68
+ */
69
+ export function loadConfigDetails(file, options = {}, env = process.env) {
70
+ const configFile = path.resolve(file);
71
+ const problems = [];
72
+ const raw = options.content !== undefined
73
+ ? parseJson(options.content, problems)
74
+ : readJson(configFile, problems, 'no configuration file here; create one, or point NOONSIGHT_CONFIG at one');
75
+ if (raw !== undefined)
76
+ problems.push(...validateSchema(schema('noonsight.schema.json'), raw));
77
+ if (problems.length)
78
+ throw new ConfigError(configFile, problems);
79
+ const machine = raw;
80
+ const project = options.project ?? null;
81
+ // The machine's configuration alone: it must load whatever the project, and its preset names the
82
+ // rules a project's entries may name by an id they had before a rename.
83
+ const own = build(machine, configFile, options, env, null);
84
+ if (project === null)
85
+ return { ...own, project: null };
86
+ const allow = machine.projects?.allow ?? DEFAULT_PROJECT_ALLOW;
87
+ const alone = (status, why = [], read = null) => ({
88
+ ...own,
89
+ project: { dir: project.dir, file: project.file, allow, status, problems: why, notes: [], rules: [], raw: read },
90
+ });
91
+ if (allow === 'none')
92
+ return alone('ignored');
93
+ if (project.trusted === null)
94
+ return alone('untrusted');
95
+ if (project.trusted === false)
96
+ return alone('declined');
97
+ const unread = [];
98
+ const read = readJson(project.file, unread, 'the project file is gone');
99
+ if (read !== undefined)
100
+ unread.push(...validateSchema(schema('noonsight-project.schema.json'), read));
101
+ if (unread.length)
102
+ return alone('refused', unread);
103
+ const projectRaw = read;
104
+ const renamed = new Map([...(own.preset?.models ?? [])].map(([model, rules]) => [model, new Map(rules.flatMap((r) => r.renamedFrom.map((old) => [old, r.id])))]));
105
+ // Paths in the project file are relative to the file itself, as in the configuration.
106
+ const merged = mergeProject(machine, projectRaw, allow, path.dirname(project.file), project.dir, (model, id) => renamed.get(model)?.get(id) ?? id);
107
+ if (merged.problems.length)
108
+ return alone('refused', merged.problems, projectRaw);
109
+ try {
110
+ // The merged configuration is checked against the configuration's schema too: a project entry
111
+ // merged into the machine's can make a combination neither file has alone.
112
+ const combined = validateSchema(schema('noonsight.schema.json'), merged.raw);
113
+ if (combined.length)
114
+ throw new ConfigError(project.file, combined);
115
+ const built = build(merged.raw, configFile, options, env, merged.origins);
116
+ return {
117
+ ...built,
118
+ project: { dir: project.dir, file: project.file, allow, status: 'applied', problems: [], notes: merged.notes, rules: projectRules(built.config), raw: projectRaw },
119
+ };
120
+ }
121
+ catch (e) {
122
+ if (!(e instanceof ConfigError))
123
+ throw e;
124
+ // A problem the configuration has alone throws from here; one the project brings leaves the project out.
125
+ return alone('refused', e.problems, projectRaw);
126
+ }
127
+ }
128
+ /** Check a configuration that matches its schema, and build what the core resolves against. */
129
+ function build(cfg, configFile, options, env, origins) {
130
+ const problems = [];
131
+ const report = (at, message) => {
132
+ problems.push(`${at}: ${message}`);
133
+ };
134
+ const refuse = () => {
135
+ throw new ConfigError(configFile, problems);
136
+ };
137
+ const origin = (u) => origins?.get(u);
138
+ const models = cfg.models ?? {};
139
+ // The preset: always read when present, required when named or when a model uses it.
140
+ const presetName = cfg.preset ?? DEFAULT_PRESET;
141
+ const presetNeeded = cfg.preset !== undefined || Object.values(models).some((m) => m.use === 'preset');
142
+ const presetsRoot = options.presetsDir ?? defaultPresetsDir(env);
143
+ const installed = loadPreset(presetName, path.join(presetsRoot, presetName), null, presetNeeded, problems);
144
+ if (problems.length)
145
+ refuse();
146
+ // Under "hold", the rules, scopes and routing table come from the accepted version, as the package keeps it.
147
+ const accepted = cfg.preset_version ?? null;
148
+ const onChange = cfg.on_preset_change ?? DEFAULT_PRESET_CHANGE_POLICY;
149
+ let preset = installed;
150
+ if (onChange === 'hold') {
151
+ if (accepted === null)
152
+ report('/on_preset_change', `"hold" keeps the rules of the preset version in "preset_version", and the configuration records none; ` +
153
+ `run \`noonsight accept\` to record ${installed ? `${installed.version}, the installed version` : 'the installed version'}`);
154
+ else if (installed !== null && installed.version !== accepted) {
155
+ preset = loadPreset(presetName, versionDir(presetsRoot, presetName, accepted), accepted, false, problems);
156
+ if (preset === null && !problems.length)
157
+ report('/preset_version', `preset "${presetName}" ${accepted} is held ("on_preset_change": "hold"), but the installed package ships ${installed.version} and keeps no copy of ${accepted}; ` +
158
+ `run \`noonsight accept\` to take ${installed.version}, or install a noonsight version that ships ${accepted}`);
159
+ }
160
+ }
161
+ if (problems.length)
162
+ refuse();
163
+ // Under "warn", an enable, disable or replaces entry can name a rule the accepted version had and the
164
+ // installed one no longer has: the update dropped it, so the entry is left out and reported, not refused.
165
+ let former;
166
+ const formerRules = (model) => {
167
+ if (former === undefined) {
168
+ former = null;
169
+ if (accepted !== null && installed !== null && preset === installed && accepted !== installed.version) {
170
+ const own = [];
171
+ former = loadPreset(presetName, versionDir(presetsRoot, presetName, accepted), accepted, false, own);
172
+ if (own.length)
173
+ former = null;
174
+ }
175
+ }
176
+ return former?.models.get(model) ?? [];
177
+ };
178
+ const scopes = mergeScopes(preset?.scopes ?? new Map(), cfg.scopes ?? {}, report);
179
+ const configDir = path.dirname(configFile);
180
+ const exact = new Map();
181
+ const wildcards = [];
182
+ const allModels = loadAllModels(cfg.all_models?.add ?? [], configDir, scopes, report, origin);
183
+ for (const [key, entry] of Object.entries(models)) {
184
+ const at = `/models/${key}`;
185
+ // Lookups use the bare identifier, so a key in any other form would never match.
186
+ const normalized = normalizeModel(key);
187
+ if (normalized !== key) {
188
+ report(at, `write the bare model identifier "${normalized}"; this key would never match`);
189
+ continue;
190
+ }
191
+ if (/[*?]/.test(key)) {
192
+ wildcards.push(compileWildcard(key));
193
+ continue;
194
+ }
195
+ if (entry.use === 'none') {
196
+ exact.set(key, { use: 'none' });
197
+ continue;
198
+ }
199
+ // The preset's part of the rules: a rule that is on, or the index in "add" of the rule that replaces it.
200
+ const presetPart = [];
201
+ // The preset rule each rule of "add" that names one in "replaces" takes its defaults from: the rule
202
+ // it replaces, or, when the update dropped that rule, the rule as the accepted version had it.
203
+ const replaced = new Map();
204
+ const presetIds = new Set(preset?.models.get(key)?.map((r) => r.id) ?? []);
205
+ if (entry.use === 'preset') {
206
+ const presetRules = preset?.models.get(key);
207
+ if (preset && !presetRules) {
208
+ report(at, `preset "${presetName}" has no rules for ${key}; declare it with "use": "custom" or "use": "none"`);
209
+ }
210
+ else if (presetRules) {
211
+ const ids = new Set(presetRules.map((r) => r.id));
212
+ // An entry that names a rule by an id it had before a rename still applies to the rule.
213
+ const renamed = new Map(presetRules.flatMap((r) => r.renamedFrom.map((old) => [old, r.id])));
214
+ const pick = (list) => {
215
+ const picked = new Map();
216
+ for (const id of entry[list] ?? []) {
217
+ const current = ids.has(id) ? id : renamed.get(id);
218
+ if (current !== undefined)
219
+ picked.set(current, id);
220
+ else if (!formerRules(key).some((r) => r.id === id))
221
+ report(`${at}/${list}`, `preset "${presetName}" has no rule "${id}" for ${key}`);
222
+ }
223
+ return picked;
224
+ };
225
+ const enable = pick('enable');
226
+ const disable = pick('disable');
227
+ for (const [id, written] of enable) {
228
+ const other = disable.get(id);
229
+ if (other !== undefined)
230
+ report(at, `rule "${id}" is both enabled and disabled` + (written !== id || other !== id ? ` (as "${written}" and "${other}")` : ''));
231
+ }
232
+ const replacing = new Map();
233
+ (entry.add ?? []).forEach((u, i) => {
234
+ if (u.replaces === undefined)
235
+ return;
236
+ const replacesAt = `${origin(u)?.at ?? `${at}/add/${i}`}/replaces`;
237
+ const current = ids.has(u.replaces) ? u.replaces : renamed.get(u.replaces);
238
+ if (current === undefined) {
239
+ const gone = formerRules(key).find((r) => r.id === u.replaces);
240
+ if (gone !== undefined)
241
+ replaced.set(i, gone);
242
+ else
243
+ report(replacesAt, `preset "${presetName}" has no rule "${u.replaces}" for ${key}`);
244
+ return;
245
+ }
246
+ const named = current !== u.replaces ? ` (as "${u.replaces}")` : '';
247
+ const other = replacing.get(current);
248
+ if (other !== undefined) {
249
+ report(replacesAt, `rule "${current}"${named} is already replaced by "${entry.add?.[other]?.id}"; a preset rule is replaced by one rule at most`);
250
+ return;
251
+ }
252
+ if (enable.has(current))
253
+ report(replacesAt, `rule "${current}"${named} is both replaced and enabled; remove it from "enable" to deliver "${u.id}" in its place`);
254
+ if (disable.has(current))
255
+ report(replacesAt, `rule "${current}"${named} is both replaced and disabled; "replaces" already turns it off, so remove it from "disable"`);
256
+ replacing.set(current, i);
257
+ replaced.set(i, presetRules.find((r) => r.id === current));
258
+ });
259
+ for (const r of presetRules) {
260
+ const by = replacing.get(r.id);
261
+ const on = (r.enabled || enable.has(r.id)) && !disable.has(r.id);
262
+ if (by !== undefined)
263
+ presetPart.push(by);
264
+ else if (on)
265
+ presetPart.push({ id: r.id, origin: r.origin, scopes: r.scopes, where: r.where, triggers: r.triggers, text: r.text });
266
+ }
267
+ }
268
+ }
269
+ // The rules of every model come after the preset's and before the model's own.
270
+ const taken = new Set(presetIds);
271
+ allModels.forEach((r, i) => {
272
+ if (presetIds.has(r.id))
273
+ report(`/all_models/add/${i}/id`, `rule id "${r.id}" is already a preset rule for ${key}; every model declared with "use": "preset" or "use": "custom" receives the rules of "all_models"`);
274
+ taken.add(r.id);
275
+ });
276
+ // A rule that replaces a preset rule takes the scopes, places and triggers it does not give from that rule.
277
+ const own = (entry.add ?? []).map((u, i) => {
278
+ const ruleAt = origin(u)?.at ?? `${at}/add/${i}`;
279
+ if (allModels.some((r) => r.id === u.id))
280
+ report(`${ruleAt}/id`, `rule id "${u.id}" is already used for ${key} by "all_models"`);
281
+ else if (taken.has(u.id))
282
+ report(`${ruleAt}/id`, `rule id "${u.id}" is already used for ${key}`);
283
+ taken.add(u.id);
284
+ const base = replaced.get(i);
285
+ const ruleScopes = u.scopes ?? base?.scopes ?? [ANY_SCOPE];
286
+ const where = placesOf(u.where, `${ruleAt}/where`, report) ?? base?.where ?? [...PLACES];
287
+ const triggers = u.triggers ?? base?.triggers ?? [];
288
+ checkScopes(ruleScopes, scopes, `${ruleAt}/scopes`, report);
289
+ const triggersFrom = u.triggers === undefined && base !== undefined ? base.id : undefined;
290
+ checkTriggers(ruleScopes, where, triggers, `${ruleAt}/triggers`, report, triggersFrom);
291
+ const text = readRuleText(path.resolve(configDir, u.file), `${ruleAt}/file`, report);
292
+ if (text === undefined)
293
+ return undefined;
294
+ const inPlace = base !== undefined && presetPart.includes(i);
295
+ return {
296
+ id: u.id,
297
+ origin: 'user',
298
+ scopes: ruleScopes,
299
+ where,
300
+ triggers,
301
+ text,
302
+ ...(inPlace ? { replaces: base.id } : {}),
303
+ ...(origin(u) ? { project: true } : {}),
304
+ };
305
+ });
306
+ // A rule that replaces a preset rule is delivered in its place; the others follow the rules of "all_models".
307
+ const rules = [
308
+ ...presetPart.flatMap((r) => (typeof r === 'number' ? (own[r] ?? []) : [r])),
309
+ ...allModels,
310
+ ...own.filter((r, i) => r !== undefined && !presetPart.includes(i)),
311
+ ];
312
+ checkDeliverySize(key, rules, scopes, at, report);
313
+ exact.set(key, { use: 'rules', rules });
314
+ }
315
+ if (problems.length)
316
+ refuse();
317
+ wildcards.sort((a, b) => b.literal - a.literal || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
318
+ const sub = cfg.subagents ?? {};
319
+ const subagents = {
320
+ delivery: sub.delivery ?? DEFAULT_SUBAGENT_SETTINGS.delivery,
321
+ permission: sub.permission ?? DEFAULT_SUBAGENT_SETTINGS.permission,
322
+ onMismatch: sub.on_mismatch ?? DEFAULT_SUBAGENT_SETTINGS.onMismatch,
323
+ };
324
+ const session = {
325
+ unattendedWhenEnv: cfg.session?.unattended_when_env ?? DEFAULT_SESSION_SETTINGS.unattendedWhenEnv,
326
+ headlessIsUnattended: cfg.session?.headless_is_unattended ?? DEFAULT_SESSION_SETTINGS.headlessIsUnattended,
327
+ };
328
+ const routing = loadRouting(cfg.routing ?? {}, preset, scopes, exact, report);
329
+ const c = cfg.classifier ?? {};
330
+ const classifier = {
331
+ mode: c.mode ?? DEFAULT_CLASSIFIER_SETTINGS.mode,
332
+ model: c.model ?? DEFAULT_CLASSIFIER_SETTINGS.model,
333
+ effort: c.effort ?? DEFAULT_CLASSIFIER_SETTINGS.effort,
334
+ timeoutMs: c.timeout_ms ?? DEFAULT_CLASSIFIER_SETTINGS.timeoutMs,
335
+ };
336
+ if (classifier.mode !== 'off' && scopes.has(NO_SCOPE_ANSWER))
337
+ report(`/scopes/${NO_SCOPE_ANSWER}`, `the classifier answers "${NO_SCOPE_ANSWER}" for a task that fits no scope, so no scope can have that name while classifier.mode is on`);
338
+ if (problems.length)
339
+ refuse();
340
+ const declared = new Map(Object.entries(models).map(([key, entry]) => [
341
+ key,
342
+ {
343
+ use: entry.use,
344
+ wildcard: /[*?]/.test(key),
345
+ enable: entry.enable ?? [],
346
+ disable: entry.disable ?? [],
347
+ add: (entry.add ?? []).map((u) => ({
348
+ ...describeRule(u, origin(u)),
349
+ ...(u.replaces !== undefined
350
+ ? {
351
+ replaces: {
352
+ id: u.replaces,
353
+ inherits: [
354
+ ...(u.scopes === undefined ? ['scopes'] : []),
355
+ ...(u.where === undefined ? ['places'] : []),
356
+ ...(u.triggers === undefined ? ['triggers'] : []),
357
+ ],
358
+ },
359
+ }
360
+ : {}),
361
+ })),
362
+ },
363
+ ]));
364
+ return {
365
+ config: { exact, wildcards, onUndeclared: cfg.on_undeclared ?? 'warn', allModels, scopes, session, subagents, routing, classifier },
366
+ preset,
367
+ presetVersions: { name: presetName, accepted, onChange, installed },
368
+ declared,
369
+ allModels: (cfg.all_models?.add ?? []).map((u) => describeRule(u, origin(u))),
370
+ };
371
+ }
372
+ /** A user rule as commands list it: its file as the configuration that writes it writes it. */
373
+ function describeRule(u, origin) {
374
+ return origin ? { id: u.id, file: origin.file, project: true } : { id: u.id, file: u.file };
375
+ }
376
+ /**
377
+ * The rules of the "all_models" block, read and checked once, in the same way as a model's own
378
+ * "add". The id of each rule must also be new for every model that receives it; the loader checks
379
+ * that where it assembles each model's rules.
380
+ */
381
+ function loadAllModels(raw, configDir, scopes, report, origin) {
382
+ const ids = new Set();
383
+ const rules = [];
384
+ raw.forEach((u, i) => {
385
+ const at = origin(u)?.at ?? `/all_models/add/${i}`;
386
+ if (ids.has(u.id))
387
+ report(`${at}/id`, `rule id "${u.id}" is used more than once in "all_models"`);
388
+ ids.add(u.id);
389
+ const ruleScopes = u.scopes ?? [ANY_SCOPE];
390
+ const where = placesOf(u.where, `${at}/where`, report) ?? [...PLACES];
391
+ const triggers = u.triggers ?? [];
392
+ checkScopes(ruleScopes, scopes, `${at}/scopes`, report);
393
+ checkTriggers(ruleScopes, where, triggers, `${at}/triggers`, report);
394
+ const text = readRuleText(path.resolve(configDir, u.file), `${at}/file`, report);
395
+ if (text !== undefined)
396
+ rules.push({ id: u.id, origin: 'user', scopes: ruleScopes, where, triggers, text, allModels: true, ...(origin(u) ? { project: true } : {}) });
397
+ });
398
+ return rules;
399
+ }
400
+ /**
401
+ * Read and check the preset in one directory: the installed preset (version null), or the copy of
402
+ * one earlier version, which must say it is that version. A missing preset is a problem only when
403
+ * needed.
404
+ */
405
+ function loadPreset(name, presetDir, version, needed, problems) {
406
+ const file = path.join(presetDir, 'preset.json');
407
+ if (!fs.existsSync(file)) {
408
+ if (needed)
409
+ problems.push(`/preset: preset "${name}" is not installed (looked for ${file})`);
410
+ return null;
411
+ }
412
+ const own = [];
413
+ const report = (at, message) => {
414
+ own.push(`${at}: ${message}`);
415
+ };
416
+ const raw = readJson(file, own, 'cannot read the preset');
417
+ if (raw !== undefined)
418
+ own.push(...validateSchema(schema('preset.schema.json'), raw));
419
+ if (own.length) {
420
+ problems.push(...own.map((p) => `preset ${file}: ${p}`));
421
+ return null;
422
+ }
423
+ const p = raw;
424
+ if (p.id !== name)
425
+ report('/id', `is "${p.id}", but the preset is installed as "${name}"`);
426
+ if (version !== null && p.version !== version)
427
+ report('/version', `is "${p.version}", but the copy is kept as version ${version}`);
428
+ const scopes = new Map(Object.entries(p.scopes ?? {}).map(([name, raw]) => [name, toScope(name, raw, `/scopes/${name}`, report)]));
429
+ const scopeSources = new Map(Object.entries(p.scopes ?? {}).flatMap(([name, raw]) => (raw.source ? [[name, raw.source]] : [])));
430
+ const routing = new Map();
431
+ for (const [scope, entry] of Object.entries(p.routing?.table ?? {})) {
432
+ const at = `/routing/table/${scope}`;
433
+ if (!scopes.has(scope))
434
+ report(at, `scope "${scope}" is not one of the preset's scopes`);
435
+ routing.set(scope, { row: toRow(entry.route, `${at}/route`, report), basis: entry.basis, sources: entry.sources });
436
+ }
437
+ const models = new Map();
438
+ for (const [key, entry] of Object.entries(p.models)) {
439
+ const at = `/models/${key}`;
440
+ if (normalizeModel(key) !== key)
441
+ report(at, `write the bare model identifier "${normalizeModel(key)}"`);
442
+ const ids = new Set();
443
+ const rules = [];
444
+ entry.rules.forEach((r, i) => {
445
+ const ruleAt = `${at}/rules/${i}`;
446
+ if (ids.has(r.id))
447
+ report(`${ruleAt}/id`, `rule id "${r.id}" is used more than once for ${key}`);
448
+ ids.add(r.id);
449
+ checkScopes(r.scopes, scopes, `${ruleAt}/scopes`, report);
450
+ const where = placesOf(r.where, `${ruleAt}/where`, report) ?? [...PLACES];
451
+ checkTriggers(r.scopes, where, r.triggers ?? [], `${ruleAt}/triggers`, report);
452
+ const text = readRuleText(path.resolve(presetDir, r.file), `${ruleAt}/file`, report);
453
+ if (text !== undefined)
454
+ rules.push({
455
+ id: r.id,
456
+ origin: 'preset',
457
+ scopes: r.scopes,
458
+ where,
459
+ triggers: r.triggers ?? [],
460
+ text,
461
+ enabled: r.enabled ?? true,
462
+ renamedFrom: r.renamed_from ?? [],
463
+ file: r.file,
464
+ source: r.source,
465
+ effect: r.effect,
466
+ cost: r.cost,
467
+ });
468
+ });
469
+ checkRenames(key, entry.rules, at, report);
470
+ // A user can turn on any preset rule, so the preset must fit with every rule on, not only as it ships.
471
+ if (rules.length === entry.rules.length)
472
+ checkPresetSize(key, rules, scopes, at, report);
473
+ models.set(key, rules);
474
+ }
475
+ if (own.length) {
476
+ problems.push(...own.map((p) => `preset ${file}: ${p}`));
477
+ return null;
478
+ }
479
+ return { name, version: p.version, claudeCode: p.claude_code ?? null, scopes, scopeSources, routing, models };
480
+ }
481
+ /**
482
+ * A rule's earlier ids map an enable or disable entry, and an earlier version's rule, to the rule, so
483
+ * each earlier id names one rule and no rule the version has.
484
+ */
485
+ function checkRenames(model, rules, at, report) {
486
+ const current = new Set(rules.map((r) => r.id));
487
+ const owner = new Map();
488
+ rules.forEach((r, i) => (r.renamed_from ?? []).forEach((old, j) => {
489
+ const oldAt = `${at}/rules/${i}/renamed_from/${j}`;
490
+ if (current.has(old))
491
+ report(oldAt, `"${old}" is the id of a rule of ${model} in this version; renamed_from lists only ids the rule had in earlier versions`);
492
+ else if (owner.has(old))
493
+ report(oldAt, `"${old}" is already an earlier id of rule "${owner.get(old)}"`);
494
+ owner.set(old, r.id);
495
+ }));
496
+ }
497
+ /**
498
+ * The declared scopes: the preset's, in its order, then the user's new ones, in theirs. A user scope
499
+ * with a preset scope's name keeps that scope's place and replaces only the keys it gives.
500
+ */
501
+ function mergeScopes(preset, user, report) {
502
+ const scopes = new Map(preset);
503
+ for (const [name, raw] of Object.entries(user))
504
+ scopes.set(name, toScope(name, raw, `/scopes/${name}`, report, scopes.get(name)));
505
+ return scopes;
506
+ }
507
+ function toScope(name, raw, at, report, base) {
508
+ const description = raw.description ?? base?.description;
509
+ return {
510
+ name,
511
+ ...(description !== undefined ? { description } : {}),
512
+ match: raw.match !== undefined ? compileMatchers(name, raw.match, `${at}/match`, report) : (base?.match ?? []),
513
+ };
514
+ }
515
+ /** Plain task texts. A matcher that matches every one of them is a catch-all, such as `.`, `\b` or `\w`. */
516
+ const CATCH_ALL_PROBES = ['a', 'Z', '0', ' a ', 'A B', 'x_1 y'];
517
+ /**
518
+ * Matchers are JavaScript regular expressions, compiled case-insensitive and Unicode-aware. A matcher
519
+ * that matches every probe text in CATCH_ALL_PROBES is a catch-all, so it is refused. Passing the
520
+ * probes does not prove a matcher is not broad; it only catches the obvious catch-alls. A matcher with
521
+ * one of the shapes backtracking.ts recognizes is refused too, since the hook runs it over every
522
+ * subagent's task text before the subagent starts.
523
+ */
524
+ function compileMatchers(scope, sources, at, report) {
525
+ const out = [];
526
+ sources.forEach((source, i) => {
527
+ let regex;
528
+ try {
529
+ regex = new RegExp(source, MATCHER_FLAGS);
530
+ }
531
+ catch (e) {
532
+ report(`${at}/${i}`, `not a valid regular expression (${e.message})`);
533
+ return;
534
+ }
535
+ if (CATCH_ALL_PROBES.every((text) => regex.test(text))) {
536
+ const probes = CATCH_ALL_PROBES.map((text) => JSON.stringify(text)).join(', ');
537
+ report(`${at}/${i}`, `"${source}" matches each of the probe texts ${probes}, which are plain task texts used to detect catch-all matchers`);
538
+ return;
539
+ }
540
+ const risk = backtrackingRisk(source, MATCHER_FLAGS);
541
+ if (risk !== null) {
542
+ report(`${at}/${i}`, `scope "${scope}": "${source}" ${describeRisk(risk)}`);
543
+ return;
544
+ }
545
+ out.push({ source, regex });
546
+ });
547
+ return out;
548
+ }
549
+ function describeRisk(risk) {
550
+ // Quoted as the pattern itself is quoted: as the configuration writes it.
551
+ const [a = '', b = ''] = risk.parts.map((p) => `"${p}"`);
552
+ switch (risk.kind) {
553
+ case 'leading-any':
554
+ return (`starts with ${a}, an unbounded repeat of any character with no "^" and only parts that can match nothing before it, so matching retries it from every position of the task text; ` +
555
+ 'start with a word instead (such as "\\binvestigat"), or anchor it with "^"');
556
+ case 'nested':
557
+ return `has the unbounded quantifier ${b} inside the unbounded quantifier ${a}, a shape whose matching time can grow exponentially with the task text`;
558
+ case 'adjacent':
559
+ return `has the unbounded quantifiers ${a} and ${b} in a row, able to match the same characters with nothing required between them, a shape whose matching time can grow much faster than the task text`;
560
+ }
561
+ }
562
+ /**
563
+ * The routing settings: the user's keys over the defaults, and the preset's table with each row the
564
+ * user writes for the same scope replacing the preset's. Every scope in the table must be declared,
565
+ * and every model an option names must be an alias or a model declared under an exact key.
566
+ */
567
+ function loadRouting(raw, preset, scopes, exact, report) {
568
+ const table = new Map();
569
+ for (const [scope, entry] of preset?.routing ?? [])
570
+ table.set(scope, entry.row);
571
+ for (const [scope, rawRow] of Object.entries(raw.table ?? {})) {
572
+ const at = `/routing/table/${scope}`;
573
+ if (!scopes.has(scope))
574
+ report(at, `scope "${scope}" is not declared`);
575
+ checkRouteModels(rawRow, at, exact, report);
576
+ table.set(scope, toRow(rawRow, at, report));
577
+ }
578
+ let fallback = null;
579
+ if (raw.default !== undefined && raw.default !== 'inherit') {
580
+ checkRouteModels(raw.default, '/routing/default', exact, report);
581
+ fallback = toRow(raw.default, '/routing/default', report);
582
+ }
583
+ return {
584
+ enabled: raw.enabled ?? DEFAULT_ROUTING_SETTINGS.enabled,
585
+ targets: raw.targets ?? DEFAULT_ROUTING_SETTINGS.targets,
586
+ respectExplicit: raw.respect_explicit ?? DEFAULT_ROUTING_SETTINGS.respectExplicit,
587
+ yieldWhenEnv: raw.yield_when_env ?? DEFAULT_ROUTING_SETTINGS.yieldWhenEnv,
588
+ table,
589
+ default: fallback,
590
+ };
591
+ }
592
+ /** A row as the core reads it: a list written for every target becomes the same list for each. */
593
+ function toRow(raw, at, report) {
594
+ if (Array.isArray(raw))
595
+ return Object.fromEntries(ROUTE_TARGETS.map((t) => [t, raw]));
596
+ if (Object.keys(raw).length === 0)
597
+ report(at, `list the options for ${ROUTE_TARGETS.join(', ')} or both, or write the options as one list for every target`);
598
+ return raw;
599
+ }
600
+ function checkRouteModels(raw, at, exact, report) {
601
+ const lists = Array.isArray(raw)
602
+ ? [[at, raw]]
603
+ : ROUTE_TARGETS.flatMap((t) => (raw[t] !== undefined ? [[`${at}/${t}`, raw[t]]] : []));
604
+ for (const [listAt, options] of lists)
605
+ options.forEach((option, i) => {
606
+ if (ROUTE_ALIASES.includes(option.model) || exact.has(option.model))
607
+ return;
608
+ report(`${listAt}/${i}/model`, `"${option.model}" is neither a model alias (${ROUTE_ALIASES.join(', ')}) nor a model declared under "models" with its exact identifier`);
609
+ });
610
+ }
611
+ /**
612
+ * A rule's places as "where" writes them: each place by its name or an earlier one, such as
613
+ * "session" for "attended", or "all" alone for every place. Undefined when "where" is not given.
614
+ */
615
+ function placesOf(raw, at, report) {
616
+ if (raw === undefined)
617
+ return undefined;
618
+ if (raw.includes(ALL_PLACES)) {
619
+ if (raw.length > 1)
620
+ report(at, `"${ALL_PLACES}" already covers every place; list it alone`);
621
+ return [...PLACES];
622
+ }
623
+ const places = [];
624
+ for (const value of raw) {
625
+ const place = placeName(value);
626
+ if (place === null)
627
+ continue; // The schema already refused it.
628
+ if (!places.includes(place))
629
+ places.push(place);
630
+ else {
631
+ const earlier = Object.keys(PLACE_ALIASES).find((name) => PLACE_ALIASES[name] === place && raw.includes(name));
632
+ report(at, `names the place "${place}" twice${earlier === undefined ? '' : ` ("${earlier}" is its earlier name)`}`);
633
+ }
634
+ }
635
+ return places;
636
+ }
637
+ function checkScopes(ruleScopes, declared, at, report) {
638
+ if (ruleScopes.includes(ANY_SCOPE) && ruleScopes.length > 1)
639
+ report(at, `"${ANY_SCOPE}" already covers every scope; list it alone`);
640
+ for (const s of ruleScopes)
641
+ if (s !== ANY_SCOPE && !declared.has(s))
642
+ report(at, `scope "${s}" is not declared`);
643
+ }
644
+ /**
645
+ * A trigger delivers a rule to a session whose scope is not one of the rule's scopes, so it adds
646
+ * nothing to a rule for every scope, and it acts only in a session's places.
647
+ */
648
+ function checkTriggers(ruleScopes, where, triggers, at, report, inheritedFrom) {
649
+ if (triggers.length === 0)
650
+ return;
651
+ const from = inheritedFrom === undefined ? '' : ` (the rule takes its triggers from "${inheritedFrom}", which it replaces; give "triggers": [] to drop them)`;
652
+ if (ruleScopes.includes(ANY_SCOPE))
653
+ report(at, `the rule is for every scope ("${ANY_SCOPE}"), so it already reaches every session; a trigger adds nothing${from}`);
654
+ if (!where.some((p) => p !== 'subagent'))
655
+ report(at, `a trigger acts only in a session, but the rule is only for the place "subagent"; add "attended" or "unattended" to "where"${from}`);
656
+ }
657
+ /** The trigger sets a delivery can be made with: none, and every trigger revealed. */
658
+ const TRIGGER_SETS = [[], TRIGGERS];
659
+ /**
660
+ * The text limit applies to what is delivered, so every combination of scope, place and revealed
661
+ * triggers is checked. Part of Claude Code's limit is kept for the note sent along when the session's
662
+ * model changes.
663
+ */
664
+ function checkDeliverySize(model, rules, scopes, at, report, prefix = '') {
665
+ for (const scope of [null, ...[...scopes.keys()].sort()])
666
+ for (const place of PLACES)
667
+ for (const triggers of TRIGGER_SETS) {
668
+ const picked = selectRules(rules, scope, place, triggers);
669
+ // Without a trigger the rules are those checked without one.
670
+ if (picked.length === 0 || (triggers.length && picked.length === selectRules(rules, scope, place).length))
671
+ continue;
672
+ const size = deliveryText(model, picked, scope, triggers).text.length;
673
+ if (size > RULES_TEXT_LIMIT) {
674
+ const shared = picked.filter((r) => r.allModels).length;
675
+ report(at, `${prefix}the rules delivered for ${scope === null ? 'no scope' : `scope "${scope}"`} in place "${place}"` +
676
+ `${triggers.length ? ` once a session reveals ${triggers.join(', ')}` : ''} come to ${size} characters` +
677
+ `${shared ? ` (${shared} of the ${picked.length} rules are from "all_models", which every model declared with "use": "preset" or "use": "custom" receives)` : ''}; ${LIMIT_TEXT}`);
678
+ }
679
+ }
680
+ }
681
+ const LIMIT_TEXT = `the limit is ${RULES_TEXT_LIMIT} (Claude Code's ${DELIVERY_TEXT_LIMIT}, less ${SWITCH_NOTE_RESERVE} kept for the model-change note)`;
682
+ /**
683
+ * A preset rule must fit on its own, and the preset's rules for a model must fit together with every
684
+ * rule on, since the user decides which of them are on.
685
+ */
686
+ function checkPresetSize(model, rules, scopes, at, report) {
687
+ let alone = true;
688
+ rules.forEach((r, i) => {
689
+ // The envelope names the scope, so the rule is measured under each scope it can be delivered in.
690
+ const under = r.scopes.includes(ANY_SCOPE) ? [null, ...scopes.keys()] : r.scopes;
691
+ const size = Math.max(...under.map((scope) => envelope(model, scope, [r.id], r.text).length),
692
+ // Delivered by a trigger: under no scope, or under a scope the rule does not list.
693
+ ...(r.triggers.length
694
+ ? [null, ...[...scopes.keys()].filter((s) => !r.scopes.includes(s))].map((scope) => envelope(model, scope, [r.id], r.text, r.triggers).length)
695
+ : []));
696
+ if (size > RULES_TEXT_LIMIT) {
697
+ alone = false;
698
+ report(`${at}/rules/${i}/file`, `rule "${r.id}" comes to ${size} characters on its own, envelope included; ${LIMIT_TEXT}`);
699
+ }
700
+ });
701
+ if (alone)
702
+ checkDeliverySize(model, rules, scopes, at, report, 'with every rule on, ');
703
+ }
704
+ function readRuleText(file, at, report) {
705
+ let text;
706
+ try {
707
+ text = fs.readFileSync(file, 'utf8');
708
+ }
709
+ catch (e) {
710
+ report(at, `cannot read ${file} (${e.code ?? String(e)})`);
711
+ return undefined;
712
+ }
713
+ // Line endings are normalized so the same rule gives the same text and hash on every system.
714
+ const normalized = text.replace(/\r\n?/g, '\n').trim();
715
+ if (!normalized) {
716
+ report(at, `${file} is empty`);
717
+ return undefined;
718
+ }
719
+ return normalized;
720
+ }
721
+ function readJson(file, problems, missing) {
722
+ let text;
723
+ try {
724
+ text = fs.readFileSync(file, 'utf8');
725
+ }
726
+ catch (e) {
727
+ const code = e.code;
728
+ problems.push(code === 'ENOENT' ? missing : `cannot read the file (${code ?? String(e)})`);
729
+ return undefined;
730
+ }
731
+ return parseJson(text, problems);
732
+ }
733
+ function parseJson(text, problems) {
734
+ try {
735
+ return JSON.parse(text);
736
+ }
737
+ catch (e) {
738
+ problems.push(`not valid JSON: ${e.message}`);
739
+ return undefined;
740
+ }
741
+ }
742
+ function compileWildcard(key) {
743
+ const source = [...key]
744
+ .map((c) => (c === '*' ? '.*' : c === '?' ? '.' : c.replace(/[.+^${}()|[\]\\-]/g, '\\$&')))
745
+ .join('');
746
+ return { key, pattern: new RegExp(`^${source}$`), literal: key.replace(/[*?]/g, '').length };
747
+ }
748
+ const schemaCache = new Map();
749
+ function schema(name) {
750
+ let s = schemaCache.get(name);
751
+ if (!s) {
752
+ s = JSON.parse(fs.readFileSync(path.join(SCHEMA_DIR, name), 'utf8'));
753
+ assertSupported(s);
754
+ schemaCache.set(name, s);
755
+ }
756
+ return s;
757
+ }
758
+ //# sourceMappingURL=load.js.map