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,252 @@
1
+ // The launcher, `noonsight run`: it starts Claude Code with the rules for the session's model in the
2
+ // system prompt, through --append-system-prompt-file, and passes every other argument unchanged.
3
+ //
4
+ // It decides exactly as the SessionStart hook does for a session that reports no model: the model
5
+ // Claude Code will start with, read from the arguments it is about to pass, ANTHROPIC_MODEL and the
6
+ // settings files (launch.ts); the scope from NOONSIGHT_SCOPE; the place from session.unattended_when_env
7
+ // and, since the session it starts reports a headless run to its hooks only once it runs, from -p or
8
+ // --print on the command line it is about to pass.
9
+ // So when the hooks are installed too, SessionStart finds the same rules already in the system prompt
10
+ // and does not deliver them a second time (launcherPrompt below).
11
+ //
12
+ // Without NOONSIGHT_SCOPE, the scope comes from the task text, --task or the prompt after -p, through
13
+ // the scopes' matchers or, with classifier.mode on, the classifier (classifier.ts), and is passed on
14
+ // to the session as NOONSIGHT_SCOPE so its hooks decide alike.
15
+ // NOONSIGHT_SCOPE_VIA says where the scope came from: a noonsight run started inside that session reads an
16
+ // inherited scope that was inferred from the outer task as no scope, and takes one from its own task.
17
+ // With routing on for the launcher, the scope's row adds --model and --effort before anything else is
18
+ // decided, so the rules are the routed model's.
19
+ //
20
+ // Claude Code keeps only the last --append-system-prompt-file it is given, while an
21
+ // --append-system-prompt adds to it. So a file someone else passes is merged into the launcher's
22
+ // file, ahead of the rules, and an --append-system-prompt is left as it is.
23
+ import { createHash } from 'node:crypto';
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { resolve, scopeChangesRules } from '../../core/resolve.js';
27
+ import { route, routeReadsScope } from '../../core/route.js';
28
+ import { sessionPlace, sessionScope, SCOPE_ENV, taskScope, taskText } from '../../core/scope.js';
29
+ import { classifiedScope } from './classifier.js';
30
+ import { launchFields, launchModelFrom, modelArgument, optionCandidates } from './launch.js';
31
+ import { launcherTranslation, routeFields } from './routing.js';
32
+ import { choiceFields, decisionFields } from './subagents.js';
33
+ /** Names, for the session and its hooks, the system prompt file the launcher passed. */
34
+ export const LAUNCH_FILE_ENV = 'NOONSIGHT_LAUNCH_FILE';
35
+ /** Where the launcher's NOONSIGHT_SCOPE came from: explicit (--scope or an explicit NOONSIGHT_SCOPE) or inferred (the task text). */
36
+ export const SCOPE_VIA_ENV = 'NOONSIGHT_SCOPE_VIA';
37
+ export const APPEND_FILE_OPTION = '--append-system-prompt-file';
38
+ /** The subdirectory of the state directory that holds the launcher's system prompt files. */
39
+ export const LAUNCH_DIR = 'launch';
40
+ /**
41
+ * What the launcher adds when it adds no rules: the scope with where it came from, and no system prompt
42
+ * file inherited from an outer launch. Without a scope of its own, a scope an outer launcher inferred
43
+ * from its task is removed, while an explicit one is kept.
44
+ */
45
+ export function passThrough(args, scope, env, via = 'explicit') {
46
+ const scopeEnv = scope !== null
47
+ ? { [SCOPE_ENV]: scope, [SCOPE_VIA_ENV]: via }
48
+ : env[SCOPE_VIA_ENV] === 'inferred'
49
+ ? { [SCOPE_ENV]: undefined, [SCOPE_VIA_ENV]: undefined }
50
+ : {};
51
+ return { args: [...args], env: { [LAUNCH_FILE_ENV]: undefined, ...scopeEnv } };
52
+ }
53
+ /** Decide what the launcher adds to a claude command line. Reads only local files, and may ask the classifier; writes nothing. */
54
+ export function planLaunch(config, configFile, req) {
55
+ const given = { args: req.args, exact: true };
56
+ const held = modelArgument(given, req.env) !== null ? { reason: 'explicit-model', explicit: true } : null;
57
+ const explicitEnv = applyEnv(req.env, passThrough(req.args, req.scope, req.env).env);
58
+ const chosen = launchScope(config, explicitEnv, req.task, given);
59
+ const taskInput = chosen.source === 'env' ? null : (req.task ?? printPrompt(req.args));
60
+ const classified = classifiedScope(config, {
61
+ chosen,
62
+ text: taskInput !== null ? taskText(null, taskInput).text : null,
63
+ matters: () => {
64
+ if (routeReadsScope(config, { target: 'launcher', env: req.env, held }))
65
+ return true;
66
+ const before = launchModelFrom(given, { env: explicitEnv, home: req.home, cwd: req.cwd });
67
+ return before.kind !== 'found' || scopeChangesRules(config, before.model, sessionPlace(config, explicitEnv, printMode(req.args)).place);
68
+ },
69
+ env: req.env,
70
+ });
71
+ const scope = classified.scope;
72
+ const routed = route(config, {
73
+ target: 'launcher',
74
+ scope: scope.scope,
75
+ env: req.env,
76
+ held,
77
+ explicitEffort: optionCandidates(given, EFFORT_OPTION).length > 0,
78
+ translate: launcherTranslation(req.env),
79
+ });
80
+ const args = routedArgs(req.args, routed);
81
+ // A scope from the task text, by a matcher or the classifier, is passed on, so the session's hooks decide with the same scope.
82
+ const inferred = scope.source === 'task-text' || scope.source === 'classifier';
83
+ const base = inferred ? passThrough(args, scope.scope, req.env, 'inferred') : passThrough(args, req.scope, req.env);
84
+ const env = applyEnv(req.env, base.env);
85
+ const place = sessionPlace(config, env, printMode(args));
86
+ const cmd = { args, exact: true };
87
+ const launch = launchModelFrom(cmd, { env, home: req.home, cwd: req.cwd });
88
+ const decision = resolve(config, { model: launch.kind === 'found' ? launch.model : null, scope: scope.scope, place: place.place });
89
+ const fields = {
90
+ ...decisionFields(decision),
91
+ ...choiceFields(scope, place),
92
+ ...classified.fields,
93
+ model_source: launch.kind === 'found' ? launch.source : null,
94
+ ...launchFields(launch),
95
+ ...routeFields(routed, env),
96
+ };
97
+ const messages = [
98
+ ...(classified.failure !== null ? [`noonsight: the classifier could not place the task (${classified.failure}), so the session has no scope.`] : []),
99
+ ...undeclaredMessages(decision, configFile),
100
+ ];
101
+ const nothing = (extra = {}, more = []) => ({
102
+ ...base,
103
+ fallback: base,
104
+ file: null,
105
+ record: { ...fields, ...extra, delivered: 'nothing', warned: messages.length + more.length > 0 },
106
+ messages: [...messages, ...more],
107
+ });
108
+ if (decision.status !== 'matched')
109
+ return nothing();
110
+ // The file someone else gave: the last one is the one Claude Code would have used.
111
+ const theirs = optionCandidates(cmd, APPEND_FILE_OPTION)[0];
112
+ let prefix = '';
113
+ if (theirs !== undefined) {
114
+ try {
115
+ prefix = fs.readFileSync(path.resolve(req.cwd, theirs), 'utf8').replace(/\s+$/, '');
116
+ }
117
+ catch (e) {
118
+ const why = e.code ?? String(e);
119
+ return nothing({ merge_failed: theirs }, [
120
+ `noonsight: could not read ${theirs}, given to ${APPEND_FILE_OPTION} (${why}), so noonsight run added no rules to the system prompt.`,
121
+ ]);
122
+ }
123
+ }
124
+ const content = `${prefix ? `${prefix}\n\n` : ''}${decision.text}\n`;
125
+ const file = path.join(req.state, LAUNCH_DIR, `${createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16)}.md`);
126
+ return {
127
+ args: [APPEND_FILE_OPTION, file, ...withoutOption(args, APPEND_FILE_OPTION)],
128
+ env: { ...base.env, [LAUNCH_FILE_ENV]: file },
129
+ fallback: base,
130
+ file: { path: file, content },
131
+ record: { ...fields, delivered: 'system-prompt', launch_file: file, ...(theirs !== undefined ? { merged_file: theirs } : {}), warned: messages.length > 0 },
132
+ messages,
133
+ };
134
+ }
135
+ const MODEL_OPTION = '--model';
136
+ const EFFORT_OPTION = '--effort';
137
+ /**
138
+ * The session's scope: NOONSIGHT_SCOPE (from --scope or an explicit one in the environment), else the scope whose matcher
139
+ * matches earliest in the task text, --task or the prompt after -p.
140
+ */
141
+ function launchScope(config, env, task, cmd) {
142
+ const explicit = sessionScope(env);
143
+ if (explicit.scope !== null)
144
+ return explicit;
145
+ const text = task ?? printPrompt(cmd.args);
146
+ return text !== null ? taskScope(config, taskText(null, text).text) : explicit;
147
+ }
148
+ /** Whether a claude command line runs headless: it gives -p or --print before a "--" that ends the options. */
149
+ export function printMode(args) {
150
+ for (const a of args) {
151
+ if (a === '--')
152
+ return false;
153
+ if (a === '-p' || a === '--print')
154
+ return true;
155
+ }
156
+ return false;
157
+ }
158
+ /**
159
+ * The prompt of `claude -p "<prompt>"`: the argument right after -p or --print, when it is not an
160
+ * option. A prompt written elsewhere on the command line, or given on standard input, is not read.
161
+ */
162
+ export function printPrompt(args) {
163
+ for (let i = 0; i < args.length; i++) {
164
+ const a = args[i] ?? '';
165
+ if (a === '--')
166
+ return null;
167
+ if (a === '-p' || a === '--print') {
168
+ const next = args[i + 1];
169
+ return next !== undefined && !next.startsWith('-') && next.trim() !== '' ? next : null;
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+ /**
175
+ * The claude arguments with a route applied: --model and --effort first, replacing any the command line
176
+ * gave, which happens only when routing.respect_explicit is false or the effort is not kept.
177
+ */
178
+ function routedArgs(args, routed) {
179
+ if (routed.routing !== 'routed')
180
+ return [...args];
181
+ let rest = withoutOption(args, MODEL_OPTION);
182
+ const added = [MODEL_OPTION, routed.value];
183
+ if (routed.effort !== undefined) {
184
+ rest = withoutOption(rest, EFFORT_OPTION);
185
+ added.push(EFFORT_OPTION, routed.effort);
186
+ }
187
+ return [...added, ...rest];
188
+ }
189
+ /** The arguments with every value of an option taken out, up to a "--" that ends the options. */
190
+ export function withoutOption(args, name) {
191
+ const kept = [];
192
+ for (let i = 0; i < args.length; i++) {
193
+ const a = args[i] ?? '';
194
+ if (a === '--') {
195
+ kept.push(...args.slice(i));
196
+ break;
197
+ }
198
+ if (a === name)
199
+ i++;
200
+ else if (!a.startsWith(`${name}=`))
201
+ kept.push(a);
202
+ }
203
+ return kept;
204
+ }
205
+ export function applyEnv(env, changes) {
206
+ const out = {};
207
+ for (const [k, v] of Object.entries(env))
208
+ if (v !== undefined)
209
+ out[k] = v;
210
+ for (const [k, v] of Object.entries(changes)) {
211
+ if (v === undefined)
212
+ delete out[k];
213
+ else
214
+ out[k] = v;
215
+ }
216
+ return out;
217
+ }
218
+ function undeclaredMessages(decision, file) {
219
+ // A session whose model the launcher cannot tell is left to the hooks, which see what Claude Code reports.
220
+ if (decision.status !== 'undeclared' || decision.warning === undefined || decision.reason !== 'no-entry')
221
+ return [];
222
+ return [
223
+ `noonsight: ${decision.model} is not declared in ${file}, so noonsight run added no rules. ` +
224
+ 'Declare it under "models" (with "use": "none" if it needs no rules).',
225
+ ];
226
+ }
227
+ /**
228
+ * The text noonsight run put in this session's system prompt, or null when it put none. The variable
229
+ * alone is not enough: a claude started from inside a launched session inherits it without the
230
+ * option, so the Claude Code command line must pass the same file.
231
+ */
232
+ export function launcherPrompt(env, commandLine) {
233
+ const file = env[LAUNCH_FILE_ENV];
234
+ if (!file)
235
+ return null;
236
+ const cmd = commandLine();
237
+ if (cmd === null)
238
+ return null;
239
+ const given = optionCandidates(cmd, APPEND_FILE_OPTION);
240
+ if (given.length !== 1 || given[0] !== file)
241
+ return null;
242
+ let content;
243
+ try {
244
+ content = fs.readFileSync(file, 'utf8');
245
+ }
246
+ catch {
247
+ return null;
248
+ }
249
+ const models = [...content.matchAll(/<noonsight-rules model="([^"]*)"/g)];
250
+ return { file, content, model: models.at(-1)?.[1] || null };
251
+ }
252
+ //# sourceMappingURL=launcher.js.map
@@ -0,0 +1,115 @@
1
+ // Where an install writes. The machine-wide paths come from Claude Code's documentation of
2
+ // file-based managed settings (https://code.claude.com/docs/en/managed-settings): Claude Code reads
3
+ // managed-settings.json and every *.json file in managed-settings.d/ from one system directory per
4
+ // operating system, and merges them.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { dataDir } from '../../config/paths.js';
9
+ import { POINTER_NAME } from './settings.js';
10
+ /** noonsight's own file in the managed settings drop-in directory. */
11
+ export const DROP_IN_NAME = 'noonsight.json';
12
+ const SYSTEM_DIRS = {
13
+ darwin: { claudeCode: '/Library/Application Support/ClaudeCode', noonsight: '/Library/Application Support/noonsight' },
14
+ linux: { claudeCode: '/etc/claude-code', noonsight: '/usr/local/lib/noonsight' },
15
+ };
16
+ /** Claude Code's managed settings directory on Windows; noonsight does not install there yet. */
17
+ export const WINDOWS_MANAGED_DIR = 'C:\\Program Files\\ClaudeCode';
18
+ export class UnsupportedPlatformError extends Error {
19
+ platform;
20
+ constructor(platform) {
21
+ super(platform === 'win32'
22
+ ? `installing on Windows is not supported yet. Claude Code reads machine-wide settings from ${WINDOWS_MANAGED_DIR}, ` +
23
+ `but the noonsight hook pointer is a POSIX shell script that has not been verified there.`
24
+ : `installing on ${platform} is not supported; noonsight knows Claude Code's managed settings directory on macOS and Linux only.`);
25
+ this.platform = platform;
26
+ this.name = 'UnsupportedPlatformError';
27
+ }
28
+ }
29
+ /**
30
+ * The machine-wide install. NOONSIGHT_SYSTEM_ROOT stands in for "/" so tests can install into a
31
+ * temporary directory; it is not meant for real installs.
32
+ */
33
+ export function managedTarget(env, platform = process.platform) {
34
+ const dirs = SYSTEM_DIRS[platform];
35
+ if (!dirs)
36
+ throw new UnsupportedPlatformError(platform);
37
+ const root = env.NOONSIGHT_SYSTEM_ROOT ? path.resolve(env.NOONSIGHT_SYSTEM_ROOT) : null;
38
+ const system = (p) => (root ? path.join(root, p) : p);
39
+ const managedDir = system(dirs.claudeCode);
40
+ return {
41
+ kind: 'managed',
42
+ managedDir,
43
+ settingsFile: path.join(managedDir, 'managed-settings.d', DROP_IN_NAME),
44
+ pointer: path.join(system(dirs.noonsight), POINTER_NAME),
45
+ };
46
+ }
47
+ /** A per-account install into one Claude Code configuration directory, such as ~/.claude. */
48
+ export function accountTarget(configDir, home = os.homedir()) {
49
+ const dir = path.resolve(expandHome(configDir, home));
50
+ return { kind: 'account', configDir: dir, settingsFile: path.join(dir, 'settings.json'), pointer: path.join(dataDir(home), POINTER_NAME) };
51
+ }
52
+ /**
53
+ * The file Claude Code keeps in a configuration directory it was started with through
54
+ * CLAUDE_CONFIG_DIR (the default directory keeps it in the home directory instead).
55
+ */
56
+ export const CONFIG_MARKER = '.claude.json';
57
+ /**
58
+ * Every Claude Code configuration directory of this account that exists, each once: ~/.claude, the
59
+ * directory in CLAUDE_CONFIG_DIR, every directory directly in the home directory that holds a Claude
60
+ * Code configuration (such as ~/.claude-work, made for a second login), and the extra directories
61
+ * given, such as the ones noonsight installed into before. Each login keeps its own settings in its
62
+ * own directory, so these are the places a per-account hook must be to reach every login.
63
+ */
64
+ export function discoverConfigDirs(env, home = os.homedir(), extra = []) {
65
+ const candidates = [path.join(home, '.claude')];
66
+ if (env.CLAUDE_CONFIG_DIR)
67
+ candidates.push(path.resolve(expandHome(env.CLAUDE_CONFIG_DIR, home)));
68
+ let names = [];
69
+ try {
70
+ names = fs.readdirSync(home).sort();
71
+ }
72
+ catch {
73
+ // No readable home directory.
74
+ }
75
+ for (const name of names) {
76
+ const dir = path.join(home, name);
77
+ if (isFile(path.join(dir, CONFIG_MARKER)))
78
+ candidates.push(dir);
79
+ }
80
+ candidates.push(...extra.map((d) => path.resolve(d)));
81
+ const seen = new Set();
82
+ const found = [];
83
+ for (const dir of candidates) {
84
+ let real;
85
+ try {
86
+ if (!fs.statSync(dir).isDirectory())
87
+ continue;
88
+ real = fs.realpathSync(dir);
89
+ }
90
+ catch {
91
+ continue;
92
+ }
93
+ if (seen.has(real))
94
+ continue;
95
+ seen.add(real);
96
+ found.push(dir);
97
+ }
98
+ return found;
99
+ }
100
+ function isFile(file) {
101
+ try {
102
+ return fs.statSync(file).isFile();
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ /** The Claude Code configuration directory this shell uses, for messages that suggest --account. */
109
+ export function defaultAccountDir(env, home = os.homedir()) {
110
+ return env.CLAUDE_CONFIG_DIR ? path.resolve(env.CLAUDE_CONFIG_DIR) : path.join(home, '.claude');
111
+ }
112
+ function expandHome(p, home) {
113
+ return p === '~' ? home : p.startsWith('~/') ? path.join(home, p.slice(2)) : p;
114
+ }
115
+ //# sourceMappingURL=locations.js.map
@@ -0,0 +1,75 @@
1
+ // Claude Code's managed settings, as far as noonsight needs them: whether the managed settings files
2
+ // apply to a login, and the values they set.
3
+ //
4
+ // Claude Code ranks its managed sources (https://code.claude.com/docs/en/managed-settings, "How
5
+ // Claude Code combines managed sources"): server-managed settings from claude.ai or a gateway first,
6
+ // then an MDM profile, then the managed settings files. By default ("first-wins") it applies only the
7
+ // highest-ranked source that delivers at least one policy key and ignores the rest, unless that
8
+ // source sets managedSourcesBehavior to "merge". Server-managed settings are cached per login in the
9
+ // Claude Code configuration directory, as remote-settings.json
10
+ // (https://code.claude.com/docs/en/server-managed-settings, "Invalid entries in delivered settings").
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { isObject } from './settings.js';
14
+ /** Keys that do not count as a policy: a source holding only these does not shadow the sources below it. */
15
+ const CONTROL_KEYS = new Set(['managedSourcesBehavior', 'wslInheritsWindowsSettings']);
16
+ /** The cache file of server-managed settings in a Claude Code configuration directory. */
17
+ export const REMOTE_SETTINGS_FILE = 'remote-settings.json';
18
+ /** The server-managed settings cached for the login that uses this configuration directory, or null. */
19
+ export function readRemoteSettings(configDir) {
20
+ const file = path.join(configDir, REMOTE_SETTINGS_FILE);
21
+ let value;
22
+ try {
23
+ value = JSON.parse(fs.readFileSync(file, 'utf8'));
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ if (!isObject(value))
29
+ return null;
30
+ return {
31
+ file,
32
+ settings: value,
33
+ deliversPolicy: Object.keys(value).some((k) => !CONTROL_KEYS.has(k)),
34
+ merges: value.managedSourcesBehavior === 'merge',
35
+ };
36
+ }
37
+ /** Whether the managed settings files reach sessions of this configuration directory's login. */
38
+ export function managedFilesApply(remote) {
39
+ return remote === null || !remote.deliversPolicy || remote.merges;
40
+ }
41
+ /** managed-settings.json, then every *.json file in managed-settings.d/ in alphabetical order. */
42
+ export function readManagedFiles(managedDir) {
43
+ const files = [path.join(managedDir, 'managed-settings.json')];
44
+ try {
45
+ const dropIns = path.join(managedDir, 'managed-settings.d');
46
+ files.push(...fs
47
+ .readdirSync(dropIns)
48
+ .filter((n) => n.endsWith('.json') && !n.startsWith('.'))
49
+ .sort()
50
+ .map((n) => path.join(dropIns, n)));
51
+ }
52
+ catch {
53
+ // No drop-in directory.
54
+ }
55
+ const merged = {};
56
+ const origins = {};
57
+ const problems = [];
58
+ for (const file of files) {
59
+ if (!fs.existsSync(file))
60
+ continue;
61
+ try {
62
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
63
+ if (!isObject(value))
64
+ throw new Error('not a JSON object');
65
+ Object.assign(merged, value);
66
+ for (const key of Object.keys(value))
67
+ origins[key] = file;
68
+ }
69
+ catch (e) {
70
+ problems.push({ file, message: e.message });
71
+ }
72
+ }
73
+ return { merged, origins, problems };
74
+ }
75
+ //# sourceMappingURL=managed.js.map
@@ -0,0 +1,88 @@
1
+ // The files that make the npm package a Claude Code plugin too, generated so they cannot drift from the
2
+ // code: the hook entries from HOOK_HANDLERS, the version from package.json, one skill per command a person
3
+ // runs inside a session. `npm run plugin-files` writes them, and a test holds the committed files to this.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { PACKAGE_ROOT } from '../../config/paths.js';
8
+ import { CLAUDE_CODE_FLOORS } from './compat.js';
9
+ import { PLUGIN_NAME } from './plugins.js';
10
+ import { HOOK_HANDLERS, HOOK_TIMEOUT_SECONDS, matcherOf } from './settings.js';
11
+ /** The plugin's launcher, relative to its folder; run through /bin/sh, so its executable bit does not matter. */
12
+ export const LAUNCHER = 'scripts/noonsight';
13
+ const LAUNCHER_PATH = `\${CLAUDE_PLUGIN_ROOT}/${LAUNCHER}`;
14
+ const DESCRIPTION = 'Hands every Claude Code session and subagent the rules for the model it actually runs on.';
15
+ const SKILLS = {
16
+ accept: { description: 'Accept the installed preset version of noonsight: list what it changes, then record it in the configuration.', commands: ['accept'] },
17
+ check: { description: 'Check the noonsight configuration, what installs its hooks, and the last decision.', commands: ['check'] },
18
+ models: { description: 'List the models noonsight declares and their rules, with source and cost.', commands: ['models'] },
19
+ report: { description: 'Report from the noonsight decision log how often each rule was delivered, and to which models, scopes and places.', commands: ['report'] },
20
+ resolve: { description: 'Show the rules noonsight gives a model, in a scope and a place.', hint: '<model> [scope] [place]', commands: ['resolve $ARGUMENTS'] },
21
+ setup: { description: 'Write the noonsight configuration from the preset when there is none, then check everything.', commands: ['init', 'check'] },
22
+ trust: { description: "Apply this project's noonsight configuration to the sessions that run in it.", hint: '[<dir>]', commands: ['trust $ARGUMENTS'] },
23
+ untrust: { description: "Stop applying this project's noonsight configuration.", hint: '[<dir>]', commands: ['untrust $ARGUMENTS'] },
24
+ };
25
+ function skill(name) {
26
+ const s = SKILLS[name];
27
+ const line = (command) => `/bin/sh "${LAUNCHER_PATH}" ${command}`;
28
+ return [
29
+ '---',
30
+ `description: ${JSON.stringify(s.description)}`,
31
+ ...(s.hint !== undefined ? [`argument-hint: ${JSON.stringify(s.hint)}`] : []),
32
+ 'disable-model-invocation: true',
33
+ `allowed-tools: ${JSON.stringify(s.commands.map((c) => `Bash(${line(c.split(' ')[0])}:*)`).join(', '))}`,
34
+ '---',
35
+ '',
36
+ 'Show the output below to the person as it is, with nothing added.',
37
+ '',
38
+ ...s.commands.flatMap((c) => ['```!', `${line(c)} 2>&1 || true`, '```', '']),
39
+ ].join('\n');
40
+ }
41
+ function json(value) {
42
+ return `${JSON.stringify(value, null, 2)}\n`;
43
+ }
44
+ /** Every generated file, by its path in the package. */
45
+ export function pluginFiles(version) {
46
+ const hooks = {};
47
+ for (const spec of HOOK_HANDLERS) {
48
+ const matcher = matcherOf(spec);
49
+ (hooks[spec.event] ??= []).push({
50
+ ...(matcher !== undefined ? { matcher } : {}),
51
+ hooks: [{ type: 'command', command: '/bin/sh', args: [LAUNCHER_PATH, 'hook', spec.arg], timeout: HOOK_TIMEOUT_SECONDS }],
52
+ });
53
+ }
54
+ return {
55
+ '.claude-plugin/plugin.json': json({
56
+ name: PLUGIN_NAME,
57
+ version,
58
+ description: DESCRIPTION,
59
+ author: { name: 'Bruno Santi' },
60
+ homepage: 'https://github.com/bpsanti/noonsight#readme',
61
+ repository: 'https://github.com/bpsanti/noonsight',
62
+ license: 'MIT',
63
+ engines: { 'claude-code': `>=${CLAUDE_CODE_FLOORS[0]?.version ?? '0.0.0'}` },
64
+ }),
65
+ // The plugin is the npm package itself, by its exact version.
66
+ '.claude-plugin/marketplace.json': json({
67
+ name: PLUGIN_NAME,
68
+ owner: { name: 'Bruno Santi' },
69
+ description: 'The rules for the model each session runs on.',
70
+ plugins: [{ name: PLUGIN_NAME, source: { source: 'npm', package: 'noonsight', version }, description: DESCRIPTION, category: 'productivity' }],
71
+ }),
72
+ 'hooks/hooks.json': json({ hooks }),
73
+ ...Object.fromEntries(Object.keys(SKILLS).map((name) => [`skills/${name}/SKILL.md`, skill(name)])),
74
+ };
75
+ }
76
+ /** Write the generated files; the skills folder holds nothing else. */
77
+ function write() {
78
+ const { version } = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
79
+ fs.rmSync(path.join(PACKAGE_ROOT, 'skills'), { recursive: true, force: true });
80
+ for (const [rel, content] of Object.entries(pluginFiles(version))) {
81
+ const file = path.join(PACKAGE_ROOT, rel);
82
+ fs.mkdirSync(path.dirname(file), { recursive: true });
83
+ fs.writeFileSync(file, content);
84
+ }
85
+ }
86
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url))
87
+ write();
88
+ //# sourceMappingURL=plugin-files.js.map
@@ -0,0 +1,117 @@
1
+ // The plugins Claude Code installed from a marketplace, as its own files record them
2
+ // (https://code.claude.com/docs/en/plugins/loading): plugins/installed_plugins.json in the configuration
3
+ // directory lists each install, and enabledPlugins in the settings says which are on. noonsight reads
4
+ // them to find subagent definitions and to find itself installed as a plugin.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { PACKAGE_ROOT } from '../../config/paths.js';
8
+ import { optionValues, readObject, remoteSettingsApply, safeManagedDir, settingSources, settingsArgument } from './launch.js';
9
+ import { managedFilesApply, readManagedFiles, readRemoteSettings } from './managed.js';
10
+ import { isObject } from './settings.js';
11
+ /** The name noonsight's plugin and marketplace have. */
12
+ export const PLUGIN_NAME = 'noonsight';
13
+ /**
14
+ * The plugins installed from a marketplace that apply to the project. installed_plugins.json lists each
15
+ * install as plugin@marketplace with its scope and folder; a project or local install applies only to
16
+ * its own project.
17
+ */
18
+ export function installedPlugins(places) {
19
+ const registry = readObject(path.join(places.configDir, 'plugins', 'installed_plugins.json'));
20
+ const plugins = registry !== null && isObject(registry.plugins) ? registry.plugins : null;
21
+ if (plugins === null)
22
+ return [];
23
+ const project = places.projectDir === null ? null : realpath(path.resolve(places.projectDir));
24
+ const found = [];
25
+ for (const [id, installs] of Object.entries(plugins)) {
26
+ if (!Array.isArray(installs))
27
+ continue;
28
+ const name = id.split('@')[0] ?? id;
29
+ for (const install of installs) {
30
+ if (!isObject(install) || typeof install.installPath !== 'string')
31
+ continue;
32
+ const scope = typeof install.scope === 'string' ? install.scope : 'user';
33
+ if ((scope === 'project' || scope === 'local') && (typeof install.projectPath !== 'string' || realpath(install.projectPath) !== project))
34
+ continue;
35
+ found.push({ id, name, dir: install.installPath, scope });
36
+ }
37
+ }
38
+ return found;
39
+ }
40
+ /**
41
+ * The plugins the settings turn on or off: enabledPlugins is read from the managed settings, the user's,
42
+ * the project's, its local settings and --settings, in that order, a later value winning.
43
+ */
44
+ export function enabledPlugins(places, cmd) {
45
+ const layers = [];
46
+ const remote = remoteSettingsApply(places.env) ? readRemoteSettings(places.configDir) : null;
47
+ if (remote?.deliversPolicy)
48
+ layers.push(remote.settings);
49
+ if (managedFilesApply(remote)) {
50
+ const dir = safeManagedDir(places.env);
51
+ if (dir !== null)
52
+ layers.push(readManagedFiles(dir).merged);
53
+ }
54
+ const s = settingSources(cmd);
55
+ const reads = (source) => s.kind !== 'listed' || s.sources.has(source);
56
+ if (reads('user'))
57
+ layers.push(readObject(path.join(places.configDir, 'settings.json')));
58
+ if (places.projectDir !== null) {
59
+ if (reads('project'))
60
+ layers.push(readObject(path.join(places.projectDir, '.claude', 'settings.json')));
61
+ if (reads('local'))
62
+ layers.push(readObject(path.join(places.projectDir, '.claude', 'settings.local.json')));
63
+ }
64
+ if (cmd !== null)
65
+ for (const v of optionValues(cmd, '--settings').slice(-1))
66
+ layers.push(settingsArgument(v));
67
+ const enabled = new Map();
68
+ for (const layer of layers) {
69
+ const e = layer !== null && isObject(layer.enabledPlugins) ? layer.enabledPlugins : null;
70
+ if (e !== null)
71
+ for (const [id, on] of Object.entries(e))
72
+ if (typeof on === 'boolean')
73
+ enabled.set(id, on);
74
+ }
75
+ return enabled;
76
+ }
77
+ /** noonsight's plugin in a login's configuration directory, once per marketplace it comes from. */
78
+ export function noonsightPlugins(places) {
79
+ const enabled = enabledPlugins(places, null);
80
+ const installed = installedPlugins(places).filter((p) => p.name === PLUGIN_NAME);
81
+ const found = installed.map((p) => ({
82
+ id: p.id,
83
+ dir: p.dir,
84
+ scope: p.scope,
85
+ enabled: enabled.get(p.id) === true,
86
+ version: pluginVersion(p.dir),
87
+ }));
88
+ for (const [id, on] of enabled)
89
+ if (on && id.startsWith(`${PLUGIN_NAME}@`) && !installed.some((p) => p.id === id))
90
+ found.push({ id, dir: null, scope: null, enabled: true, version: null });
91
+ return found;
92
+ }
93
+ function pluginVersion(dir) {
94
+ if (!fs.existsSync(path.join(dir, 'dist', 'src', 'cli.js')))
95
+ return null;
96
+ const manifest = readObject(path.join(dir, '.claude-plugin', 'plugin.json'));
97
+ return typeof manifest?.version === 'string' ? manifest.version : null;
98
+ }
99
+ /**
100
+ * Whether this copy of noonsight is the one a plugin runs: Claude Code named its folder to the process
101
+ * (a hook or a skill of the plugin), or it lies in a plugin cache. Claude Code deletes such a folder some
102
+ * time after an update, so nothing that stays may point at it.
103
+ */
104
+ export function runsFromPlugin(env, root = PACKAGE_ROOT) {
105
+ if (env.CLAUDE_PLUGIN_ROOT && realpath(env.CLAUDE_PLUGIN_ROOT) === realpath(root))
106
+ return true;
107
+ return /[\\/]plugins[\\/]cache[\\/][^\\/]+[\\/][^\\/]+[\\/][^\\/]+[\\/]?$/.test(realpath(root)) && fs.existsSync(path.join(root, '.claude-plugin', 'plugin.json'));
108
+ }
109
+ function realpath(p) {
110
+ try {
111
+ return fs.realpathSync(p);
112
+ }
113
+ catch {
114
+ return p;
115
+ }
116
+ }
117
+ //# sourceMappingURL=plugins.js.map