noonsight 0.0.0-stage → 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 (115) hide show
  1. package/.claude-plugin/marketplace.json +19 -0
  2. package/.claude-plugin/plugin.json +14 -0
  3. package/LICENSE +21 -0
  4. package/README.md +281 -2
  5. package/dist/src/adapters/claude-code/classifier.js +138 -0
  6. package/dist/src/adapters/claude-code/code-edit.js +108 -0
  7. package/dist/src/adapters/claude-code/compat.js +31 -0
  8. package/dist/src/adapters/claude-code/definitions.js +347 -0
  9. package/dist/src/adapters/claude-code/fork.js +132 -0
  10. package/dist/src/adapters/claude-code/hook.js +652 -0
  11. package/dist/src/adapters/claude-code/install.js +186 -0
  12. package/dist/src/adapters/claude-code/launch.js +270 -0
  13. package/dist/src/adapters/claude-code/launcher.js +252 -0
  14. package/dist/src/adapters/claude-code/locations.js +115 -0
  15. package/dist/src/adapters/claude-code/managed.js +75 -0
  16. package/dist/src/adapters/claude-code/plugin-files.js +88 -0
  17. package/dist/src/adapters/claude-code/plugins.js +117 -0
  18. package/dist/src/adapters/claude-code/pointer.js +48 -0
  19. package/dist/src/adapters/claude-code/predict.js +271 -0
  20. package/dist/src/adapters/claude-code/routing.js +88 -0
  21. package/dist/src/adapters/claude-code/settings.js +189 -0
  22. package/dist/src/adapters/claude-code/subagents.js +666 -0
  23. package/dist/src/adapters/claude-code/triggers.js +88 -0
  24. package/dist/src/cli.js +157 -0
  25. package/dist/src/commands/accept.js +115 -0
  26. package/dist/src/commands/check.js +529 -0
  27. package/dist/src/commands/hook.js +73 -0
  28. package/dist/src/commands/init.js +29 -0
  29. package/dist/src/commands/install.js +370 -0
  30. package/dist/src/commands/models.js +213 -0
  31. package/dist/src/commands/receives.js +84 -0
  32. package/dist/src/commands/report.js +386 -0
  33. package/dist/src/commands/resolve.js +32 -0
  34. package/dist/src/commands/run.js +168 -0
  35. package/dist/src/commands/trust.js +70 -0
  36. package/dist/src/commands/usage.js +10 -0
  37. package/dist/src/commands/watch.js +154 -0
  38. package/dist/src/config/create.js +51 -0
  39. package/dist/src/config/json-schema.js +207 -0
  40. package/dist/src/config/load.js +758 -0
  41. package/dist/src/config/paths.js +42 -0
  42. package/dist/src/config/preset-changes.js +190 -0
  43. package/dist/src/config/project.js +354 -0
  44. package/dist/src/config/rewrite.js +112 -0
  45. package/dist/src/core/backtracking.js +330 -0
  46. package/dist/src/core/classify.js +66 -0
  47. package/dist/src/core/normalize.js +24 -0
  48. package/dist/src/core/overlap.js +39 -0
  49. package/dist/src/core/regex-sample.js +278 -0
  50. package/dist/src/core/resolve.js +201 -0
  51. package/dist/src/core/route.js +93 -0
  52. package/dist/src/core/scope.js +77 -0
  53. package/dist/src/core/triggers.js +30 -0
  54. package/dist/src/core/types.js +74 -0
  55. package/dist/src/state/agents.js +200 -0
  56. package/dist/src/state/claims.js +80 -0
  57. package/dist/src/state/files.js +84 -0
  58. package/dist/src/state/installs.js +29 -0
  59. package/dist/src/state/log.js +90 -0
  60. package/dist/src/state/node.js +35 -0
  61. package/dist/src/state/sessions.js +109 -0
  62. package/dist/src/state/triggers.js +57 -0
  63. package/dist/src/version.js +24 -0
  64. package/dist/src/watch/service.js +172 -0
  65. package/dist/src/watch/watcher.js +130 -0
  66. package/dist/src/wording.js +11 -0
  67. package/hooks/hooks.json +118 -0
  68. package/package.json +60 -4
  69. package/presets/claude/SOURCES.md +485 -0
  70. package/presets/claude/preset.json +432 -0
  71. package/presets/claude/rules/fable-5-2/code-ownership.md +1 -0
  72. package/presets/claude/rules/fable-5-2/finish-work.md +1 -0
  73. package/presets/claude/rules/fable-5-2/low-context-report.md +1 -0
  74. package/presets/claude/rules/fable-5-2/progress-updates.md +1 -0
  75. package/presets/claude/rules/haiku-5-5/carry-through.md +1 -0
  76. package/presets/claude/rules/haiku-5-5/search-recent-facts.md +1 -0
  77. package/presets/claude/rules/haiku-5-5/verify-changes.md +1 -0
  78. package/presets/claude/rules/opus-5-5/explore-before-acting.md +1 -0
  79. package/presets/claude/rules/opus-5-5/progress-updates.md +1 -0
  80. package/presets/claude/rules/opus-5-5/unattended-run.md +1 -0
  81. package/presets/claude/rules/sonnet-5-5/carry-through.md +1 -0
  82. package/presets/claude/rules/sonnet-5-5/check-current-facts.md +1 -0
  83. package/presets/claude/rules/sonnet-5-5/ideas-first.md +1 -0
  84. package/presets/claude/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  85. package/presets/claude/rules/sonnet-5-5/stay-in-scope.md +1 -0
  86. package/presets/claude/rules/sonnet-5-5/verify-changes.md +1 -0
  87. package/presets/claude/versions/1.3.0/preset.json +432 -0
  88. package/presets/claude/versions/1.3.0/rules/fable-5-2/code-ownership.md +1 -0
  89. package/presets/claude/versions/1.3.0/rules/fable-5-2/finish-work.md +1 -0
  90. package/presets/claude/versions/1.3.0/rules/fable-5-2/low-context-report.md +1 -0
  91. package/presets/claude/versions/1.3.0/rules/fable-5-2/progress-updates.md +1 -0
  92. package/presets/claude/versions/1.3.0/rules/haiku-5-5/carry-through.md +1 -0
  93. package/presets/claude/versions/1.3.0/rules/haiku-5-5/search-recent-facts.md +1 -0
  94. package/presets/claude/versions/1.3.0/rules/haiku-5-5/verify-changes.md +1 -0
  95. package/presets/claude/versions/1.3.0/rules/opus-5-5/explore-before-acting.md +1 -0
  96. package/presets/claude/versions/1.3.0/rules/opus-5-5/progress-updates.md +1 -0
  97. package/presets/claude/versions/1.3.0/rules/opus-5-5/unattended-run.md +1 -0
  98. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/carry-through.md +1 -0
  99. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/check-current-facts.md +1 -0
  100. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/ideas-first.md +1 -0
  101. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  102. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/stay-in-scope.md +1 -0
  103. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/verify-changes.md +1 -0
  104. package/schema/noonsight-project.schema.json +394 -0
  105. package/schema/noonsight.schema.json +425 -0
  106. package/schema/preset.schema.json +194 -0
  107. package/scripts/noonsight +68 -0
  108. package/skills/accept/SKILL.md +11 -0
  109. package/skills/check/SKILL.md +11 -0
  110. package/skills/models/SKILL.md +11 -0
  111. package/skills/report/SKILL.md +11 -0
  112. package/skills/resolve/SKILL.md +12 -0
  113. package/skills/setup/SKILL.md +15 -0
  114. package/skills/trust/SKILL.md +12 -0
  115. package/skills/untrust/SKILL.md +12 -0
@@ -0,0 +1,370 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { checkInstallable, checkUninstallable, install, InstallRefused, NeedsPermission, readSettings, uninstall } from '../adapters/claude-code/install.js';
5
+ import { accountTarget, defaultAccountDir, discoverConfigDirs, managedTarget, UnsupportedPlatformError } from '../adapters/claude-code/locations.js';
6
+ import { managedFilesApply, readRemoteSettings } from '../adapters/claude-code/managed.js';
7
+ import { noonsightPlugins, runsFromPlugin } from '../adapters/claude-code/plugins.js';
8
+ import { findNoonsightHandlers } from '../adapters/claude-code/settings.js';
9
+ import { writeConfig } from '../config/create.js';
10
+ import { ConfigError, loadConfig, loadConfigDetails } from '../config/load.js';
11
+ import { CLI_FILE, configPath, stateDir } from '../config/paths.js';
12
+ import { projectFor } from '../config/project.js';
13
+ import { isPermissionError } from '../state/files.js';
14
+ import { accountInstalls, recordAccountInstall } from '../state/installs.js';
15
+ import { packageVersion } from '../version.js';
16
+ import { runCheck } from './check.js';
17
+ import { changeLines, receivesLines } from './receives.js';
18
+ import { UsageError } from './usage.js';
19
+ export const INSTALL_USAGE = `usage: noonsight install [--account <dir> | --managed]
20
+ noonsight uninstall [--account <dir> | --managed]
21
+
22
+ One command sets noonsight up: it writes the configuration file when there is none (as
23
+ \`noonsight init\`, never replacing an existing file), installs the hooks, runs \`noonsight check\`
24
+ and lists what each declared model receives. It is safe to run again, and says what it changed or
25
+ that nothing changed. It exits 0 once the hooks and a valid configuration are in place, and the
26
+ check's lines say what else needs attention; it exits 2 when the configuration is refused.
27
+
28
+ With no option, install noonsight's hooks into the user settings of every Claude Code configuration
29
+ directory of this account: ~/.claude, the directory in CLAUDE_CONFIG_DIR, and every other directory
30
+ in the home directory that holds a Claude Code configuration, one per login. It needs no
31
+ administrator rights, and it reaches every login, including one whose organization delivers
32
+ server-managed settings. Run it again after adding a Claude Code configuration directory, or run
33
+ \`noonsight watch enable\` once to have each new one installed as it appears; \`noonsight check\`
34
+ lists any directory it does not reach.
35
+
36
+ --account <dir> only this Claude Code configuration directory
37
+ --managed once for every account on the machine, in Claude Code's managed settings files;
38
+ needs administrator rights, and Claude Code ignores these files on a login whose
39
+ organization delivers server-managed settings (see docs/install.md); it only
40
+ installs the hooks, because the configuration belongs to each account
41
+
42
+ Running install again changes nothing; uninstall removes only noonsight's own entries.`;
43
+ /** The page that explains the guard Claude Code loads on every machine with managed settings. */
44
+ export const MOD_GUARD_URL = 'https://code.claude.com/docs/en/plugins/mods/admin#know-what-happens-by-default';
45
+ /** Why nothing that stays may point at the copy of noonsight a plugin runs. */
46
+ export const PLUGIN_COPY_REFUSED = 'this copy of noonsight is the one a Claude Code plugin runs, in a folder Claude Code deletes some time after an update, so hooks and the watcher cannot point at it; nothing was changed. ' +
47
+ 'The plugin already delivers in its own login. To install the hooks, run noonsight from npm: `npx noonsight install`.';
48
+ export function runInstall(command, args, env, io, options = {}) {
49
+ const mode = parseMode(args);
50
+ const home = os.homedir();
51
+ const runtime = { node: process.execPath, cli: fs.realpathSync(CLI_FILE), version: packageVersion() };
52
+ if (command === 'install' && runsFromPlugin(env)) {
53
+ io.err(`noonsight: ${PLUGIN_COPY_REFUSED}`);
54
+ return 1;
55
+ }
56
+ let targets;
57
+ try {
58
+ if (mode.kind === 'managed')
59
+ targets = [managedTarget(env)];
60
+ else if (mode.kind === 'account')
61
+ targets = [accountTarget(mode.dir, home)];
62
+ else
63
+ targets = everyAccountTarget(command, env, home);
64
+ }
65
+ catch (e) {
66
+ if (!(e instanceof UnsupportedPlatformError) && !(e instanceof InstallRefused))
67
+ throw e;
68
+ io.err(`noonsight: ${e.message}`);
69
+ return 1;
70
+ }
71
+ const setup = command === 'install' && mode.kind !== 'managed' && options.hooksOnly !== true;
72
+ let wrote = null;
73
+ const lines = [];
74
+ let current = targets[0];
75
+ try {
76
+ if (command === 'install') {
77
+ // Every directory is checked before any is written, so a refusal leaves all of them as they were.
78
+ for (const target of targets) {
79
+ current = target;
80
+ checkInstallable(target, runtime);
81
+ }
82
+ if (setup) {
83
+ const file = configPath(env, home);
84
+ try {
85
+ wrote = writeConfig(env);
86
+ }
87
+ catch (e) {
88
+ if (!isPermissionError(e))
89
+ throw e;
90
+ io.err(`noonsight: this account cannot write ${e.path ?? file}, so the configuration file ${file} was not written, and no hook was written either. ` +
91
+ 'Make that directory writable, or set NOONSIGHT_CONFIG to a file this account can write, then run `noonsight install` again.');
92
+ return 1;
93
+ }
94
+ lines.push(...(wrote ?? [`config ${file}: already there, left as it is`]));
95
+ }
96
+ for (const target of targets) {
97
+ current = target;
98
+ lines.push(...install(target, runtime));
99
+ record(target, true, home, lines);
100
+ }
101
+ }
102
+ else {
103
+ // The per-account pointer is shared by every account install of this account: it stays while a
104
+ // recorded directory that still exists, and that this uninstall has not reached yet, runs it.
105
+ const recorded = accountInstalls(stateDir(home));
106
+ const vanished = recorded.filter(isGone);
107
+ const live = recorded.filter((d) => !vanished.includes(d));
108
+ const keepPointer = targets.map((target, i) => target.kind === 'account' && live.some((d) => !targets.slice(0, i + 1).some((t) => t.configDir === d)));
109
+ for (const [i, target] of targets.entries()) {
110
+ current = target;
111
+ checkUninstallable(target, { keepPointer: keepPointer[i] === true });
112
+ }
113
+ for (const [i, target] of targets.entries()) {
114
+ current = target;
115
+ lines.push(...uninstall(target, { keepPointer: keepPointer[i] === true }));
116
+ record(target, false, home, lines);
117
+ }
118
+ if (mode.kind !== 'managed')
119
+ for (const dir of vanished)
120
+ if (recordDir(dir, false, home, lines))
121
+ lines.push(`account install ${dir}: forgotten (the directory no longer exists)`);
122
+ }
123
+ }
124
+ catch (e) {
125
+ const failed = current ?? targets[0];
126
+ if (failed === undefined)
127
+ throw e;
128
+ if (lines.length)
129
+ io.out(lines.join('\n'));
130
+ if (e instanceof NeedsPermission) {
131
+ io.err(permissionMessage(command, failed, e.paths, runtime, env, home, lines.length > 0));
132
+ return 1;
133
+ }
134
+ if (e instanceof InstallRefused) {
135
+ io.err(`noonsight: ${e.message}${lines.length > 0 ? ' (except what the lines above report)' : ''}`);
136
+ return 1;
137
+ }
138
+ // A permission the check before writing could not foresee, such as a file locked meanwhile.
139
+ if (isPermissionError(e)) {
140
+ io.err(permissionMessage(command, failed, [e.path ?? failed.settingsFile], runtime, env, home, lines.length > 0));
141
+ return 1;
142
+ }
143
+ throw e;
144
+ }
145
+ if (setup)
146
+ return finishSetup(lines, wrote !== null, targets, env, home, io);
147
+ if (command === 'install')
148
+ lines.push(...installNotes(targets, env, home, true));
149
+ else {
150
+ if (targets.length === 0)
151
+ lines.push('no Claude Code configuration directory found; nothing to remove');
152
+ lines.push(...pluginNotes(targets, env, (id) => `still delivers there; to remove it too: \`claude plugin uninstall ${id}\``));
153
+ }
154
+ io.out(lines.join('\n'));
155
+ return 0;
156
+ }
157
+ /**
158
+ * The rest of the one-command setup, once the configuration file and the hooks are in: what each
159
+ * declared model receives, then the check, then one line on what changed. It composes models and
160
+ * check, and holds no logic of its own about them. Its exit status covers what it set up, the hooks
161
+ * and the configuration; the check's lines report the rest of the machine without changing it.
162
+ */
163
+ function finishSetup(setupLines, wroteConfig, targets, env, home, io) {
164
+ const out = [...setupLines];
165
+ let usable = true;
166
+ try {
167
+ out.push(...receives(env, home));
168
+ }
169
+ catch (e) {
170
+ if (!(e instanceof ConfigError))
171
+ throw e;
172
+ usable = false;
173
+ }
174
+ const checked = [];
175
+ const checkStatus = runCheck([], env, (t) => checked.push(t), { receives: false });
176
+ if (checkStatus === 2)
177
+ usable = false;
178
+ out.push(...checked, ...installNotes(targets, env, home, false));
179
+ const hooks = setupLines.filter((l) => /^hooks .*: (created|added)\b/.test(l)).length;
180
+ const pointer = setupLines.some((l) => /^hook pointer .*: (written|rewritten)\b/.test(l));
181
+ const changes = [
182
+ ...(wroteConfig ? ['the configuration file was written'] : []),
183
+ ...(hooks > 0 ? [`hooks were added to ${hooks} Claude Code configuration ${hooks === 1 ? 'directory' : 'directories'}`] : []),
184
+ ...(pointer && hooks === 0 ? ['the hook pointer was updated'] : []),
185
+ ];
186
+ out.push(changes.length === 0 ? 'Nothing changed: noonsight was already set up here.' : `Changed: ${changes.join('; ')}.`);
187
+ if (!usable)
188
+ out.push('Until the configuration is fixed, sessions get no rules. Edit it, then run `noonsight install` again.');
189
+ else if (checkStatus !== 0)
190
+ out.push('Not done yet: fix the problems the check reports above, then run `noonsight check` again.');
191
+ else
192
+ out.push('Done: from the next Claude Code session on, each session and subagent receives what the lines above give its model in its place and scope. ' +
193
+ '`noonsight report` shows what was delivered. To undo: `noonsight uninstall`.');
194
+ io.out(out.join('\n'));
195
+ return usable ? 0 : 2;
196
+ }
197
+ /**
198
+ * What each declared model will receive in each place with no scope, one line each, and the two ways
199
+ * to change it; the configuration is read as a session started here would read it.
200
+ */
201
+ function receives(env, home) {
202
+ const file = configPath(env, home);
203
+ const details = loadConfigDetails(file, { project: projectFor(env.CLAUDE_PROJECT_DIR || process.cwd(), file, stateDir(home)) }, env);
204
+ return [
205
+ 'Each declared model receives, with no scope:',
206
+ ...receivesLines(details).map((l) => ` ${l}`),
207
+ ...changeLines(details).map((l) => ` ${l}`),
208
+ ];
209
+ }
210
+ /**
211
+ * The default install reaches every Claude Code configuration directory of this account. ~/.claude
212
+ * is Claude Code's own default, so install creates it when Claude Code has not run yet; uninstall
213
+ * also visits every directory noonsight installed into before.
214
+ */
215
+ function everyAccountTarget(command, env, home) {
216
+ if (process.getuid?.() === 0 && ownerOf(home) !== 0)
217
+ throw new InstallRefused(`${home} belongs to another account. Without --managed, noonsight installs for the account that runs it: ` +
218
+ 'run it as that account, without sudo, or install for every account with --managed.');
219
+ const recorded = accountInstalls(stateDir(home));
220
+ if (command === 'install') {
221
+ const defaultDir = path.join(home, '.claude');
222
+ if (!fs.existsSync(defaultDir))
223
+ fs.mkdirSync(defaultDir, { recursive: true, mode: 0o700 });
224
+ }
225
+ return discoverConfigDirs(env, home, recorded).map((dir) => accountTarget(dir, home));
226
+ }
227
+ function ownerOf(file) {
228
+ try {
229
+ return fs.statSync(file).uid;
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ }
235
+ function record(target, installed, home, lines) {
236
+ if (target.kind === 'account' && target.configDir !== undefined)
237
+ recordDir(target.configDir, installed, home, lines);
238
+ }
239
+ function recordDir(configDir, installed, home, lines) {
240
+ try {
241
+ recordAccountInstall(stateDir(home), configDir, installed);
242
+ return true;
243
+ }
244
+ catch {
245
+ lines.push(`warning: could not update the list of account installs in ${stateDir(home)}; \`noonsight check\` may not see this install`);
246
+ return false;
247
+ }
248
+ }
249
+ /** Whether a recorded directory is gone; one that cannot be reached now, such as on an unmounted volume, is not. */
250
+ function isGone(dir) {
251
+ try {
252
+ return !fs.statSync(dir).isDirectory();
253
+ }
254
+ catch (e) {
255
+ const code = e.code;
256
+ return code === 'ENOENT' || code === 'ENOTDIR';
257
+ }
258
+ }
259
+ function parseMode(args) {
260
+ let mode = { kind: 'every' };
261
+ const set = (next) => {
262
+ if (mode.kind !== 'every')
263
+ throw new UsageError('give at most one of --account and --managed', INSTALL_USAGE);
264
+ mode = next;
265
+ };
266
+ for (let i = 0; i < args.length; i++) {
267
+ const a = args[i] ?? '';
268
+ if (a === '--account') {
269
+ const dir = args[++i];
270
+ if (dir === undefined || dir === '')
271
+ throw new UsageError('--account needs a directory', INSTALL_USAGE);
272
+ set({ kind: 'account', dir });
273
+ }
274
+ else if (a.startsWith('--account=')) {
275
+ const dir = a.slice('--account='.length);
276
+ if (!dir)
277
+ throw new UsageError('--account needs a directory', INSTALL_USAGE);
278
+ set({ kind: 'account', dir });
279
+ }
280
+ else if (a === '--managed')
281
+ set({ kind: 'managed' });
282
+ else
283
+ throw new UsageError(a.startsWith('-') ? `unknown option ${a}` : `unexpected argument "${a}"`, INSTALL_USAGE);
284
+ }
285
+ return mode;
286
+ }
287
+ function installNotes(targets, env, home, withConfigLine) {
288
+ const notes = [];
289
+ if (targets[0]?.kind === 'managed') {
290
+ notes.push('note: every Claude Code account on this machine now runs these hooks; an account with no noonsight configuration gets nothing and is not warned.', 'note: a person can silence noonsight for one session with NOONSIGHT_DISABLE=1; disableAllHooks in their own settings does not reach managed hooks.', `note: on a machine with managed settings, Claude Code loads its built-in guard for the mods users install: ${MOD_GUARD_URL}`);
291
+ for (const dir of discoverConfigDirs(env, home)) {
292
+ const remote = readRemoteSettings(dir);
293
+ if (!managedFilesApply(remote))
294
+ notes.push(`warning: the login in ${dir} receives server-managed settings from its organization (${remote?.file ?? ''}), ` +
295
+ 'so Claude Code ignores the managed settings files there and its sessions get no rules from this install. ' +
296
+ 'Run `noonsight install`, without --managed and without sudo, as the account that owns it.');
297
+ }
298
+ }
299
+ else {
300
+ if (targets.length === 0)
301
+ notes.push('no Claude Code configuration directory found');
302
+ notes.push(...pluginNotes(targets, env, (id) => `reaches this login too; each event is delivered once, and one of the two is enough: \`claude plugin uninstall ${id}\` removes the plugin`));
303
+ const managed = safeManaged(env);
304
+ if (managed && hasNoonsightHooks(managed.settingsFile)) {
305
+ const both = targets.filter((t) => t.configDir !== undefined && managedFilesApply(readRemoteSettings(t.configDir)));
306
+ if (both.length)
307
+ notes.push(`warning: noonsight is also installed for the whole machine (${managed.settingsFile}), which reaches ${both.map((t) => t.configDir).join(', ')} too; ` +
308
+ 'each event is delivered once, so one of the two is enough: remove one with `noonsight uninstall`.');
309
+ }
310
+ }
311
+ if (process.getuid?.() === 0)
312
+ notes.push('next: run `noonsight check` as yourself, without administrator rights, to check your configuration.');
313
+ else if (withConfigLine)
314
+ notes.push(configLine(env, home));
315
+ return notes;
316
+ }
317
+ /** A line for each login of the targets where noonsight's plugin is on. */
318
+ function pluginNotes(targets, env, what) {
319
+ return targets.flatMap((t) => t.configDir === undefined
320
+ ? []
321
+ : noonsightPlugins({ projectDir: null, configDir: t.configDir, env })
322
+ .filter((p) => p.enabled && p.version !== null)
323
+ .map((p) => `note: the plugin ${p.id} in ${t.configDir} ${what(p.id)}`));
324
+ }
325
+ function configLine(env, home) {
326
+ const file = configPath(env, home);
327
+ if (!fs.existsSync(file))
328
+ return `next: create ${file} to declare your models (see docs/configuration.md), then run \`noonsight check\`.`;
329
+ try {
330
+ loadConfig(file, {}, env);
331
+ return `config ${file}: valid`;
332
+ }
333
+ catch (e) {
334
+ if (e instanceof ConfigError)
335
+ return `config ${file}: refused (${e.problems.length} problem${e.problems.length === 1 ? '' : 's'}); run \`noonsight check\` to see them. Until it is fixed, sessions get no rules.`;
336
+ throw e;
337
+ }
338
+ }
339
+ function permissionMessage(command, target, paths, runtime, env, home, changedBefore) {
340
+ const unchanged = changedBefore ? 'Nothing was changed past the lines above.' : 'Nothing was changed.';
341
+ const lines = [`noonsight: this account cannot write ${paths.join(' or ')}. ${unchanged}`];
342
+ if (target.kind === 'managed') {
343
+ lines[0] = `noonsight: ${command === 'install' ? 'installing' : 'uninstalling'} with --managed writes Claude Code's managed settings, which needs administrator rights. ${unchanged}`;
344
+ lines.push(`It writes: ${paths.join('\n ')}`, 'Run it once as an administrator:', ` sudo ${shellQuote(runtime.node)} ${shellQuote(runtime.cli)} ${command} --managed`, 'Or, with no administrator rights, for every Claude Code configuration directory of this account:', ` noonsight ${command}`);
345
+ }
346
+ else if (process.getuid?.() !== 0) {
347
+ lines.push(`To ${command} for one directory only: noonsight ${command} --account ${shellQuote(defaultAccountDir(env, home))}`);
348
+ }
349
+ return lines.join('\n');
350
+ }
351
+ function safeManaged(env) {
352
+ try {
353
+ return managedTarget(env);
354
+ }
355
+ catch {
356
+ return null;
357
+ }
358
+ }
359
+ function hasNoonsightHooks(file) {
360
+ try {
361
+ return findNoonsightHandlers(readSettings(file)).length > 0;
362
+ }
363
+ catch {
364
+ return false;
365
+ }
366
+ }
367
+ function shellQuote(s) {
368
+ return /^[A-Za-z0-9_./~:@%+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
369
+ }
370
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1,213 @@
1
+ // noonsight models: the models the configuration declares and the rules each one receives, with the
2
+ // source, effect and cost the preset gives for each rule; the preset's models that are not
3
+ // declared; and the models the decision log has seen that are not declared. It reads local files
4
+ // only and changes nothing.
5
+ import os from 'node:os';
6
+ import { loadConfigDetails } from '../config/load.js';
7
+ import { configPath, stateDir } from '../config/paths.js';
8
+ import { describeProject, projectFor } from '../config/project.js';
9
+ import { ANY_SCOPE } from '../core/types.js';
10
+ import { readDecisions } from '../state/log.js';
11
+ import { UsageError } from './usage.js';
12
+ export const MODELS_USAGE = `usage: noonsight models [--json]
13
+
14
+ List the models the configuration declares and the rules each one receives, with the source,
15
+ effect and cost of each preset rule; the preset's models that are not declared; and the models
16
+ seen in the decision log that are not declared. A project configuration found from the current
17
+ directory applies as it would to a session started here. --json prints the same as JSON.
18
+ Exits 0, or 2 for a usage error or a refused configuration.`;
19
+ export function runModels(args, env, out) {
20
+ const json = args.includes('--json');
21
+ const other = args.find((a) => a !== '--json');
22
+ if (other !== undefined)
23
+ throw new UsageError(other.startsWith('-') ? `unknown option ${other}` : `unexpected argument "${other}"`, MODELS_USAGE);
24
+ const report = modelsReport(env);
25
+ out(json ? JSON.stringify(report, null, 2) : renderModels(report));
26
+ return 0;
27
+ }
28
+ export function modelsReport(env, home = os.homedir()) {
29
+ const file = configPath(env, home);
30
+ const log = stateDir(home);
31
+ const project = projectFor(env.CLAUDE_PROJECT_DIR || process.cwd(), file, log);
32
+ const { config, preset, presetVersions, declared, allModels, project: layer } = loadConfigDetails(file, { project }, env);
33
+ const seen = seenModels(log);
34
+ const listed = [];
35
+ for (const [key, entry] of declared) {
36
+ if (entry.wildcard) {
37
+ const pattern = config.wildcards.find((w) => w.key === key)?.pattern;
38
+ // A seen model is covered by the wildcard that decides for it: none when an exact key or a stronger wildcard wins.
39
+ const covers = Object.fromEntries([...seen].filter(([model]) => pattern?.test(model) && decidingKey(config, model) === key));
40
+ listed.push({ key, use: entry.use, wildcard: true, rules: [], covers });
41
+ continue;
42
+ }
43
+ listed.push({ key, use: entry.use, wildcard: false, rules: listRules(key, entry, config, preset, allModels), seen: seen.get(key) ?? { decisions: 0, last: null } });
44
+ }
45
+ const presetUndeclared = [...(preset?.models ?? [])]
46
+ .filter(([key]) => decidingKey(config, key) === null)
47
+ .map(([key, rules]) => ({ key, rules: rules.length, on_by_default: rules.filter((r) => r.enabled).length }));
48
+ const seenUndeclared = [...seen]
49
+ .filter(([model]) => decidingKey(config, model) === null)
50
+ .map(([model, s]) => ({ model, ...s, in_preset: preset?.models.has(model) ?? false }));
51
+ return {
52
+ config: file,
53
+ project: layer && { file: layer.file, dir: layer.dir, allow: layer.allow, status: layer.status, summary: describeProject(layer) },
54
+ log,
55
+ preset: preset && {
56
+ name: preset.name,
57
+ version: preset.version,
58
+ claude_code: preset.claudeCode,
59
+ accepted: presetVersions.accepted,
60
+ installed: presetVersions.installed?.version ?? null,
61
+ },
62
+ all_models: config.allModels.map((r) => userRule(r, allModels.find((a) => a.id === r.id)?.file)),
63
+ declared: listed,
64
+ preset_undeclared: presetUndeclared,
65
+ seen_undeclared: seenUndeclared,
66
+ };
67
+ }
68
+ /**
69
+ * The rules of one exact model, in the order they are delivered: every preset rule, on or off, for
70
+ * "use": "preset", each replaced one followed by the user rule delivered in its place, then the rules
71
+ * of "all_models", then the model's own.
72
+ */
73
+ function listRules(key, entry, config, preset, allModels) {
74
+ const resolved = config.exact.get(key);
75
+ const delivered = resolved?.use === 'rules' ? resolved.rules : [];
76
+ const on = new Set(delivered.map((r) => `${r.origin}:${r.id}`));
77
+ const own = (r) => userRule(r, entry.add.find((a) => a.id === r.id)?.file);
78
+ const rules = [];
79
+ if (entry.use === 'preset')
80
+ for (const r of preset?.models.get(key) ?? []) {
81
+ const by = delivered.find((x) => x.replaces === r.id);
82
+ rules.push(presetRule(r, on.has(`preset:${r.id}`), by?.id));
83
+ if (by !== undefined)
84
+ rules.push(own(by));
85
+ }
86
+ for (const r of delivered.filter((x) => x.allModels))
87
+ rules.push(userRule(r, allModels.find((a) => a.id === r.id)?.file));
88
+ for (const r of delivered.filter((x) => x.origin === 'user' && !x.allModels && x.replaces === undefined))
89
+ rules.push(own(r));
90
+ return rules;
91
+ }
92
+ function presetRule(r, on, replacedBy) {
93
+ return {
94
+ id: r.id,
95
+ origin: 'preset',
96
+ on,
97
+ scopes: r.scopes,
98
+ where: r.where,
99
+ triggers: r.triggers,
100
+ source: r.source,
101
+ effect: r.effect,
102
+ cost: r.cost,
103
+ ...(replacedBy !== undefined ? { replaced_by: replacedBy } : {}),
104
+ };
105
+ }
106
+ function userRule(r, file) {
107
+ return {
108
+ id: r.id,
109
+ origin: 'user',
110
+ on: true,
111
+ scopes: r.scopes,
112
+ where: r.where,
113
+ triggers: r.triggers,
114
+ ...(r.allModels ? { from: 'all_models' } : {}),
115
+ ...(r.project ? { project: true } : {}),
116
+ ...(file !== undefined ? { file } : {}),
117
+ ...(r.replaces !== undefined ? { replaces: r.replaces } : {}),
118
+ };
119
+ }
120
+ /** The key that decides for a model, as the core resolves it: the exact key, else the strongest wildcard. */
121
+ function decidingKey(config, model) {
122
+ if (config.exact.has(model))
123
+ return model;
124
+ return config.wildcards.find((w) => w.pattern.test(model))?.key ?? null;
125
+ }
126
+ /** Every model the decision log names, with how many decisions named it and the latest time. */
127
+ function seenModels(dir) {
128
+ const seen = new Map();
129
+ for (const record of readDecisions(dir)) {
130
+ const model = record.model;
131
+ if (typeof model !== 'string' || model === '')
132
+ continue;
133
+ const s = seen.get(model) ?? { decisions: 0, last: null };
134
+ s.decisions++;
135
+ if (typeof record.ts === 'string' && (s.last === null || record.ts > s.last))
136
+ s.last = record.ts;
137
+ seen.set(model, s);
138
+ }
139
+ return new Map([...seen].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
140
+ }
141
+ export function renderModels(r) {
142
+ const lines = [`config ${r.config}`];
143
+ if (r.project)
144
+ lines.push(`project ${r.project.file}: ${r.project.summary}`);
145
+ if (r.preset)
146
+ lines.push(`preset ${r.preset.name} ${r.preset.version}` +
147
+ (r.preset.installed !== null && r.preset.installed !== r.preset.version ? ` (held; the package ships ${r.preset.installed})` : '') +
148
+ (r.preset.claude_code
149
+ ? `: its rules were compared with the system prompts of Claude Code ${r.preset.claude_code.version} on ${r.preset.claude_code.checked}, so none is delivered where that version already sends the same advice`
150
+ : ''));
151
+ else
152
+ lines.push('preset: not installed');
153
+ if (r.all_models.length) {
154
+ lines.push('', `all_models: ${r.all_models.length} ${r.all_models.length === 1 ? 'rule' : 'rules'} for every model declared with "use": "preset" or "use": "custom", after the preset's rules and before the model's own`);
155
+ for (const rule of r.all_models)
156
+ lines.push(ruleLine(rule), ...(rule.file !== undefined ? [` file: ${rule.file}`] : []));
157
+ }
158
+ for (const m of r.declared) {
159
+ lines.push('');
160
+ if (m.wildcard) {
161
+ const covered = Object.entries(m.covers ?? {});
162
+ lines.push(`${m.key}: none, a wildcard` +
163
+ (covered.length ? `; covers ${covered.map(([model, s]) => `${model} (${times(s.decisions)})`).join(', ')} from the decision log` : ''));
164
+ continue;
165
+ }
166
+ const on = m.rules.filter((x) => x.on).length;
167
+ const head = m.use === 'none'
168
+ ? 'none, by decision'
169
+ : m.use === 'preset'
170
+ ? `preset, ${on} of ${m.rules.length} rules on`
171
+ : `custom, ${m.rules.length} ${m.rules.length === 1 ? 'rule' : 'rules'}`;
172
+ lines.push(`${m.key}: ${head}; ${seenText(m.seen)}`);
173
+ for (const rule of m.rules) {
174
+ lines.push(ruleLine(rule));
175
+ if (rule.source)
176
+ lines.push(` source: ${rule.source.url}, "${rule.source.section}", read ${rule.source.date}`);
177
+ if (rule.effect !== undefined)
178
+ lines.push(` effect: ${rule.effect}`);
179
+ if (rule.cost !== undefined)
180
+ lines.push(` cost: ${rule.cost}`);
181
+ if (rule.file !== undefined)
182
+ lines.push(` file: ${rule.file}`);
183
+ }
184
+ }
185
+ if (r.preset_undeclared.length) {
186
+ lines.push('', 'In the preset, not declared (add an entry with "use": "preset" to receive these rules):');
187
+ for (const p of r.preset_undeclared)
188
+ lines.push(` ${p.key}: ${p.rules} rules, ${p.on_by_default} on by default`);
189
+ }
190
+ if (r.seen_undeclared.length) {
191
+ lines.push('', `Seen in the decision log (${r.log}), not declared, so they get no rules and a warning:`);
192
+ for (const s of r.seen_undeclared)
193
+ lines.push(` ${s.model}: ${seenText(s)}; ` +
194
+ (s.in_preset ? 'the preset has rules for it ("use": "preset")' : 'the preset has no rules for it ("use": "custom" with your own, or "use": "none")'));
195
+ }
196
+ return lines.join('\n');
197
+ }
198
+ function ruleLine(rule) {
199
+ const triggers = rule.triggers.length ? `; triggers: ${rule.triggers.join(', ')}` : '';
200
+ const from = (rule.from === 'all_models' ? '; from all_models' : '') + (rule.project ? '; from the project' : '');
201
+ const pair = rule.replaced_by !== undefined ? `; replaced by ${rule.replaced_by}` : rule.replaces !== undefined ? `; replaces ${rule.replaces}` : '';
202
+ return ` ${rule.on ? 'on ' : 'off'} ${rule.id} (scopes: ${scopesText(rule.scopes)}; places: ${rule.where.join(', ')}${triggers}${from}${pair})`;
203
+ }
204
+ function scopesText(scopes) {
205
+ return scopes.includes(ANY_SCOPE) ? 'every scope' : scopes.join(', ');
206
+ }
207
+ function seenText(s) {
208
+ return !s || s.decisions === 0 ? 'not seen in the decision log' : `seen in ${times(s.decisions)}, last ${s.last ?? 'at an unknown time'}`;
209
+ }
210
+ function times(n) {
211
+ return `${n} ${n === 1 ? 'decision' : 'decisions'}`;
212
+ }
213
+ //# sourceMappingURL=models.js.map
@@ -0,0 +1,84 @@
1
+ // What each declared model receives in each place when nothing gives it a scope, written out, as
2
+ // `noonsight install` and `noonsight check` say it: one line per model, a place with no rule written
3
+ // as "nothing" with the preset rules that are off there, then the two ways to change what a session
4
+ // receives.
5
+ import { selectRules } from '../core/resolve.js';
6
+ import { PLACES, TRIGGERS } from '../core/types.js';
7
+ /** How the lines name each place. */
8
+ export const PLACE_NAMES = {
9
+ attended: 'attended session',
10
+ unattended: 'unattended session',
11
+ subagent: 'subagent',
12
+ };
13
+ /** When a trigger adds its rules to a session, as the lines say it. */
14
+ const TRIGGER_WHEN = {
15
+ 'code-edit': 'once it edits tracked code (code-edit)',
16
+ };
17
+ /**
18
+ * One line per declared model: what it receives in each place with no scope, "nothing" where it
19
+ * receives nothing. A place with nothing names the preset rules of the model that are off and are for
20
+ * that place, and the line ends by saying how such a place gets rules.
21
+ */
22
+ export function receivesLines(details) {
23
+ const { config } = details;
24
+ return [
25
+ ...[...config.exact].map(([key, entry]) => `${key}: ${describeEntry(entry, offRules(details, key, entry))}`),
26
+ ...config.wildcards.map((w) => `${w.key}: nothing in any place, by decision ("use": "none" for every model it matches)`),
27
+ ];
28
+ }
29
+ /** The two ways to change what a session receives: its place and its scope. */
30
+ export function changeLines({ config }) {
31
+ const { unattendedWhenEnv: names, headlessIsUnattended: headless } = config.session;
32
+ const set = names.length ? ` (here: ${names.join(', ')})` : '';
33
+ return [
34
+ (headless
35
+ ? 'A session is unattended when it runs headless, as `claude -p` and the Agent SDK do, or when a variable of `session.unattended_when_env` is set' +
36
+ `${set}; set it to your CI's or orchestrator's variable so the interactive sessions nobody watches are unattended too.`
37
+ : 'A session is unattended only when a variable of `session.unattended_when_env` is set' +
38
+ `${set}, because \`session.headless_is_unattended\` is false; set it to your CI's or orchestrator's variable for the sessions nobody watches.`),
39
+ 'A rule limited to scopes adds to these only in one of its scopes: a session takes its scope from `NOONSIGHT_SCOPE` or `noonsight run --scope`, ' +
40
+ 'a subagent from its task; `noonsight models` lists every rule with its scopes and places.',
41
+ ];
42
+ }
43
+ /**
44
+ * The preset rules of a model declared with "use": "preset" that it does not receive: those that ship
45
+ * off and are not enabled, and those disabled. A rule another one replaces is not off: the rule that
46
+ * replaces it is delivered in its place.
47
+ */
48
+ function offRules({ preset, declared }, key, entry) {
49
+ if (entry.use !== 'rules' || declared.get(key)?.use !== 'preset')
50
+ return [];
51
+ const on = new Set(entry.rules.flatMap((r) => (r.origin === 'preset' ? [r.id] : r.replaces !== undefined ? [r.replaces] : [])));
52
+ return (preset?.models.get(key) ?? []).filter((r) => !on.has(r.id));
53
+ }
54
+ function describeEntry(entry, off) {
55
+ if (entry.use === 'none')
56
+ return 'nothing in any place, by decision ("use": "none")';
57
+ const places = PLACES.map((place) => ({ place, always: selectRules(entry.rules, null, place) }));
58
+ const line = places.map(({ place, always }) => `${PLACE_NAMES[place]}: ${describePlace(entry.rules, place, always, off)}`).join('; ');
59
+ const empty = places.filter(({ always }) => always.length === 0).map(({ place }) => place);
60
+ if (empty.length === 0)
61
+ return line;
62
+ const offThere = off.some((r) => r.where.some((p) => empty.includes(p)));
63
+ return (`${line}. Your own rules without "where" are delivered in every place, the ${empty.map((p) => PLACE_NAMES[p]).join(' and ')} included` +
64
+ `${offThere ? '; "enable" turns on a rule that is off' : ''}.`);
65
+ }
66
+ /**
67
+ * The rules for every scope in a place, then those a trigger adds to a session; triggers act only in
68
+ * a session. A place with no rule for every scope names the rules that are off there, for any scope.
69
+ */
70
+ function describePlace(rules, place, always, off) {
71
+ const offHere = off.filter((r) => r.where.includes(place));
72
+ const parts = [always.length ? ids(always) : offHere.length ? `nothing (off: ${ids(offHere)})` : 'nothing'];
73
+ if (place !== 'subagent')
74
+ for (const t of TRIGGERS) {
75
+ const added = selectRules(rules, null, place, [t]).filter((r) => !always.includes(r));
76
+ if (added.length)
77
+ parts.push(`then ${ids(added)} ${TRIGGER_WHEN[t]}`);
78
+ }
79
+ return parts.join(', ');
80
+ }
81
+ function ids(rules) {
82
+ return rules.map((r) => r.id).join(', ');
83
+ }
84
+ //# sourceMappingURL=receives.js.map