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,529 @@
1
+ // noonsight check: the configuration, every install this account can see, the plugin included, the watcher, the Claude
2
+ // Code version and the last decision, one line each. It reads local files, runs `claude --version`,
3
+ // and, when the watcher is on, asks the service manager whether it runs; it never uses the network
4
+ // and never changes anything.
5
+ import { spawnSync } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { CLAUDE_CODE_FLOORS, MODEL_ALIASES } from '../adapters/claude-code/compat.js';
10
+ import { readSettings } from '../adapters/claude-code/install.js';
11
+ import { accountTarget, discoverConfigDirs, managedTarget } from '../adapters/claude-code/locations.js';
12
+ import { managedFilesApply, readManagedFiles, readRemoteSettings } from '../adapters/claude-code/managed.js';
13
+ import { noonsightPlugins } from '../adapters/claude-code/plugins.js';
14
+ import { readPointer } from '../adapters/claude-code/pointer.js';
15
+ import { findNoonsightHandlers, handlersFor, HOOK_HANDLERS, matcherOf } from '../adapters/claude-code/settings.js';
16
+ import { ConfigError, loadConfigDetails } from '../config/load.js';
17
+ import { changesDelivery, comparePresets, describeChanges } from '../config/preset-changes.js';
18
+ import { scopeOverlaps } from '../core/overlap.js';
19
+ import { SCOPE_ENV, sessionPlace, sessionScope } from '../core/scope.js';
20
+ import { ROUTING_ENV, routingEnvOff } from '../core/route.js';
21
+ import { TRIGGER_ACTIONS } from '../core/triggers.js';
22
+ import { ROUTE_TARGETS, RULES_TEXT_LIMIT, TRIGGERS } from '../core/types.js';
23
+ import { CLI_FILE, configPath, stateDir } from '../config/paths.js';
24
+ import { describeProject, projectFor } from '../config/project.js';
25
+ import { accountInstalls } from '../state/installs.js';
26
+ import { isLoaded, isOurs, manager, readServiceFile, serviceContent, watchService, WatchUnsupported } from '../watch/service.js';
27
+ import { lastDecision } from '../state/log.js';
28
+ import { compareVersions, packageVersion } from '../version.js';
29
+ import { changeLines, receivesLines } from './receives.js';
30
+ import { UsageError } from './usage.js';
31
+ export const CHECK_USAGE = `usage: noonsight check
32
+
33
+ Check the configuration, the installed hooks, the watcher and the Claude Code version, and show
34
+ the last decision. A project configuration found from the current directory is checked as a
35
+ session started here would read it. Each line starts with ok, warning or problem. Exits 0 when there is no problem, 1 when there is one,
36
+ and 2 when the configuration is missing or refused.`;
37
+ export function runCheck(args, env, out, options = {}) {
38
+ if (args.length)
39
+ throw new UsageError(`unexpected argument "${args[0]}"`, CHECK_USAGE);
40
+ const home = os.homedir();
41
+ const lines = [];
42
+ const add = (level, text) => {
43
+ lines.push([level, text]);
44
+ };
45
+ const version = packageVersion();
46
+ const cli = fs.realpathSync(CLI_FILE);
47
+ // Configuration.
48
+ const file = configPath(env, home);
49
+ let configOk = false;
50
+ try {
51
+ // As a session started here would: with the project found from this directory over the configuration.
52
+ const details = loadConfigDetails(file, { project: projectFor(env.CLAUDE_PROJECT_DIR || process.cwd(), file, stateDir(home)) }, env);
53
+ const config = details.config;
54
+ configOk = true;
55
+ const sub = config.subagents;
56
+ add('ok', `config ${file}: valid (${config.exact.size + config.wildcards.length} model entries; subagents: ` +
57
+ (sub.delivery === 'off' ? 'off' : `rules when each subagent starts, permission ${sub.permission} for a routed call, on mismatch ${sub.onMismatch}`) +
58
+ ')');
59
+ checkProject(details, add);
60
+ checkPreset(details, env, add);
61
+ checkAllModels(config, add);
62
+ if (options.receives !== false)
63
+ checkReceives(details, add);
64
+ checkScopes(config, env, add);
65
+ checkTriggers(config, add);
66
+ checkRouting(config, env, add);
67
+ checkClassifier(config, add);
68
+ }
69
+ catch (e) {
70
+ if (!(e instanceof ConfigError))
71
+ throw e;
72
+ add('problem', `config ${e.message.replace(/^configuration refused \(([^)]*)\):/, '$1: refused, so sessions get no rules:')}`);
73
+ }
74
+ // Installs: the machine-wide one, then every Claude Code configuration directory of this account.
75
+ let installs = 0;
76
+ let managed = null;
77
+ try {
78
+ managed = managedTarget(env);
79
+ }
80
+ catch (e) {
81
+ add('warning', `machine-wide install: ${e.message}`);
82
+ }
83
+ const managedInstalled = managed !== null && checkInstall(managed, version, cli, add, false);
84
+ if (managed) {
85
+ if (managedInstalled)
86
+ installs++;
87
+ checkManagedPolicy(managed, env, add, managedInstalled);
88
+ }
89
+ const recorded = accountInstalls(stateDir(home));
90
+ const dirs = discoverConfigDirs(env, home, recorded);
91
+ const uncovered = [];
92
+ for (const dir of dirs) {
93
+ const target = accountTarget(dir, home);
94
+ const remote = readRemoteSettings(dir);
95
+ const managedReaches = managedInstalled && managedFilesApply(remote);
96
+ const hasAccountHooks = hasHooks(target.settingsFile);
97
+ const plugins = noonsightPlugins({ projectDir: env.CLAUDE_PROJECT_DIR || process.cwd(), configDir: dir, env });
98
+ const pluginRuns = checkPlugins(dir, plugins, target.settingsFile, add);
99
+ if (pluginRuns !== null)
100
+ installs++;
101
+ // With the plugin there, a recorded install whose hooks are gone was replaced by it.
102
+ if (hasAccountHooks || (recorded.includes(dir) && pluginRuns === null)) {
103
+ if (checkInstall(target, version, cli, add, true))
104
+ installs++;
105
+ if (hasAccountHooks && managedReaches)
106
+ add('warning', `account install ${dir}: the machine-wide install reaches this login too; each event is delivered once, by whichever copy runs first, so one of the two is enough: remove one with \`noonsight uninstall\``);
107
+ }
108
+ else if (pluginRuns === null && managedReaches)
109
+ add('ok', `Claude Code configuration ${dir}: reached by the machine-wide install`);
110
+ else if (pluginRuns === null)
111
+ uncovered.push(dir);
112
+ if (pluginRuns !== null && (hasAccountHooks || managedReaches))
113
+ checkBoth(dir, pluginRuns, hasAccountHooks ? target : managed, add);
114
+ checkRemotePolicy(dir, remote, hasAccountHooks || pluginRuns !== null, managedInstalled, add);
115
+ }
116
+ if (installs === 0)
117
+ add('problem', 'noonsight is not installed: run `noonsight install`, or install the Claude Code plugin');
118
+ else
119
+ for (const dir of uncovered)
120
+ add('problem', `Claude Code configuration ${dir}: no noonsight hooks reach it` +
121
+ (managedInstalled ? ' (its login receives server-managed settings, so Claude Code ignores the machine-wide install there)' : '') +
122
+ '; run `noonsight install`');
123
+ // The watcher.
124
+ checkWatcher(env, home, cli, add);
125
+ // Claude Code.
126
+ checkClaude(env, add);
127
+ // The decision log.
128
+ const last = lastDecision(stateDir(home));
129
+ if (last)
130
+ add('ok', `last decision: ${String(last.ts)} ${String(last.event)} ${String(last.status ?? last.result)}` +
131
+ `${last.model ? ` ${String(last.model)}` : ''} (${String(last.delivered)}), log in ${stateDir(home)}`);
132
+ else
133
+ add('ok', `no decisions logged yet in ${stateDir(home)}`);
134
+ out(lines.map(([level, text]) => `${level}: ${text}`).join('\n'));
135
+ if (!configOk)
136
+ return 2;
137
+ return lines.some(([level]) => level === 'problem') ? 1 : 0;
138
+ }
139
+ /** The project configuration found from this directory: what became of it, and its entries that do not apply here. */
140
+ function checkProject(details, add) {
141
+ const layer = details.project;
142
+ if (layer === null)
143
+ return;
144
+ const level = layer.status === 'refused' ? 'problem' : layer.status === 'untrusted' ? 'warning' : 'ok';
145
+ add(level, `project ${layer.file}: ${describeProject(layer)}`);
146
+ for (const note of layer.notes)
147
+ add('warning', `project ${layer.file}: ${note}`);
148
+ }
149
+ /**
150
+ * The preset version the configuration accepted against the installed one, and, model by model, what
151
+ * the installed version changes: rules turned on or off, renamed or changed, and enable, disable or
152
+ * replaces entries that no longer name a rule.
153
+ */
154
+ function checkPreset(details, env, add) {
155
+ const v = details.presetVersions;
156
+ let c;
157
+ try {
158
+ c = comparePresets(v, details.declared, {}, env);
159
+ }
160
+ catch (e) {
161
+ if (!(e instanceof ConfigError))
162
+ throw e;
163
+ add('problem', `preset ${v.name}: the copy of ${String(v.accepted)} the package keeps was refused, so what changed since cannot be listed: ${e.problems.join('; ')}`);
164
+ return;
165
+ }
166
+ // A configuration that declares no model with "use": "preset" takes only the preset's scopes and routing table.
167
+ if (c === null || (c.accepted === null && ![...details.declared.values()].some((m) => m.use === 'preset')))
168
+ return;
169
+ const to = c.installed.version;
170
+ const accept = `run \`noonsight accept\` to accept ${to}`;
171
+ if (c.accepted === null)
172
+ add('warning', `preset ${c.name} ${to}: the configuration records no "preset_version", so nothing can say what a preset update changes in the rules sessions receive; ` +
173
+ `run \`noonsight accept\` to record ${to}`);
174
+ else if (c.accepted === to)
175
+ add('ok', `preset ${c.name} ${to}: the version the configuration accepted` + (v.onChange === 'hold' ? ', held ("on_preset_change": "hold")' : ''));
176
+ else if (c.from === null)
177
+ add('warning', `preset ${c.name}: the configuration accepted ${c.accepted}, but the package ships ${to} and keeps no copy of ${c.accepted}, so what changed cannot be listed; ` +
178
+ `sessions receive the rules of ${to}. Review them with \`noonsight models\`, then ${accept}`);
179
+ else if (c.held)
180
+ add('warning', `preset ${c.name}: held at ${c.accepted} ("on_preset_change": "hold") while the package ships ${to}, so sessions keep the rules of ${c.accepted}; ` +
181
+ (c.models.some(changesDelivery) ? `accepting ${to} would change them as listed below; ` : `${to} changes no rule a declared model receives; `) +
182
+ accept);
183
+ else
184
+ add('warning', `preset ${c.name}: the package ships ${to}, and the configuration accepted ${c.accepted}, so sessions receive the rules of ${to}` +
185
+ (c.models.some(changesDelivery) ? ', which changed as listed below' : ', which change no rule a declared model receives') +
186
+ `; ${accept} once reviewed`);
187
+ for (const m of c.models)
188
+ add('warning', `preset ${c.name}, ${m.model}: ${describeChanges(m, c.held)}`);
189
+ }
190
+ /**
191
+ * The "all_models" block: the models that receive its rules and the places they cover. The limit on
192
+ * the text delivered was already checked per model when the configuration loaded, with these rules
193
+ * in each model's rules, so a block that is too large for a model has refused the configuration.
194
+ */
195
+ function checkAllModels(config, add) {
196
+ if (config.allModels.length === 0)
197
+ return;
198
+ const receiving = [...config.exact].filter(([, entry]) => entry.use === 'rules').map(([model]) => model);
199
+ add('ok', `all_models: ${plural(config.allModels.length, 'rule')} (${config.allModels.map((r) => r.id).join(', ')}) delivered to ${plural(receiving.length, 'model')} declared with preset or custom` +
200
+ `${receiving.length ? ` (${receiving.join(', ')})` : ''}, each within the ${RULES_TEXT_LIMIT}-character limit on the rules delivered`);
201
+ if (receiving.length === 0)
202
+ add('warning', 'all_models: no model is declared with "use": "preset" or "use": "custom", so no model receives these rules');
203
+ }
204
+ /** What each declared model receives in each place with no scope, then how to change it. */
205
+ function checkReceives(details, add) {
206
+ for (const line of receivesLines(details))
207
+ add('ok', `receives with no scope, ${line}`);
208
+ add('ok', `places and scopes: ${changeLines(details).join(' ')}`);
209
+ }
210
+ /**
211
+ * The declared scopes: scopes a single task can fall in, matchers that could not be tested for that,
212
+ * and the scope and place sessions started from this environment get.
213
+ */
214
+ function checkScopes(config, env, add) {
215
+ const report = scopeOverlaps(config);
216
+ if (config.scopes.size > 0) {
217
+ const untested = report.untested.map((u) => `scope "${u.scope}": ${JSON.stringify(u.matcher)}`);
218
+ add('ok', `scopes: ${plural(config.scopes.size, 'scope')} declared, ${plural(report.matchers, 'matcher')}` +
219
+ (report.overlaps.length === 0 && untested.length === 0 && report.matchers > 0 ? '; no two scopes overlap' : '') +
220
+ (untested.length ? `; not all example texts could be built for ${untested.join(', ')}, so their overlaps are not fully checked` : ''));
221
+ }
222
+ for (const o of report.overlaps)
223
+ add('warning', `scopes "${o.scopes[0]}" and "${o.scopes[1]}" overlap: the task text ${JSON.stringify(o.text)} matches both` +
224
+ (o.winner !== null ? `, and a task with only that text gets "${o.winner}"` : '') +
225
+ '; the scope whose matcher matches earliest in a task wins, and at the same place the one declared first');
226
+ const scope = sessionScope(env).scope;
227
+ const place = sessionPlace(config, env);
228
+ if (scope !== null && !config.scopes.has(scope))
229
+ add('warning', `${SCOPE_ENV} is "${scope}" here, which is not a declared scope, so sessions started from this environment get only the rules for every scope`);
230
+ else if (scope !== null || place.because !== undefined)
231
+ add('ok', 'sessions started from this environment get ' +
232
+ (scope !== null ? `scope "${scope}" (${SCOPE_ENV})` : 'no scope') +
233
+ `, place "${place.place}"` +
234
+ (place.because === 'env' ? ` (${place.env} is set)` : place.because === 'headless' ? ' (a headless run)' : ''));
235
+ }
236
+ /** The triggers the hooks act on, and the rules that list each one. */
237
+ function checkTriggers(config, add) {
238
+ const listing = (trigger) => [...config.exact].flatMap(([model, entry]) => (entry.use === 'rules' ? entry.rules.filter((r) => r.triggers.includes(trigger)).map((r) => `${r.id} for ${model}`) : []));
239
+ for (const t of TRIGGERS) {
240
+ const rules = listing(t);
241
+ add('ok', `triggers: ${t}` + (rules.length ? `, which delivers ${rules.join(', ')} to ${TRIGGER_ACTIONS[t]}` : ', which no rule lists'));
242
+ }
243
+ }
244
+ /** Whether routing is on, where it acts, its table, and whether sessions started from this environment are routed. */
245
+ function checkRouting(config, env, add) {
246
+ const r = config.routing;
247
+ if (!r.enabled) {
248
+ add('ok', 'routing: off, so noonsight never changes a model or an effort');
249
+ return;
250
+ }
251
+ const rows = [...r.table.entries()].map(([scope, row]) => `${scope} ${describeRow(row)}`);
252
+ add('ok', `routing: on for ${r.targets.join(' and ')}` +
253
+ (r.respectExplicit ? ', a model the caller chose wins' : ', the table wins over a model the caller chose') +
254
+ (r.yieldWhenEnv.length ? `, yields when ${r.yieldWhenEnv.join(' or ')} is set` : '') +
255
+ `; table: ${rows.length ? rows.join('; ') : 'empty'}; default: ${r.default === null ? 'inherit' : describeRow(r.default)}`);
256
+ if (routingEnvOff(env))
257
+ add('ok', `${ROUTING_ENV} turns routing off for sessions started from this environment`);
258
+ else {
259
+ const yieldEnv = r.yieldWhenEnv.find((name) => (env[name] ?? '') !== '');
260
+ if (yieldEnv !== undefined)
261
+ add('ok', `routing yields for sessions started from this environment (${yieldEnv} is set)`);
262
+ }
263
+ }
264
+ /** Whether the classifier is on, for which tasks, and what one classification may cost in time. */
265
+ function checkClassifier(config, add) {
266
+ const c = config.classifier;
267
+ if (c.mode === 'off') {
268
+ add('ok', 'classifier: off, so a task without an explicit scope takes its scope from the matchers alone');
269
+ return;
270
+ }
271
+ const which = c.mode === 'fallback' ? 'for a task no explicit scope and no matcher placed' : 'for every task without an explicit scope, over the matchers';
272
+ add('ok', `classifier: ${c.mode}, ${which}; ${c.model} at ${c.effort} effort, at most ${c.timeoutMs} ms per task`);
273
+ }
274
+ function describeRow(row) {
275
+ const list = (options) => options === undefined ? 'default' : options.length === 0 ? 'none' : options.map((o) => (o.effort ? `${o.model} ${o.effort}` : o.model)).join(', ');
276
+ const [launcher, subagents] = ROUTE_TARGETS.map((t) => list(row[t]));
277
+ return launcher === subagents ? `[${launcher}]` : `[launcher: ${launcher}; subagents: ${subagents}]`;
278
+ }
279
+ function plural(n, word) {
280
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
281
+ }
282
+ /** Report one install; returns whether its hook entries are there. */
283
+ function checkInstall(target, version, cli, add, expected) {
284
+ const label = target.kind === 'managed' ? 'machine-wide install' : `account install ${target.configDir}`;
285
+ const again = target.kind === 'managed' ? '`noonsight install --managed` again, as an administrator,' : '`noonsight install` again';
286
+ let settings;
287
+ try {
288
+ settings = readSettings(target.settingsFile);
289
+ }
290
+ catch (e) {
291
+ add('problem', `${label}: ${e.message}`);
292
+ return false;
293
+ }
294
+ const found = findNoonsightHandlers(settings);
295
+ if (found.length === 0) {
296
+ if (expected)
297
+ add('problem', `${label}: no noonsight hooks in ${target.settingsFile}; run \`noonsight install --account ${target.configDir}\``);
298
+ else
299
+ add('ok', `${label}: not installed (${target.settingsFile})`);
300
+ return false;
301
+ }
302
+ const missing = HOOK_HANDLERS.filter((spec) => handlersFor(found, spec, target.pointer).length === 0);
303
+ if (missing.length || found.length !== HOOK_HANDLERS.length)
304
+ add('problem', `${label}: the hooks in ${target.settingsFile} are incomplete or point elsewhere` +
305
+ (missing.length ? ` (missing: ${missing.map(describeHandler).join(', ')})` : '') +
306
+ `; run ${again} to repair them`);
307
+ else
308
+ add('ok', `${label}: hooks in ${target.settingsFile} (${HOOK_HANDLERS.map(describeHandler).join(', ')})`);
309
+ if (target.kind === 'account' && settings?.disableAllHooks === true)
310
+ add('problem', `${label}: ${target.settingsFile} sets disableAllHooks, so Claude Code runs none of this account's hooks`);
311
+ const pointer = readPointer(target.pointer);
312
+ if (!pointer) {
313
+ add('problem', `${label}: the hook pointer ${target.pointer} is missing or unreadable; run ${again}`);
314
+ return true;
315
+ }
316
+ const unreachable = [reach(pointer.node, fs.constants.X_OK), reach(pointer.cli, fs.constants.R_OK)];
317
+ const gone = [pointer.node, pointer.cli].filter((_, i) => unreachable[i] === 'ENOENT');
318
+ if (gone.length) {
319
+ add('problem', `${label}: the hook pointer runs ${gone.join(' and ')}, which no longer exists; hooks do nothing. Run ${again}`);
320
+ return true;
321
+ }
322
+ const denied = [pointer.node, pointer.cli].filter((_, i) => unreachable[i] !== null);
323
+ if (denied.length) {
324
+ add('problem', `${label}: this account cannot run ${denied.join(' and ')}, so its hooks do nothing; ` +
325
+ 'install noonsight from a Node.js and a copy of noonsight that every account can read and run');
326
+ return true;
327
+ }
328
+ const running = pointer.cli === cli ? version : versionOf(pointer.node, pointer.cli);
329
+ if (running === null)
330
+ add('problem', `${label}: the copy of noonsight the hook pointer runs (${pointer.cli}) did not report its version`);
331
+ else if (running !== version)
332
+ add('warning', `${label}: hooks run noonsight ${running} (${pointer.cli}), but this copy is ${version}; run ${again} to switch`);
333
+ else
334
+ add('ok', `${label}: hook pointer ${target.pointer} runs noonsight ${running}`);
335
+ return true;
336
+ }
337
+ /** Report noonsight's plugin in one login; returns the one whose hooks run there, or null. */
338
+ function checkPlugins(dir, plugins, settingsFile, add) {
339
+ let runs = null;
340
+ for (const p of plugins) {
341
+ const label = `plugin ${p.id} in ${dir}`;
342
+ if (!p.enabled)
343
+ add('ok', `${label}: installed and turned off; \`claude plugin enable ${p.id}\` turns it on`);
344
+ else if (p.dir === null)
345
+ add('problem', `${label}: turned on in the settings and not installed, so it delivers nothing; run \`claude plugin install ${p.id}\``);
346
+ else if (p.version === null)
347
+ add('problem', `${label}: its folder ${p.dir} holds no noonsight that can run, so it delivers nothing; run \`claude plugin install ${p.id}\` again`);
348
+ else {
349
+ add('ok', `${label}: runs noonsight ${p.version} (${p.dir})` + (p.scope === 'project' || p.scope === 'local' ? `, in this project only (${p.scope} scope)` : ''));
350
+ runs ??= p;
351
+ }
352
+ }
353
+ if (runs !== null) {
354
+ let settings = null;
355
+ try {
356
+ settings = readSettings(settingsFile);
357
+ }
358
+ catch {
359
+ // Reported with the login's other findings, or by Claude Code itself.
360
+ }
361
+ if (settings?.disableAllHooks === true)
362
+ add('problem', `plugin ${runs.id} in ${dir}: ${settingsFile} sets disableAllHooks, so Claude Code runs none of its hooks`);
363
+ }
364
+ return runs;
365
+ }
366
+ /** A login the plugin and an install of the hooks both reach: safe, but the copy that runs first decides the version. */
367
+ function checkBoth(dir, plugin, target, add) {
368
+ const pointer = target === null ? null : readPointer(target.pointer);
369
+ const other = pointer === null ? null : versionOf(pointer.node, pointer.cli);
370
+ const label = target?.kind === 'managed' ? 'the machine-wide install' : 'the account install';
371
+ add('warning', `Claude Code configuration ${dir}: both the plugin ${plugin.id} and ${label} reach this login; each event is delivered once, by whichever copy runs first` +
372
+ (other !== null && plugin.version !== null && other !== plugin.version ? `, and they run different versions (the plugin ${plugin.version}, ${label} ${other})` : '') +
373
+ `. One is enough: remove the plugin with \`claude plugin uninstall ${plugin.id}\`, or the hooks with \`noonsight uninstall${target?.kind === 'managed' ? ' --managed' : ` --account ${dir}`}\``);
374
+ }
375
+ /**
376
+ * Machine-wide settings that decide whether the installed hooks run at all. Claude Code merges the
377
+ * managed settings file and every drop-in file in alphabetical order; a later value wins.
378
+ */
379
+ function checkManagedPolicy(managed, env, add, installed) {
380
+ const { merged: policy, problems } = readManagedFiles(managed.managedDir ?? '');
381
+ for (const p of problems)
382
+ add('problem', `managed settings ${p.file} cannot be read as a JSON object (${p.message}); Claude Code refuses to start while it is so`);
383
+ if (policy.disableAllHooks === true)
384
+ add('problem', 'managed settings set disableAllHooks: Claude Code runs no hooks at all, noonsight included');
385
+ if (policy.allowManagedHooksOnly === true)
386
+ add('warning', 'managed settings set allowManagedHooksOnly: only the machine-wide install runs; account installs are ignored, and so is the plugin unless managed settings enable it');
387
+ // An MDM profile ranks above managed settings files, and Claude Code then ignores the files by default.
388
+ if (installed && process.platform === 'darwin') {
389
+ const root = env.NOONSIGHT_SYSTEM_ROOT ? path.resolve(env.NOONSIGHT_SYSTEM_ROOT) : '/';
390
+ const profile = path.join(root, 'Library', 'Managed Preferences', 'com.anthropic.claudecode.plist');
391
+ if (fs.existsSync(profile))
392
+ add('warning', `an MDM profile for Claude Code is present (${profile}); unless it sets managedSourcesBehavior to "merge", ` +
393
+ 'Claude Code ignores the managed settings files and the machine-wide hooks do not run. Use `noonsight install` (without --managed) instead.');
394
+ }
395
+ }
396
+ /**
397
+ * Server-managed settings, which Claude Code caches per login in its configuration directory. They
398
+ * outrank the managed settings files, and can turn hooks off for that login.
399
+ */
400
+ function checkRemotePolicy(dir, remote, accountHooks, managedInstalled, add) {
401
+ if (!remote?.deliversPolicy)
402
+ return;
403
+ const label = `Claude Code configuration ${dir}`;
404
+ if (remote.settings.disableAllHooks === true)
405
+ add('problem', `${label}: the server-managed settings of this login (${remote.file}) set disableAllHooks, so Claude Code runs no hooks there`);
406
+ else if (remote.settings.allowManagedHooksOnly === true && !(remote.merges && managedInstalled))
407
+ add('problem', `${label}: the server-managed settings of this login (${remote.file}) set allowManagedHooksOnly, ` +
408
+ 'so Claude Code runs only the hooks the organization delivers, and no noonsight install reaches it');
409
+ else if (accountHooks && !remote.merges)
410
+ add('ok', `${label}: this login receives server-managed settings, which shadow the managed settings files; the account install reaches it`);
411
+ }
412
+ /** Whether the opt-in watcher is on, whether it runs, and what it last logged. */
413
+ function checkWatcher(env, home, cli, add) {
414
+ let service;
415
+ try {
416
+ service = watchService(env, home);
417
+ }
418
+ catch (e) {
419
+ if (!(e instanceof WatchUnsupported))
420
+ throw e;
421
+ add('ok', `watcher: off (${e.message})`);
422
+ return;
423
+ }
424
+ let content;
425
+ try {
426
+ content = readServiceFile(service);
427
+ }
428
+ catch (e) {
429
+ add('warning', `watcher: cannot read ${service.file} (${e.message})`);
430
+ return;
431
+ }
432
+ if (content === null) {
433
+ if (isLoaded(manager.running(service)))
434
+ add('problem', `watcher: loaded without ${service.file}; run \`noonsight watch disable\` to stop it`);
435
+ else
436
+ add('ok', 'watcher: off; `noonsight watch enable` installs into each new Claude Code configuration directory as it appears');
437
+ return;
438
+ }
439
+ if (!isOurs(content)) {
440
+ add('warning', `watcher: ${service.file} is in noonsight's place but was not written by noonsight`);
441
+ return;
442
+ }
443
+ const running = manager.running(service);
444
+ if (running === 'off')
445
+ add('problem', `watcher: on in ${service.file}, but not running; run \`noonsight watch enable\` again`);
446
+ else if (running === 'loaded')
447
+ add('warning', `watcher: on in ${service.file}, but loaded without a running process; run \`noonsight watch enable\` again`);
448
+ else
449
+ add('ok', `watcher: on (${service.file})${running === null ? '; whether it runs now could not be checked' : ''}`);
450
+ if (content !== serviceContent(service, { node: process.execPath, cli }))
451
+ add('warning', `watcher: ${service.file} runs another copy of noonsight or another Node.js; run \`noonsight watch enable\` again to switch to this one`);
452
+ const last = lastLine(service.log);
453
+ if (last !== null)
454
+ add(/ (problem|noonsight): /.test(last) ? 'warning' : 'ok', `watcher log ${service.log}: ${last}`);
455
+ }
456
+ /** The last line of a small log file, or null when there is none. */
457
+ function lastLine(file) {
458
+ try {
459
+ const fd = fs.openSync(file, 'r');
460
+ try {
461
+ const size = fs.fstatSync(fd).size;
462
+ const length = Math.min(size, 16 * 1024);
463
+ const buffer = Buffer.alloc(length);
464
+ fs.readSync(fd, buffer, 0, length, size - length);
465
+ return buffer.toString('utf8').trimEnd().split('\n').pop() || null;
466
+ }
467
+ finally {
468
+ fs.closeSync(fd);
469
+ }
470
+ }
471
+ catch {
472
+ return null;
473
+ }
474
+ }
475
+ function checkClaude(env, add) {
476
+ const r = spawnSync('claude', ['--version'], {
477
+ encoding: 'utf8',
478
+ timeout: 10000,
479
+ env: { ...env, DISABLE_AUTOUPDATER: '1' },
480
+ });
481
+ if (r.error || r.status !== 0) {
482
+ add('warning', 'claude: not found on PATH, so its version was not checked');
483
+ return;
484
+ }
485
+ const found = /(\d+\.\d+\.\d+)/.exec(r.stdout)?.[1];
486
+ if (!found) {
487
+ add('warning', `claude: cannot read the version from "${r.stdout.trim()}"`);
488
+ return;
489
+ }
490
+ const short = CLAUDE_CODE_FLOORS.filter((f) => (compareVersions(found, f.version) ?? -1) < 0);
491
+ if (short.length)
492
+ for (const f of short)
493
+ add('problem', `claude: installed ${found}; ${f.feature} needs ${f.version} or later (upgrade: claude update)`);
494
+ else
495
+ add('ok', `claude: ${found}`);
496
+ const aliases = MODEL_ALIASES.reduce((v, a) => ((compareVersions(a.since, v) ?? 0) > 0 ? a.since : v), '0.0.0');
497
+ if ((compareVersions(found, aliases) ?? 0) < 0)
498
+ add('warning', `claude: installed ${found}; when a session without a reported model, such as \`claude -p\`, names it by an alias, ` +
499
+ `noonsight assumes what the aliases select from Claude Code ${aliases} on (upgrade: claude update)`);
500
+ }
501
+ /** An entry as check lists it: its event, with the tools it matches. */
502
+ function describeHandler(spec) {
503
+ const matcher = matcherOf(spec);
504
+ return matcher === undefined ? spec.event : `${spec.event} on ${matcher}`;
505
+ }
506
+ /** Why this account cannot use a file in the given mode, as an error code, or null when it can. */
507
+ function reach(file, mode) {
508
+ try {
509
+ fs.accessSync(file, mode);
510
+ return null;
511
+ }
512
+ catch (e) {
513
+ return e.code ?? 'EACCES';
514
+ }
515
+ }
516
+ function versionOf(node, cli) {
517
+ const r = spawnSync(node, [cli, '--version'], { encoding: 'utf8', timeout: 10000 });
518
+ const v = r.status === 0 ? r.stdout.trim() : '';
519
+ return /^\d+\.\d+\.\d+$/.test(v) ? v : null;
520
+ }
521
+ function hasHooks(file) {
522
+ try {
523
+ return findNoonsightHandlers(readSettings(file)).length > 0;
524
+ }
525
+ catch {
526
+ return false;
527
+ }
528
+ }
529
+ //# sourceMappingURL=check.js.map
@@ -0,0 +1,73 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import { runHook } from '../adapters/claude-code/hook.js';
4
+ import { INSTALL_KINDS } from '../state/installs.js';
5
+ import { recordNode } from '../state/node.js';
6
+ import { packageVersion } from '../version.js';
7
+ export const HOOK_USAGE = `usage: noonsight hook [--install managed|account|plugin] <session-start|model-switch|agent-call|subagent-start|agent-result|file-edit|agent-held>
8
+
9
+ The Claude Code hook adapter; the hook pointer written by \`noonsight install\`, or the plugin's launcher, runs it. It reads the
10
+ hook input on stdin, prints at most one JSON object, writes the decision log, and always exits 0.`;
11
+ /** Runs a hook event. Always returns 0: a hook never holds or fails the session. */
12
+ export function runHookCommand(args, env, out) {
13
+ let install = null;
14
+ const rest = [];
15
+ for (let i = 0; i < args.length; i++) {
16
+ const a = args[i];
17
+ if (a === '--install') {
18
+ const kind = args[++i];
19
+ install = INSTALL_KINDS.find((k) => k === kind) ?? null;
20
+ }
21
+ else if (a !== undefined)
22
+ rest.push(a);
23
+ }
24
+ if (rest.length !== 1)
25
+ return 0;
26
+ if (install === 'plugin')
27
+ recordNode(os.homedir(), process.execPath);
28
+ const stdout = runHook(rest[0] ?? '', readStdin(), {
29
+ env,
30
+ home: os.homedir(),
31
+ now: new Date(),
32
+ version: safeVersion(),
33
+ install,
34
+ parentPid: process.ppid,
35
+ });
36
+ if (stdout)
37
+ out(stdout);
38
+ return 0;
39
+ }
40
+ const RETRY_WAIT = new Int32Array(new SharedArrayBuffer(4));
41
+ /** The whole hook input. A pipe that is not yet written makes a read fail with EAGAIN, so it is retried. */
42
+ function readStdin() {
43
+ // A terminal would block the read; hooks always get a pipe.
44
+ if (process.stdin.isTTY)
45
+ return '';
46
+ const chunks = [];
47
+ const chunk = Buffer.alloc(64 * 1024);
48
+ for (;;) {
49
+ let n;
50
+ try {
51
+ n = fs.readSync(0, chunk, 0, chunk.length, null);
52
+ }
53
+ catch (e) {
54
+ if (e.code === 'EAGAIN') {
55
+ Atomics.wait(RETRY_WAIT, 0, 0, 1);
56
+ continue;
57
+ }
58
+ return '';
59
+ }
60
+ if (n === 0)
61
+ return Buffer.concat(chunks).toString('utf8');
62
+ chunks.push(Buffer.from(chunk.subarray(0, n)));
63
+ }
64
+ }
65
+ function safeVersion() {
66
+ try {
67
+ return packageVersion();
68
+ }
69
+ catch {
70
+ return 'unknown';
71
+ }
72
+ }
73
+ //# sourceMappingURL=hook.js.map
@@ -0,0 +1,29 @@
1
+ // noonsight init: write a first configuration file from the preset, declaring every model the preset
2
+ // has rules for with "use": "preset". It never replaces an existing file, and it reads only the
3
+ // installed preset.
4
+ import { writeConfig } from '../config/create.js';
5
+ import { configPath } from '../config/paths.js';
6
+ import { UsageError } from './usage.js';
7
+ export const INIT_USAGE = `usage: noonsight init
8
+
9
+ Create the configuration file from the preset: every model the preset has rules for is declared
10
+ with "use": "preset", and so receives the preset's rules that are on by default. The file goes to
11
+ $NOONSIGHT_CONFIG, else ~/.config/noonsight/noonsight.json; an existing file is never replaced.
12
+ Exits 0 when the file was written, 1 when one already exists, and 2 for a usage error or a
13
+ refused preset.`;
14
+ export function runInit(args, env, io) {
15
+ if (args.length)
16
+ throw new UsageError(`unexpected argument "${args[0]}"`, INIT_USAGE);
17
+ const file = configPath(env);
18
+ const written = writeConfig(env);
19
+ if (written === null) {
20
+ io.err(`noonsight: ${file} already exists, and init never replaces it; edit it, or move it away and run \`noonsight init\` again`);
21
+ return 1;
22
+ }
23
+ io.out([
24
+ ...written,
25
+ 'Next: `noonsight models` lists every rule with its source, effect and cost; `noonsight install` adds the hooks; `noonsight check` checks it all.',
26
+ ].join('\n'));
27
+ return 0;
28
+ }
29
+ //# sourceMappingURL=init.js.map