noonsight 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/.claude-plugin/marketplace.json +19 -0
  2. package/.claude-plugin/plugin.json +14 -0
  3. package/README.md +271 -9
  4. package/dist/src/adapters/claude-code/classifier.js +138 -0
  5. package/dist/src/adapters/claude-code/code-edit.js +108 -0
  6. package/dist/src/adapters/claude-code/compat.js +31 -0
  7. package/dist/src/adapters/claude-code/definitions.js +347 -0
  8. package/dist/src/adapters/claude-code/fork.js +132 -0
  9. package/dist/src/adapters/claude-code/hook.js +652 -0
  10. package/dist/src/adapters/claude-code/install.js +186 -0
  11. package/dist/src/adapters/claude-code/launch.js +270 -0
  12. package/dist/src/adapters/claude-code/launcher.js +252 -0
  13. package/dist/src/adapters/claude-code/locations.js +115 -0
  14. package/dist/src/adapters/claude-code/managed.js +75 -0
  15. package/dist/src/adapters/claude-code/plugin-files.js +88 -0
  16. package/dist/src/adapters/claude-code/plugins.js +117 -0
  17. package/dist/src/adapters/claude-code/pointer.js +48 -0
  18. package/dist/src/adapters/claude-code/predict.js +271 -0
  19. package/dist/src/adapters/claude-code/routing.js +88 -0
  20. package/dist/src/adapters/claude-code/settings.js +189 -0
  21. package/dist/src/adapters/claude-code/subagents.js +666 -0
  22. package/dist/src/adapters/claude-code/triggers.js +88 -0
  23. package/dist/src/cli.js +157 -0
  24. package/dist/src/commands/accept.js +115 -0
  25. package/dist/src/commands/check.js +529 -0
  26. package/dist/src/commands/hook.js +73 -0
  27. package/dist/src/commands/init.js +29 -0
  28. package/dist/src/commands/install.js +370 -0
  29. package/dist/src/commands/models.js +213 -0
  30. package/dist/src/commands/receives.js +84 -0
  31. package/dist/src/commands/report.js +386 -0
  32. package/dist/src/commands/resolve.js +32 -0
  33. package/dist/src/commands/run.js +168 -0
  34. package/dist/src/commands/trust.js +70 -0
  35. package/dist/src/commands/usage.js +10 -0
  36. package/dist/src/commands/watch.js +154 -0
  37. package/dist/src/config/create.js +51 -0
  38. package/dist/src/config/json-schema.js +207 -0
  39. package/dist/src/config/load.js +758 -0
  40. package/dist/src/config/paths.js +42 -0
  41. package/dist/src/config/preset-changes.js +190 -0
  42. package/dist/src/config/project.js +354 -0
  43. package/dist/src/config/rewrite.js +112 -0
  44. package/dist/src/core/backtracking.js +330 -0
  45. package/dist/src/core/classify.js +66 -0
  46. package/dist/src/core/normalize.js +24 -0
  47. package/dist/src/core/overlap.js +39 -0
  48. package/dist/src/core/regex-sample.js +278 -0
  49. package/dist/src/core/resolve.js +201 -0
  50. package/dist/src/core/route.js +93 -0
  51. package/dist/src/core/scope.js +77 -0
  52. package/dist/src/core/triggers.js +30 -0
  53. package/dist/src/core/types.js +74 -0
  54. package/dist/src/state/agents.js +200 -0
  55. package/dist/src/state/claims.js +80 -0
  56. package/dist/src/state/files.js +84 -0
  57. package/dist/src/state/installs.js +29 -0
  58. package/dist/src/state/log.js +90 -0
  59. package/dist/src/state/node.js +35 -0
  60. package/dist/src/state/sessions.js +109 -0
  61. package/dist/src/state/triggers.js +57 -0
  62. package/dist/src/version.js +24 -0
  63. package/dist/src/watch/service.js +172 -0
  64. package/dist/src/watch/watcher.js +130 -0
  65. package/dist/src/wording.js +11 -0
  66. package/hooks/hooks.json +118 -0
  67. package/package.json +57 -7
  68. package/presets/claude/SOURCES.md +485 -0
  69. package/presets/claude/preset.json +432 -0
  70. package/presets/claude/rules/fable-5-2/code-ownership.md +1 -0
  71. package/presets/claude/rules/fable-5-2/finish-work.md +1 -0
  72. package/presets/claude/rules/fable-5-2/low-context-report.md +1 -0
  73. package/presets/claude/rules/fable-5-2/progress-updates.md +1 -0
  74. package/presets/claude/rules/haiku-5-5/carry-through.md +1 -0
  75. package/presets/claude/rules/haiku-5-5/search-recent-facts.md +1 -0
  76. package/presets/claude/rules/haiku-5-5/verify-changes.md +1 -0
  77. package/presets/claude/rules/opus-5-5/explore-before-acting.md +1 -0
  78. package/presets/claude/rules/opus-5-5/progress-updates.md +1 -0
  79. package/presets/claude/rules/opus-5-5/unattended-run.md +1 -0
  80. package/presets/claude/rules/sonnet-5-5/carry-through.md +1 -0
  81. package/presets/claude/rules/sonnet-5-5/check-current-facts.md +1 -0
  82. package/presets/claude/rules/sonnet-5-5/ideas-first.md +1 -0
  83. package/presets/claude/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  84. package/presets/claude/rules/sonnet-5-5/stay-in-scope.md +1 -0
  85. package/presets/claude/rules/sonnet-5-5/verify-changes.md +1 -0
  86. package/presets/claude/versions/1.3.0/preset.json +432 -0
  87. package/presets/claude/versions/1.3.0/rules/fable-5-2/code-ownership.md +1 -0
  88. package/presets/claude/versions/1.3.0/rules/fable-5-2/finish-work.md +1 -0
  89. package/presets/claude/versions/1.3.0/rules/fable-5-2/low-context-report.md +1 -0
  90. package/presets/claude/versions/1.3.0/rules/fable-5-2/progress-updates.md +1 -0
  91. package/presets/claude/versions/1.3.0/rules/haiku-5-5/carry-through.md +1 -0
  92. package/presets/claude/versions/1.3.0/rules/haiku-5-5/search-recent-facts.md +1 -0
  93. package/presets/claude/versions/1.3.0/rules/haiku-5-5/verify-changes.md +1 -0
  94. package/presets/claude/versions/1.3.0/rules/opus-5-5/explore-before-acting.md +1 -0
  95. package/presets/claude/versions/1.3.0/rules/opus-5-5/progress-updates.md +1 -0
  96. package/presets/claude/versions/1.3.0/rules/opus-5-5/unattended-run.md +1 -0
  97. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/carry-through.md +1 -0
  98. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/check-current-facts.md +1 -0
  99. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/ideas-first.md +1 -0
  100. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/no-self-review-rounds.md +1 -0
  101. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/stay-in-scope.md +1 -0
  102. package/presets/claude/versions/1.3.0/rules/sonnet-5-5/verify-changes.md +1 -0
  103. package/schema/noonsight-project.schema.json +394 -0
  104. package/schema/noonsight.schema.json +425 -0
  105. package/schema/preset.schema.json +194 -0
  106. package/scripts/noonsight +68 -0
  107. package/skills/accept/SKILL.md +11 -0
  108. package/skills/check/SKILL.md +11 -0
  109. package/skills/models/SKILL.md +11 -0
  110. package/skills/report/SKILL.md +11 -0
  111. package/skills/resolve/SKILL.md +12 -0
  112. package/skills/setup/SKILL.md +15 -0
  113. package/skills/trust/SKILL.md +12 -0
  114. package/skills/untrust/SKILL.md +12 -0
@@ -0,0 +1,386 @@
1
+ // noonsight report: what the decision log says the hooks and the launcher did. For each rule, how
2
+ // often it was delivered, and to which models, scopes, places and events, and whether its scope or a
3
+ // trigger brought it; the triggers sessions revealed, and with which edits; the rules the
4
+ // configuration has on that the log never shows delivered; the decisions that delivered nothing, by
5
+ // why; and what the classifier did, how long it took and what it cost. The configuration is read as
6
+ // a session started in the current directory reads it, with that directory's project laid over it.
7
+ // It reads local files only and changes nothing.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { ConfigError, loadConfigDetails } from '../config/load.js';
12
+ import { configPath, stateDir } from '../config/paths.js';
13
+ import { describeProject, projectFor } from '../config/project.js';
14
+ import { ANY_SCOPE, placeName } from '../core/types.js';
15
+ import { LOG_FILE, readDecisionFile, readDecisions, ROTATED_LOG_FILE } from '../state/log.js';
16
+ import { UsageError } from './usage.js';
17
+ export const REPORT_USAGE = `usage: noonsight report [--json] [--log <file>]
18
+
19
+ Report what the decision log records: for each rule, how often it was delivered and to which
20
+ models, scopes, places and events, whether its scope or a trigger brought it, and the length of its
21
+ text; the triggers sessions revealed, by the edits that revealed them; the rules the configuration
22
+ has on that the log never shows delivered; the decisions that delivered nothing, by why; and the
23
+ classifier's results, time and cost. Rule lengths and the rules never delivered come from the
24
+ configuration as a session started in the current directory reads it, with the project
25
+ configuration found from there laid over it; the log counts the sessions of every project.
26
+
27
+ --log <file> read this log file instead of the account's decision log
28
+ --json print the same as JSON
29
+
30
+ Exits 0, or 2 for a usage error.`;
31
+ /** How a tally names a field the log line does not carry, such as the place on lines older than places. */
32
+ export const NOT_RECORDED = '(not recorded)';
33
+ /** How a tally names a task with no scope. */
34
+ export const NO_SCOPE = '(none)';
35
+ /** How the tally of what brought a rule names a delivery by the rule's scopes, as opposed to a trigger. */
36
+ export const BY_SCOPE = 'scope';
37
+ /** How many files a trigger's text lists, most frequent first. */
38
+ const FILES_SHOWN = 10;
39
+ /** The values of `delivered` that mean the rules reached the model: by the hook, or in the system prompt. */
40
+ export const DELIVERING = ['rules', 'rules+note', 'system-prompt'];
41
+ /**
42
+ * Why a /model line's rules are not counted as delivered when the same session's next line is another
43
+ * /model line: Claude Code adds what the hook returns to the next request only, and loses it when
44
+ * another switch comes first. The log records no requests, so a switch followed at once by another
45
+ * may never have reached the model.
46
+ */
47
+ export const SWITCHED_AGAIN = 'switched-again';
48
+ export function runReport(args, env, out) {
49
+ const options = parseArgs(args);
50
+ // As `noonsight check` and `noonsight models` do: the project a session started here would get.
51
+ const report = buildReport(env, { ...options, project: env.CLAUDE_PROJECT_DIR || process.cwd() });
52
+ out(options.json ? JSON.stringify(report, null, 2) : renderReport(report));
53
+ return 0;
54
+ }
55
+ function parseArgs(args) {
56
+ let json = false;
57
+ let log = null;
58
+ for (let i = 0; i < args.length; i++) {
59
+ const a = args[i];
60
+ if (a === '--json')
61
+ json = true;
62
+ else if (a === '--log') {
63
+ const value = args[++i];
64
+ if (value === undefined || value === '')
65
+ throw new UsageError(`${a} needs a value`, REPORT_USAGE);
66
+ log = value;
67
+ }
68
+ else
69
+ throw new UsageError(a.startsWith('-') ? `unknown option ${a}` : `unexpected argument "${a}"`, REPORT_USAGE);
70
+ }
71
+ return { json, log };
72
+ }
73
+ export function buildReport(env, options, home = os.homedir()) {
74
+ const dir = stateDir(home);
75
+ const files = options.log !== null ? [path.resolve(options.log)] : [path.join(dir, ROTATED_LOG_FILE), path.join(dir, LOG_FILE)];
76
+ if (options.log !== null && !readableFile(files[0]))
77
+ throw new UsageError(`cannot read the log file ${options.log}`, REPORT_USAGE);
78
+ const records = options.log !== null ? readDecisionFile(files[0]) : readDecisions(dir);
79
+ const superseded = switchedAgain(records);
80
+ const delivering = {};
81
+ const notDelivering = {};
82
+ const agentResults = {};
83
+ const classifierResults = {};
84
+ const classifierMs = [];
85
+ let classifierCost = 0;
86
+ const rules = new Map();
87
+ const triggers = new Map();
88
+ let first = null;
89
+ let last = null;
90
+ for (const [index, r] of records.entries()) {
91
+ const ts = typeof r.ts === 'string' ? r.ts : null;
92
+ if (ts !== null) {
93
+ if (first === null || ts < first)
94
+ first = ts;
95
+ if (last === null || ts > last)
96
+ last = ts;
97
+ }
98
+ const event = text(r.event) ?? NOT_RECORDED;
99
+ const outcome = text(r.classifier);
100
+ if (outcome !== null) {
101
+ count(classifierResults, outcome);
102
+ if (typeof r.classifier_ms === 'number' && Number.isFinite(r.classifier_ms))
103
+ classifierMs.push(r.classifier_ms);
104
+ if (typeof r.classifier_cost_usd === 'number' && Number.isFinite(r.classifier_cost_usd))
105
+ classifierCost += r.classifier_cost_usd;
106
+ }
107
+ if (event === 'agent-result') {
108
+ count(agentResults, text(r.result) ?? NOT_RECORDED);
109
+ continue;
110
+ }
111
+ const revealed = event === 'file-edit' ? text(r.trigger) : null;
112
+ if (revealed !== null) {
113
+ const t = triggers.get(revealed) ?? { revealed: 0, delivered: 0, tools: {}, extensions: {}, files: {} };
114
+ triggers.set(revealed, t);
115
+ t.revealed++;
116
+ if (DELIVERING.includes(r.delivered))
117
+ t.delivered++;
118
+ count(t.tools, text(r.tool_name) ?? NOT_RECORDED);
119
+ const file = text(r.file);
120
+ count(t.extensions, file === null ? NOT_RECORDED : path.extname(file).toLowerCase() || '(none)');
121
+ count(t.files, file ?? NOT_RECORDED);
122
+ }
123
+ // A subagent's rules are counted once: delivered at its start, or not delivered at its call.
124
+ if (event === 'agent-call' && r.delivered === 'at-start')
125
+ continue;
126
+ const ids = Array.isArray(r.rules) ? r.rules.filter((x) => typeof x === 'string') : [];
127
+ const delivers = DELIVERING.includes(r.delivered) && ids.length > 0;
128
+ if (!delivers || superseded.has(index)) {
129
+ if (delivers)
130
+ count(notDelivering, SWITCHED_AGAIN);
131
+ else if (event !== 'subagent-start')
132
+ count(notDelivering, whyNothing(r));
133
+ // Rules the call had that a start shared between several calls could not give.
134
+ else if (text(r.reason) === 'calls-differ')
135
+ count(notDelivering, 'calls-differ');
136
+ continue;
137
+ }
138
+ count(delivering, event);
139
+ const triggered = Array.isArray(r.triggered_rules) ? r.triggered_rules.filter((x) => typeof x === 'string') : [];
140
+ const lineTriggers = Array.isArray(r.triggers) ? r.triggers.filter((x) => typeof x === 'string') : [];
141
+ // A file-edit line names its trigger; a session start or a switch after one names the session's triggers.
142
+ const by = text(r.trigger) ?? (lineTriggers.join(', ') || NOT_RECORDED);
143
+ for (const id of ids) {
144
+ const rule = rules.get(id) ?? newRule(id);
145
+ rules.set(id, rule);
146
+ rule.deliveries++;
147
+ const session = text(r.session_id);
148
+ if (session !== null)
149
+ rule.sessions.add(session);
150
+ if (ts !== null) {
151
+ if (rule.first === null || ts < rule.first)
152
+ rule.first = ts;
153
+ if (rule.last === null || ts > rule.last)
154
+ rule.last = ts;
155
+ }
156
+ count(rule.models, text(r.model) ?? NOT_RECORDED);
157
+ // Lines older than scopes carry no scope field; a null scope is a task with no scope.
158
+ count(rule.scopes, 'scope' in r ? (text(r.scope) ?? NO_SCOPE) : NOT_RECORDED);
159
+ // Lines written before "attended" was the place's name say "session"; both count as "attended".
160
+ const place = text(r.place);
161
+ count(rule.places, place === null ? NOT_RECORDED : (placeName(place) ?? place));
162
+ count(rule.events, event);
163
+ count(rule.brought_by, triggered.includes(id) ? by : BY_SCOPE);
164
+ }
165
+ }
166
+ const file = configPath(env, home);
167
+ let config = null;
168
+ let layer = null;
169
+ let status = fs.existsSync(file) ? 'read' : 'missing';
170
+ if (status === 'read')
171
+ try {
172
+ ({ config, project: layer } = loadConfigDetails(file, { project: projectFor(options.project, file, dir) }, env));
173
+ }
174
+ catch (e) {
175
+ if (!(e instanceof ConfigError))
176
+ throw e;
177
+ status = 'refused';
178
+ }
179
+ const lengths = config ? ruleLengths(config) : new Map();
180
+ const listed = [...rules.values()]
181
+ .sort((a, b) => b.deliveries - a.deliveries || (a.id < b.id ? -1 : 1))
182
+ .map((r) => {
183
+ const characters = lengths.get(r.id);
184
+ const shown = characters ? Object.fromEntries([...characters].filter(([model]) => model in r.models)) : {};
185
+ return {
186
+ id: r.id,
187
+ deliveries: r.deliveries,
188
+ sessions: r.sessions.size,
189
+ first: r.first,
190
+ last: r.last,
191
+ models: sorted(r.models),
192
+ scopes: sorted(r.scopes),
193
+ places: sorted(r.places),
194
+ events: sorted(r.events),
195
+ brought_by: sorted(r.brought_by),
196
+ ...(Object.keys(shown).length ? { characters: shown } : {}),
197
+ };
198
+ });
199
+ const neverDelivered = [];
200
+ if (config)
201
+ for (const [model, entry] of config.exact) {
202
+ if (entry.use !== 'rules')
203
+ continue;
204
+ for (const rule of entry.rules)
205
+ if (!((rules.get(rule.id)?.models[model] ?? 0) > 0))
206
+ neverDelivered.push({ id: rule.id, model, scopes: rule.scopes, where: rule.where });
207
+ }
208
+ return {
209
+ log: files,
210
+ decisions: records.length,
211
+ first,
212
+ last,
213
+ delivering: sorted(delivering),
214
+ not_delivering: sorted(notDelivering),
215
+ agent_results: sorted(agentResults),
216
+ rules: listed,
217
+ triggers: Object.fromEntries([...triggers]
218
+ .sort(([a], [b]) => (a < b ? -1 : 1))
219
+ .map(([name, t]) => [name, { revealed: t.revealed, delivered: t.delivered, tools: sorted(t.tools), extensions: sorted(t.extensions), files: sorted(t.files) }])),
220
+ config: { file, status },
221
+ project: layer && { file: layer.file, dir: layer.dir, allow: layer.allow, status: layer.status, summary: describeProject(layer) },
222
+ never_delivered: neverDelivered,
223
+ classifier: total(classifierResults) === 0
224
+ ? null
225
+ : {
226
+ results: sorted(classifierResults),
227
+ runs: classifierMs.length,
228
+ median_ms: median(classifierMs),
229
+ max_ms: classifierMs.length ? Math.max(...classifierMs) : null,
230
+ cost_usd: Math.round(classifierCost * 1e6) / 1e6,
231
+ },
232
+ };
233
+ }
234
+ /** The positions of the model-switch lines whose session's next line is another model-switch line. */
235
+ function switchedAgain(records) {
236
+ const superseded = new Set();
237
+ const previous = new Map();
238
+ for (const [index, r] of records.entries()) {
239
+ const session = text(r.session_id);
240
+ if (session === null)
241
+ continue;
242
+ const before = previous.get(session);
243
+ if (before !== undefined && r.event === 'model-switch' && records[before]?.event === 'model-switch')
244
+ superseded.add(before);
245
+ previous.set(session, index);
246
+ }
247
+ return superseded;
248
+ }
249
+ /** The middle value, or the mean of the two middle values; null for none. */
250
+ function median(values) {
251
+ if (values.length === 0)
252
+ return null;
253
+ const s = [...values].sort((a, b) => a - b);
254
+ const mid = Math.floor(s.length / 2);
255
+ return s.length % 2 === 1 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
256
+ }
257
+ function newRule(id) {
258
+ return { id, deliveries: 0, sessions: new Set(), first: null, last: null, models: {}, scopes: {}, places: {}, events: {}, brought_by: {} };
259
+ }
260
+ /**
261
+ * Why a decision delivered no rules, in the log's own words: the reason of a "none" decision
262
+ * (declared-none, no-rule-applies), the `delivered` value of a matched one (already-delivered,
263
+ * launcher, off), or the status (undeclared, config-invalid, error).
264
+ */
265
+ function whyNothing(r) {
266
+ const status = text(r.status);
267
+ if (status === 'none')
268
+ return text(r.reason) ?? 'none';
269
+ if (status === 'matched')
270
+ return text(r.delivered) ?? NOT_RECORDED;
271
+ return status ?? NOT_RECORDED;
272
+ }
273
+ /** Each rule's text length, per exact model. */
274
+ function ruleLengths(config) {
275
+ const lengths = new Map();
276
+ for (const [model, entry] of config.exact) {
277
+ if (entry.use !== 'rules')
278
+ continue;
279
+ for (const rule of entry.rules) {
280
+ const perModel = lengths.get(rule.id) ?? new Map();
281
+ perModel.set(model, rule.text.length);
282
+ lengths.set(rule.id, perModel);
283
+ }
284
+ }
285
+ return lengths;
286
+ }
287
+ function readableFile(file) {
288
+ try {
289
+ fs.accessSync(file, fs.constants.R_OK);
290
+ return fs.statSync(file).isFile();
291
+ }
292
+ catch {
293
+ return false;
294
+ }
295
+ }
296
+ function text(v) {
297
+ return typeof v === 'string' && v !== '' ? v : null;
298
+ }
299
+ function count(tally, key) {
300
+ tally[key] = (tally[key] ?? 0) + 1;
301
+ }
302
+ /** Most first, then by name. */
303
+ function sorted(tally) {
304
+ return Object.fromEntries(Object.entries(tally).sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1)));
305
+ }
306
+ export function renderReport(r) {
307
+ const lines = [];
308
+ lines.push(`log ${r.log.join(', ')}`);
309
+ if (r.project)
310
+ lines.push(`project ${r.project.file}: ${r.project.summary}`);
311
+ if (r.decisions === 0) {
312
+ lines.push('No decisions in the log.');
313
+ }
314
+ else {
315
+ lines.push(`${r.decisions} ${r.decisions === 1 ? 'decision' : 'decisions'}, from ${r.first ?? 'an unknown time'} to ${r.last ?? 'an unknown time'}`);
316
+ lines.push(` delivered rules: ${total(r.delivering)}${tallyText(r.delivering)}`);
317
+ lines.push(` delivered no rules: ${total(r.not_delivering)}${tallyText(r.not_delivering)}`);
318
+ if (total(r.agent_results) > 0)
319
+ lines.push(` subagent checks: ${total(r.agent_results)}${tallyText(r.agent_results)}`);
320
+ }
321
+ if (r.rules.length) {
322
+ lines.push('', 'Rules delivered, most often first:');
323
+ for (const rule of r.rules) {
324
+ lines.push(` ${rule.id}: ${rule.deliveries} ${rule.deliveries === 1 ? 'delivery' : 'deliveries'}` +
325
+ (rule.sessions ? ` in ${rule.sessions} ${rule.sessions === 1 ? 'session' : 'sessions'}` : '') +
326
+ `, last ${rule.last ?? 'at an unknown time'}`);
327
+ lines.push(` models: ${pairs(rule.models)}`);
328
+ lines.push(` scopes: ${pairs(rule.scopes)}`);
329
+ lines.push(` places: ${pairs(rule.places)}`);
330
+ lines.push(` events: ${pairs(rule.events)}`);
331
+ if (Object.keys(rule.brought_by).some((k) => k !== BY_SCOPE))
332
+ lines.push(` brought by: ${pairs(rule.brought_by)}`);
333
+ if (rule.characters)
334
+ lines.push(` text: ${Object.entries(rule.characters).map(([model, n]) => `${n} characters for ${model}`).join(', ')}`);
335
+ }
336
+ }
337
+ const triggerNames = Object.keys(r.triggers);
338
+ if (triggerNames.length) {
339
+ lines.push('', 'Triggers revealed:');
340
+ for (const name of triggerNames) {
341
+ const t = r.triggers[name];
342
+ lines.push(` ${name}: in ${t.revealed} ${t.revealed === 1 ? 'session' : 'sessions'}, ${t.delivered} with rules delivered`);
343
+ lines.push(` tools: ${pairs(t.tools)}`);
344
+ lines.push(` extensions: ${pairs(t.extensions)}`);
345
+ const files = Object.entries(t.files);
346
+ const more = files.length - FILES_SHOWN;
347
+ lines.push(` files: ${pairs(Object.fromEntries(files.slice(0, FILES_SHOWN)))}${more > 0 ? `, and ${more} more` : ''}`);
348
+ }
349
+ }
350
+ if (r.classifier !== null) {
351
+ const c = r.classifier;
352
+ lines.push('', 'Classifier:');
353
+ lines.push(` tasks: ${total(c.results)} (${pairs(c.results)})`);
354
+ lines.push(c.runs === 0
355
+ ? ' runs: 0'
356
+ : ` runs: ${c.runs}, median ${c.median_ms} ms, longest ${c.max_ms} ms, cost US$ ${c.cost_usd.toFixed(4)}`);
357
+ }
358
+ if (r.config.status === 'read') {
359
+ // The log holds the sessions of every project; the configuration is the one of this directory.
360
+ const configuration = r.project?.status === 'applied' ? `${r.config.file}, with the project ${r.project.file}` : r.config.file;
361
+ if (r.never_delivered.length) {
362
+ lines.push('', `On in the configuration (${configuration}), never delivered in this log:`);
363
+ for (const idle of r.never_delivered)
364
+ lines.push(` ${idle.id} for ${idle.model} (scopes: ${idle.scopes.includes(ANY_SCOPE) ? 'every scope' : idle.scopes.join(', ')}; places: ${idle.where.join(', ')})`);
365
+ }
366
+ else if (r.rules.length)
367
+ lines.push('', `Every rule on in the configuration (${configuration}) was delivered at least once in this log.`);
368
+ }
369
+ else
370
+ lines.push('', r.config.status === 'missing'
371
+ ? `No configuration at ${r.config.file}, so rule lengths and the rules never delivered are not shown.`
372
+ : `The configuration at ${r.config.file} is refused (\`noonsight check\` lists why), so rule lengths and the rules never delivered are not shown.`);
373
+ return lines.join('\n');
374
+ }
375
+ function total(t) {
376
+ return Object.values(t).reduce((a, b) => a + b, 0);
377
+ }
378
+ function tallyText(t) {
379
+ return total(t) ? ` (${pairs(t)})` : '';
380
+ }
381
+ function pairs(t) {
382
+ return Object.entries(t)
383
+ .map(([k, n]) => `${k} ${n}`)
384
+ .join(', ');
385
+ }
386
+ //# sourceMappingURL=report.js.map
@@ -0,0 +1,32 @@
1
+ import { configPath, stateDir } from '../config/paths.js';
2
+ import { loadConfigDetails } from '../config/load.js';
3
+ import { projectFor } from '../config/project.js';
4
+ import { resolve } from '../core/resolve.js';
5
+ import { placeName } from '../core/types.js';
6
+ import { UsageError } from './usage.js';
7
+ export const RESOLVE_USAGE = `usage: noonsight resolve <model> [scope] [attended|unattended|subagent]
8
+
9
+ Print, as JSON, the decision for a model: the rules it receives and the exact text that would be
10
+ delivered, "none" when the configuration decided it needs no rules, or "undeclared".
11
+ The place defaults to "attended", a session someone is watching; "session", its earlier name, is
12
+ also read. An empty model ("") stands for a tool that reported no model,
13
+ and an empty scope ("") for no scope, so a place can be given without one. A project configuration
14
+ found from the current directory applies as it would to a session started here.`;
15
+ export function runResolve(args, env) {
16
+ const option = args.find((a) => a.length > 1 && a.startsWith('-'));
17
+ if (option !== undefined)
18
+ throw new UsageError(`unknown option ${option}`, RESOLVE_USAGE);
19
+ const [model, scopeArg, placeArg = 'attended', ...extra] = args;
20
+ if (model === undefined)
21
+ throw new UsageError('missing the model', RESOLVE_USAGE);
22
+ if (extra.length)
23
+ throw new UsageError(`unexpected argument "${extra[0]}"`, RESOLVE_USAGE);
24
+ const place = placeName(placeArg);
25
+ if (place === null)
26
+ throw new UsageError(`unknown place "${placeArg}"`, RESOLVE_USAGE);
27
+ // As a session started here would: the machine's configuration, with this directory's project over it.
28
+ const file = configPath(env);
29
+ const { config } = loadConfigDetails(file, { project: projectFor(env.CLAUDE_PROJECT_DIR || process.cwd(), file, stateDir()) }, env);
30
+ return resolve(config, { model, scope: scopeArg || null, place });
31
+ }
32
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1,168 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { applyEnv, passThrough, planLaunch } from '../adapters/claude-code/launcher.js';
6
+ import { notRouted } from '../adapters/claude-code/routing.js';
7
+ import { ConfigError, loadConfigDetails } from '../config/load.js';
8
+ import { configPath, stateDir } from '../config/paths.js';
9
+ import { projectFields, projectFor, projectWarning } from '../config/project.js';
10
+ import { appendDecision } from '../state/log.js';
11
+ import { writeFileAtomic } from '../state/files.js';
12
+ import { packageVersion } from '../version.js';
13
+ import { UsageError } from './usage.js';
14
+ export const RUN_USAGE = `usage: noonsight run [--scope <scope>] [--task <text>] [--] [claude arguments...]
15
+
16
+ Start Claude Code with the rules for its model in the system prompt, for sessions the hooks do not
17
+ reach or reach without the model, such as \`claude -p\`. noonsight takes the model the way Claude Code
18
+ does: --model among the claude arguments, else ANTHROPIC_MODEL, else the model setting. It adds the
19
+ rules with --append-system-prompt-file and runs claude with every other argument unchanged. When the
20
+ hooks are installed too, they find the rules in the system prompt and do not deliver them again.
21
+
22
+ With routing on for the launcher, the task scope's row in the routing table adds --model and
23
+ --effort first, unless the claude arguments already give --model.
24
+
25
+ Options, before the claude arguments:
26
+ --scope <scope> the task scope, set as NOONSIGHT_SCOPE for the session
27
+ --task <text> the task text the scopes' matchers read when no scope is given; without it,
28
+ the prompt right after -p or --print
29
+
30
+ Everything from the first other argument, or after "--", goes to claude. noonsight run exits with
31
+ claude's exit status.`;
32
+ /** Run claude through the launcher. Resolves to claude's exit status. */
33
+ export async function runRun(args, env, io, home = os.homedir()) {
34
+ let scope = null;
35
+ let task = null;
36
+ let rest = [];
37
+ for (let i = 0; i < args.length; i++) {
38
+ const a = args[i] ?? '';
39
+ if (a === '--help' || a === '-h') {
40
+ io.out(RUN_USAGE);
41
+ return 0;
42
+ }
43
+ if (a === '--scope') {
44
+ const value = args[++i];
45
+ if (value === undefined)
46
+ throw new UsageError('--scope needs a value', RUN_USAGE);
47
+ scope = value;
48
+ }
49
+ else if (a.startsWith('--scope='))
50
+ scope = a.slice('--scope='.length);
51
+ else if (a === '--task') {
52
+ const value = args[++i];
53
+ if (value === undefined)
54
+ throw new UsageError('--task needs a value', RUN_USAGE);
55
+ task = value;
56
+ }
57
+ else if (a.startsWith('--task='))
58
+ task = a.slice('--task='.length);
59
+ else {
60
+ rest = args.slice(a === '--' ? i + 1 : i);
61
+ break;
62
+ }
63
+ }
64
+ const plan = env.NOONSIGHT_DISABLE === '1' ? { args: [...rest], env: {} } : prepare(rest, scope, task, env, home, io);
65
+ return exec(plan.args, applyEnv(env, plan.env), io);
66
+ }
67
+ /** Decide, write the system prompt file and log. Any failure starts claude without the launcher's rules. */
68
+ function prepare(args, scope, task, env, home, io) {
69
+ const state = stateDir(home);
70
+ const file = configPath(env, home);
71
+ const log = (fields) => {
72
+ try {
73
+ appendDecision(state, { ts: new Date().toISOString(), version: safeVersion(), event: 'launch', config: file, ...fields });
74
+ }
75
+ catch {
76
+ // A log that cannot be written must not cost the session its rules.
77
+ }
78
+ };
79
+ if (!env.NOONSIGHT_CONFIG && !fs.existsSync(file)) {
80
+ io.err(`noonsight: there is no configuration at ${file}, so noonsight run added no rules. Run \`noonsight init\` to create one.`);
81
+ return passThrough(args, scope, env);
82
+ }
83
+ let plan;
84
+ let projectNote = null;
85
+ try {
86
+ // The session's project: the one Claude Code will find from the same directory.
87
+ const cwd = process.cwd();
88
+ const details = loadConfigDetails(file, { project: projectFor(env.CLAUDE_PROJECT_DIR || cwd, file, state) }, env);
89
+ plan = planLaunch(details.config, file, { args, scope, task, env, home, cwd, state });
90
+ plan = { ...plan, record: { ...plan.record, ...projectFields(details.project) } };
91
+ projectNote = projectWarning(details.project);
92
+ }
93
+ catch (e) {
94
+ if (e instanceof ConfigError) {
95
+ log({ status: 'config-invalid', problems: e.problems.length, ...notRouted('config-invalid'), delivered: 'nothing', warned: true });
96
+ io.err(`noonsight: the configuration at ${file} was refused (${e.problems.length} problem${e.problems.length === 1 ? '' : 's'}), ` +
97
+ 'so noonsight run added no rules. Run `noonsight check` to see the problems.');
98
+ }
99
+ else {
100
+ const message = e instanceof Error ? e.message : String(e);
101
+ log({ status: 'error', error: message, ...notRouted('error'), delivered: 'nothing', warned: true });
102
+ io.err(`noonsight: noonsight run failed (${message}), so it added no rules.`);
103
+ }
104
+ return passThrough(args, scope, env);
105
+ }
106
+ if (plan.file !== null) {
107
+ try {
108
+ fs.mkdirSync(path.dirname(plan.file.path), { recursive: true, mode: 0o700 });
109
+ // Written on every launch, which also keeps the file from being pruned while it is in use.
110
+ writeFileAtomic(plan.file.path, plan.file.content, 0o600);
111
+ }
112
+ catch (e) {
113
+ const message = e instanceof Error ? e.message : String(e);
114
+ log({ ...plan.record, status: 'error', error: message, delivered: 'nothing', warned: true });
115
+ io.err(`noonsight: could not write ${plan.file.path} (${message}), so noonsight run added no rules.`);
116
+ return plan.fallback;
117
+ }
118
+ }
119
+ log(projectNote !== null ? { ...plan.record, warned: true } : plan.record);
120
+ for (const m of [...plan.messages, ...(projectNote !== null ? [projectNote] : [])])
121
+ io.err(m);
122
+ return plan;
123
+ }
124
+ /**
125
+ * Start claude in the foreground and wait for it. The terminal sends Ctrl-C and Ctrl-\ to claude as
126
+ * well, so the launcher ignores them instead of ending under it; a SIGTERM or SIGHUP sent to the
127
+ * launcher alone is passed on.
128
+ */
129
+ function exec(args, env, io) {
130
+ return new Promise((done) => {
131
+ const child = spawn('claude', [...args], { stdio: 'inherit', env });
132
+ const ignore = () => { };
133
+ const forward = (signal) => {
134
+ child.kill(signal);
135
+ };
136
+ const handlers = [
137
+ ['SIGINT', ignore],
138
+ ['SIGQUIT', ignore],
139
+ ['SIGTERM', forward],
140
+ ['SIGHUP', forward],
141
+ ];
142
+ for (const [s, h] of handlers)
143
+ process.on(s, h);
144
+ let finished = false;
145
+ const finish = (code) => {
146
+ if (finished)
147
+ return;
148
+ finished = true;
149
+ for (const [s, h] of handlers)
150
+ process.off(s, h);
151
+ done(code);
152
+ };
153
+ child.on('error', (e) => {
154
+ io.err(`noonsight: could not start claude (${e.message}).`);
155
+ finish(127);
156
+ });
157
+ child.on('exit', (code, signal) => finish(code ?? 128 + (signal ? (os.constants.signals[signal] ?? 0) : 0)));
158
+ });
159
+ }
160
+ function safeVersion() {
161
+ try {
162
+ return packageVersion();
163
+ }
164
+ catch {
165
+ return 'unknown';
166
+ }
167
+ }
168
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1,70 @@
1
+ // noonsight trust and noonsight untrust: this account's decision about the project configuration
2
+ // found from a directory. A trusted project is laid over the machine's configuration for the sessions
3
+ // that run in it, and keeps applying as its file changes; a declined one is left out without a warning.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { ConfigError, loadConfigDetails } from '../config/load.js';
8
+ import { configPath, stateDir } from '../config/paths.js';
9
+ import { describeProject, findProject, PROJECT_FILE, setTrust } from '../config/project.js';
10
+ import { UsageError } from './usage.js';
11
+ export const TRUST_USAGE = `usage: noonsight trust [<dir>]
12
+ noonsight untrust [<dir>]
13
+
14
+ trust: apply the project configuration (${PROJECT_FILE}) found from <dir>, by default the current
15
+ directory, up to its repository root, to the sessions that run in that project, laid over the
16
+ machine's configuration as its "projects.allow" permits. Trust is kept for the project directory and
17
+ this account; later changes to the project's files apply without asking again.
18
+ untrust: stop applying it, and stop the warning sessions in the project start with.
19
+ Exits 0, 1 when no project configuration is found or the decision cannot be written, and 2 for a usage error.`;
20
+ export function runTrust(command, args, env, io, now = new Date()) {
21
+ const option = args.find((a) => a.length > 1 && a.startsWith('-'));
22
+ if (option !== undefined)
23
+ throw new UsageError(`unknown option ${option}`, TRUST_USAGE);
24
+ if (args.length > 1)
25
+ throw new UsageError(`unexpected argument "${args[1]}"`, TRUST_USAGE);
26
+ const home = os.homedir();
27
+ const start = path.resolve(args[0] ?? process.cwd());
28
+ const found = findProject(start);
29
+ if (found === null) {
30
+ io.err(`noonsight: no project configuration (${PROJECT_FILE}) from ${start} up to its repository root.`);
31
+ return 1;
32
+ }
33
+ const trusted = command === 'trust';
34
+ const state = stateDir(home);
35
+ let before;
36
+ try {
37
+ before = setTrust(state, found.dir, trusted, now);
38
+ }
39
+ catch (e) {
40
+ io.err(`noonsight: could not record the decision in ${state} (${e.message}).`);
41
+ return 1;
42
+ }
43
+ const decided = trusted ? 'trusted' : 'declined';
44
+ io.out(`project ${found.file}: ${before === trusted ? `already ${decided}` : decided} for this account`);
45
+ if (!trusted) {
46
+ io.out(`sessions in ${found.dir} get only the machine's configuration, without a warning; \`noonsight trust\` there applies it again`);
47
+ return 0;
48
+ }
49
+ // What the project now does, as a session started there reads it.
50
+ const file = configPath(env, home);
51
+ if (!env.NOONSIGHT_CONFIG && !fs.existsSync(file)) {
52
+ io.out(`there is no machine configuration at ${file} yet, so the project applies once \`noonsight init\` writes one`);
53
+ return 0;
54
+ }
55
+ try {
56
+ const { project } = loadConfigDetails(file, { project: { ...found, trusted: true } }, env);
57
+ if (project !== null) {
58
+ io.out(`project ${found.file}: ${describeProject(project)}`);
59
+ for (const note of project.notes)
60
+ io.out(`note: ${note}`);
61
+ }
62
+ }
63
+ catch (e) {
64
+ if (!(e instanceof ConfigError))
65
+ throw e;
66
+ io.out(`the machine's configuration at ${file} is refused, so nothing applies until it is fixed; run \`noonsight check\` to see the problems`);
67
+ }
68
+ return 0;
69
+ }
70
+ //# sourceMappingURL=trust.js.map
@@ -0,0 +1,10 @@
1
+ /** A command line that cannot be run as written. The CLI prints the message and the usage, and exits with 2. */
2
+ export class UsageError extends Error {
3
+ usage;
4
+ constructor(message, usage) {
5
+ super(message);
6
+ this.usage = usage;
7
+ this.name = 'UsageError';
8
+ }
9
+ }
10
+ //# sourceMappingURL=usage.js.map