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,30 @@
1
+ // What counts as revealing a trigger, in the part that needs no file and no process. The adapter adds
2
+ // the rest: that the file is one the project's git already tracks (code-edit.ts).
3
+ import path from 'node:path';
4
+ /** What reveals each trigger, as the person reads it. */
5
+ export const TRIGGER_ACTIONS = {
6
+ 'code-edit': "a session once it edits a code file its project's git already tracks",
7
+ };
8
+ /**
9
+ * The extensions of the files the code-edit trigger counts as code: source files of programming
10
+ * languages, shell scripts and SQL. Left out on purpose: documents and reports (.md, .html, .txt),
11
+ * styles, data and configuration (.css, .json, .yaml, .toml, .xml, .csv), notebooks, and files with
12
+ * no extension, so writing a report, a note or a setting never counts as building.
13
+ */
14
+ export const CODE_EXTENSIONS = new Set([
15
+ // C family and the JVM
16
+ 'c', 'h', 'cc', 'cpp', 'cxx', 'hh', 'hpp', 'hxx', 'm', 'mm', 'cs', 'java', 'kt', 'kts', 'scala', 'groovy', 'gradle', 'clj', 'cljs', 'cljc',
17
+ // JavaScript and TypeScript
18
+ 'js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts', 'vue', 'svelte',
19
+ // Other languages
20
+ 'go', 'rs', 'swift', 'dart', 'py', 'pyi', 'rb', 'php', 'pl', 'pm', 'lua', 'r', 'jl', 'ex', 'exs', 'erl', 'hrl', 'hs', 'ml', 'mli',
21
+ 'fs', 'fsx', 'elm', 'nim', 'zig', 'sol',
22
+ // Shell and SQL
23
+ 'sh', 'bash', 'zsh', 'fish', 'ps1', 'psm1', 'sql',
24
+ ]);
25
+ /** Whether a file's name has a code extension, compared without case. */
26
+ export function hasCodeExtension(file) {
27
+ const ext = path.extname(file).slice(1).toLowerCase();
28
+ return ext !== '' && CODE_EXTENSIONS.has(ext);
29
+ }
30
+ //# sourceMappingURL=triggers.js.map
@@ -0,0 +1,74 @@
1
+ // Data the core works on. The core never reads files, the network, the clock or any state:
2
+ // the configuration loader builds these values, and the core only computes over them.
3
+ /**
4
+ * Where the delivered text will be read.
5
+ * attended a session someone is watching.
6
+ * unattended a session nobody is watching.
7
+ * subagent a subagent's task.
8
+ */
9
+ export const PLACES = ['attended', 'unattended', 'subagent'];
10
+ /** The word a rule's "where" may give alone for every place. */
11
+ export const ALL_PLACES = 'all';
12
+ /**
13
+ * Earlier names of places, still read where a place is written: in "where", on the command line, and
14
+ * in the decision log. "session" is the earlier name of "attended": configurations and logs written
15
+ * with it keep their meaning.
16
+ */
17
+ export const PLACE_ALIASES = { session: 'attended' };
18
+ /** A place written by its name or an earlier one, as its current name; null when it names no place. */
19
+ export function placeName(value) {
20
+ return PLACES.includes(value) ? value : (PLACE_ALIASES[value] ?? null);
21
+ }
22
+ /** Scope marker for a rule that applies to every task scope. */
23
+ export const ANY_SCOPE = '*';
24
+ /**
25
+ * What a session can do that shows what kind of task it is on, without anyone naming a scope.
26
+ * code-edit the session edited a code file the project's git already tracks.
27
+ * A rule that lists a trigger is also delivered to a session once the session has done it, whatever
28
+ * the session's scope. Only a session reveals a trigger; a subagent's scope comes from its task.
29
+ */
30
+ export const TRIGGERS = ['code-edit'];
31
+ /**
32
+ * Claude Code replaces hook context longer than this with a file path and a short preview,
33
+ * so every text the core can produce must fit.
34
+ */
35
+ export const DELIVERY_TEXT_LIMIT = 10000;
36
+ /** Room kept for the note that says the session's model changed (see switchNote). */
37
+ export const SWITCH_NOTE_RESERVE = 500;
38
+ /**
39
+ * Stands for every model in the models a conversation may hold rules of, when which ones cannot be
40
+ * told: a model-change note then retires the rules of every model but the session's own.
41
+ */
42
+ export const ANY_MODEL = '*';
43
+ /** The longest rule text, envelope included, a configuration may produce: the note must still fit. */
44
+ export const RULES_TEXT_LIMIT = DELIVERY_TEXT_LIMIT - SWITCH_NOTE_RESERVE;
45
+ export const DEFAULT_SUBAGENT_SETTINGS = { delivery: 'prompt', permission: 'allow', onMismatch: 'warn' };
46
+ /** Flags every scope matcher is compiled with: case-insensitive, Unicode-aware. */
47
+ export const MATCHER_FLAGS = 'iu';
48
+ export const DEFAULT_SESSION_SETTINGS = { unattendedWhenEnv: [], headlessIsUnattended: true };
49
+ /** Where routing can act: the session `noonsight run` starts, and the subagents a session starts. */
50
+ export const ROUTE_TARGETS = ['launcher', 'subagents'];
51
+ /** The effort levels Claude Code accepts, for --effort and for an agent call's effort parameter. */
52
+ export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
53
+ /**
54
+ * The model aliases a routing table may name. Each selects the latest model of its family, and both
55
+ * the claude --model option and the agent tool's model parameter accept them.
56
+ */
57
+ export const ROUTE_ALIASES = ['fable', 'opus', 'sonnet', 'haiku'];
58
+ export const DEFAULT_ROUTING_SETTINGS = {
59
+ enabled: false,
60
+ targets: ROUTE_TARGETS,
61
+ respectExplicit: true,
62
+ yieldWhenEnv: [],
63
+ table: new Map(),
64
+ default: null,
65
+ };
66
+ /**
67
+ * When the classifier, a small model asked through `claude -p`, picks a task's scope.
68
+ * off never: a scope comes only from NOONSIGHT_SCOPE, --scope or the matchers.
69
+ * fallback only for a task no explicit scope and no matcher placed.
70
+ * always for every task without an explicit scope, over the matchers.
71
+ */
72
+ export const CLASSIFIER_MODES = ['off', 'fallback', 'always'];
73
+ export const DEFAULT_CLASSIFIER_SETTINGS = { mode: 'off', model: 'haiku', effort: 'low', timeoutMs: 8000 };
74
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,200 @@
1
+ // What the subagent hooks keep between the call that starts a subagent, its start, and its result.
2
+ //
3
+ // agent-calls/<tool_use_id>.json written before the subagent starts: the model noonsight predicted,
4
+ // and the rules to hand the subagent when it starts. The result of
5
+ // the same call, which carries the same tool_use_id, compares the
6
+ // prediction with the model that ran.
7
+ // agent-pools/<session id>.json the calls of a session whose subagent has not started yet, which a
8
+ // subagent's start chooses from, since its input does not name the
9
+ // call that started it. Read and changed under agent-pools/<session
10
+ // id>.lock only.
11
+ // agent-starts/<agent id>.json written when a subagent starts: the call it was matched with and
12
+ // the rules it was given, given again when the same subagent resumes.
13
+ // agent-links/<agent id>.json written when a call's result names its subagent before that
14
+ // subagent's start has been seen, so the start finds its own call.
15
+ // agents/<agent id>.json written when a call's result names the subagent and the model it
16
+ // started on, so a call made inside that subagent knows the model it
17
+ // would inherit.
18
+ // agent-pending/<agent id>.json written when a subagent's start could not tell its call from others
19
+ // that need other rules, so it got none: the calls it may have come
20
+ // from, until a later hook inside that subagent finds its own call.
21
+ //
22
+ // Every key comes from Claude Code's hook input, and every kind of record is pruned with the others.
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { writeFileAtomic } from './files.js';
26
+ const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
27
+ function keyed(stateDir, dir, id, ext = '.json') {
28
+ return id !== null && SAFE_ID.test(id) ? path.join(stateDir, dir, `${id}${ext}`) : null;
29
+ }
30
+ export function agentCallFile(stateDir, toolUseId) {
31
+ return keyed(stateDir, 'agent-calls', toolUseId);
32
+ }
33
+ export function agentFile(stateDir, agentId) {
34
+ return keyed(stateDir, 'agents', agentId);
35
+ }
36
+ export function poolFile(stateDir, sessionId) {
37
+ return keyed(stateDir, 'agent-pools', sessionId);
38
+ }
39
+ export function agentStartFile(stateDir, agentId) {
40
+ return keyed(stateDir, 'agent-starts', agentId);
41
+ }
42
+ export function agentLinkFile(stateDir, agentId) {
43
+ return keyed(stateDir, 'agent-links', agentId);
44
+ }
45
+ export function agentPendingFile(stateDir, agentId) {
46
+ return keyed(stateDir, 'agent-pending', agentId);
47
+ }
48
+ export function readAgentPending(file) {
49
+ const v = readJson(file);
50
+ return v !== null && typeof v.session_id === 'string' && Array.isArray(v.calls) && v.calls.every((c) => typeof c === 'string')
51
+ ? v
52
+ : null;
53
+ }
54
+ export function readAgentCall(file) {
55
+ const v = readJson(file);
56
+ if (v !== null &&
57
+ (v.session_id === null || typeof v.session_id === 'string') &&
58
+ typeof v.subagent_type === 'string' &&
59
+ (v.predicted === null || typeof v.predicted === 'string') &&
60
+ (v.status === 'matched' || v.status === 'none' || v.status === 'undeclared') &&
61
+ (v.sha256 === null || typeof v.sha256 === 'string') &&
62
+ (v.delivered === 'at-start' || v.delivered === 'rules' || v.delivered === 'already-delivered' || v.delivered === 'nothing') &&
63
+ (v.text === undefined || typeof v.text === 'string') &&
64
+ (v.rules === undefined || (Array.isArray(v.rules) && v.rules.every((r) => typeof r === 'string'))) &&
65
+ (v.scope === undefined || v.scope === null || typeof v.scope === 'string') &&
66
+ (v.routing === undefined || typeof v.routing === 'string') &&
67
+ (v.routing_reason === undefined || typeof v.routing_reason === 'string'))
68
+ return v;
69
+ return null;
70
+ }
71
+ export function readAgentModel(file) {
72
+ const v = readJson(file);
73
+ return v !== null && typeof v.model === 'string' && v.model !== '' ? v.model : null;
74
+ }
75
+ export function readAgentStart(file) {
76
+ const v = readJson(file);
77
+ if (v !== null &&
78
+ typeof v.session_id === 'string' &&
79
+ typeof v.subagent_type === 'string' &&
80
+ (v.match === 'single' || v.match === 'result' || v.match === 'shared') &&
81
+ Array.isArray(v.calls) &&
82
+ v.calls.every((c) => typeof c === 'string') &&
83
+ (v.text === null || typeof v.text === 'string'))
84
+ return v;
85
+ return null;
86
+ }
87
+ export function readAgentLink(file) {
88
+ const v = readJson(file);
89
+ return v !== null && typeof v.call === 'string' ? v : null;
90
+ }
91
+ /** The pool as recorded; an empty pool when there is none or it cannot be read. A count no group carries is ignored. */
92
+ export function readPool(file) {
93
+ const v = readJson(file);
94
+ const optional = (x) => x === undefined || typeof x === 'string';
95
+ const open = Array.isArray(v?.open)
96
+ ? v.open.filter((c) => isObject(c) &&
97
+ typeof c.id === 'string' &&
98
+ typeof c.type === 'string' &&
99
+ typeof c.at === 'string' &&
100
+ optional(c.name) &&
101
+ optional(c.input) &&
102
+ optional(c.by) &&
103
+ optional(c.held))
104
+ : [];
105
+ const groups = Array.isArray(v?.groups)
106
+ ? v.groups.filter((g) => isObject(g) &&
107
+ Array.isArray(g.calls) &&
108
+ g.calls.every((c) => typeof c === 'string') &&
109
+ typeof g.started === 'number' &&
110
+ Number.isInteger(g.started) &&
111
+ g.started > 0)
112
+ : [];
113
+ return { open, groups };
114
+ }
115
+ export function writeRecord(file, record) {
116
+ if (file === null)
117
+ return;
118
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
119
+ writeFileAtomic(file, `${JSON.stringify(record)}\n`, 0o600);
120
+ }
121
+ export function removeRecord(file) {
122
+ if (file === null)
123
+ return;
124
+ try {
125
+ fs.rmSync(file, { force: true });
126
+ }
127
+ catch {
128
+ // Pruned later.
129
+ }
130
+ }
131
+ /** A lock older than this was left by a hook that was stopped while holding it. */
132
+ const LOCK_STALE_MS = 5000;
133
+ /** How long a hook waits for another hook of the same session to release the lock. */
134
+ const LOCK_WAIT_MS = 3000;
135
+ const PAUSE = new Int32Array(new SharedArrayBuffer(4));
136
+ /** Pause the hook, which runs synchronously, for a few milliseconds. */
137
+ export function pause(ms) {
138
+ Atomics.wait(PAUSE, 0, 0, ms);
139
+ }
140
+ /**
141
+ * Change a session's pool. The subagent hooks of one session run at the same time, one process each,
142
+ * so the pool is read and written under a lock: a directory, which only one process can create. The
143
+ * change returns the new pool, or null to leave it as it was, and a value for the caller.
144
+ */
145
+ export function changePool(stateDir, sessionId, change) {
146
+ const file = poolFile(stateDir, sessionId);
147
+ if (file === null)
148
+ throw new Error('the session id cannot name a file');
149
+ const lock = `${file.slice(0, -'.json'.length)}.lock`;
150
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
151
+ const deadline = Date.now() + LOCK_WAIT_MS;
152
+ for (;;) {
153
+ try {
154
+ fs.mkdirSync(lock, { mode: 0o700 });
155
+ break;
156
+ }
157
+ catch (e) {
158
+ if (e.code !== 'EEXIST')
159
+ throw e;
160
+ }
161
+ try {
162
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS)
163
+ fs.rmSync(lock, { recursive: true, force: true });
164
+ }
165
+ catch {
166
+ // Released meanwhile.
167
+ }
168
+ if (Date.now() > deadline)
169
+ throw new Error("another hook of the session held its subagent records too long");
170
+ pause(5);
171
+ }
172
+ try {
173
+ const { pool, value } = change(readPool(file));
174
+ if (pool !== null) {
175
+ if (pool.open.length === 0)
176
+ removeRecord(file);
177
+ else
178
+ writeRecord(file, pool);
179
+ }
180
+ return value;
181
+ }
182
+ finally {
183
+ fs.rmSync(lock, { recursive: true, force: true });
184
+ }
185
+ }
186
+ function readJson(file) {
187
+ if (file === null)
188
+ return null;
189
+ try {
190
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
191
+ return isObject(value) ? value : null;
192
+ }
193
+ catch {
194
+ return null;
195
+ }
196
+ }
197
+ function isObject(value) {
198
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
199
+ }
200
+ //# sourceMappingURL=agents.js.map
@@ -0,0 +1,80 @@
1
+ // One claim per event occurrence. Claude Code runs the hooks of every place noonsight is installed in,
2
+ // a settings file and a plugin alike, so two installs would each deliver the same event, and change the
3
+ // records of open subagent calls at the same time. Both copies get the same bytes on standard input from
4
+ // the same Claude Code process, which identifies the occurrence, so the first copy to claim it runs and
5
+ // the others do nothing:
6
+ //
7
+ // nothing claimed it, or the claim is older than WINDOW_MS: claim it and run
8
+ // another kind of install claimed it: do nothing
9
+ // this kind of install claimed it: the same input came again, so claim it again and run
10
+ //
11
+ // A failure to read, write or lock a claim runs the hook: delivering twice is the safe direction.
12
+ import { createHash } from 'node:crypto';
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { writeFileAtomic } from './files.js';
16
+ /** Far longer than the copies of one occurrence are apart: Claude Code starts them together and stops each after 10 seconds. */
17
+ const WINDOW_MS = 60_000;
18
+ /** How long a copy waits for the lock before it runs without a claim. */
19
+ const LOCK_WAIT_MS = 500;
20
+ /** A lock this old was left by a copy that was stopped while it held it. */
21
+ const LOCK_STALE_MS = 5_000;
22
+ const WAIT = new Int32Array(new SharedArrayBuffer(4));
23
+ /** Whether this copy is the one that runs the occurrence. */
24
+ export function claimOccurrence(stateDir, kind, o, now) {
25
+ const key = createHash('sha256').update(`${o.event}\0${o.parentPid}\0${o.input}`).digest('hex');
26
+ const dir = path.join(stateDir, 'claims');
27
+ const file = path.join(dir, `${key}.json`);
28
+ const lock = path.join(dir, `${key}.lock`);
29
+ try {
30
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
31
+ if (!takeLock(lock))
32
+ return true;
33
+ try {
34
+ const claim = readClaim(file);
35
+ if (claim !== null && claim.kind !== kind && Math.abs(now - claim.at) < WINDOW_MS)
36
+ return false;
37
+ writeFileAtomic(file, `${JSON.stringify({ kind, at: now })}\n`, 0o600);
38
+ return true;
39
+ }
40
+ finally {
41
+ fs.rmSync(lock, { force: true });
42
+ }
43
+ }
44
+ catch {
45
+ return true;
46
+ }
47
+ }
48
+ function readClaim(file) {
49
+ try {
50
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
51
+ return typeof value.kind === 'string' && typeof value.at === 'number' ? { kind: value.kind, at: value.at } : null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ function takeLock(lock) {
58
+ const until = Date.now() + LOCK_WAIT_MS;
59
+ for (;;) {
60
+ try {
61
+ fs.writeFileSync(lock, '', { flag: 'wx', mode: 0o600 });
62
+ return true;
63
+ }
64
+ catch (e) {
65
+ if (e.code !== 'EEXIST')
66
+ throw e;
67
+ }
68
+ try {
69
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS)
70
+ fs.rmSync(lock, { force: true });
71
+ }
72
+ catch {
73
+ // Released meanwhile.
74
+ }
75
+ if (Date.now() >= until)
76
+ return false;
77
+ Atomics.wait(WAIT, 0, 0, 2);
78
+ }
79
+ }
80
+ //# sourceMappingURL=claims.js.map
@@ -0,0 +1,84 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ /**
5
+ * Replace a file in one step: write a hidden temporary file next to it, then rename it over the
6
+ * target. A reader, such as Claude Code watching its settings, sees the old content or the new
7
+ * content and never a partial file. The temporary name starts with a dot and does not end in
8
+ * .json, so Claude Code never reads it from a managed-settings.d directory.
9
+ */
10
+ export function writeFileAtomic(file, content, mode) {
11
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
12
+ fs.writeFileSync(tmp, content, { mode, flag: 'wx' });
13
+ try {
14
+ fs.chmodSync(tmp, mode);
15
+ fs.renameSync(tmp, file);
16
+ }
17
+ catch (e) {
18
+ fs.rmSync(tmp, { force: true });
19
+ throw e;
20
+ }
21
+ }
22
+ /**
23
+ * Create a file in one step, or return false when it already exists: its content is written to a hidden
24
+ * temporary file, which is then linked to the name, so no reader sees part of it and nothing is replaced.
25
+ */
26
+ export function createFileAtomic(file, content, mode = 0o644) {
27
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
28
+ fs.writeFileSync(tmp, content, { mode, flag: 'wx' });
29
+ try {
30
+ try {
31
+ fs.linkSync(tmp, file);
32
+ }
33
+ catch (e) {
34
+ if (e.code === 'EEXIST')
35
+ return false;
36
+ // A file system without hard links: created in place, still without replacing anything.
37
+ fs.writeFileSync(file, content, { mode, flag: 'wx' });
38
+ }
39
+ return true;
40
+ }
41
+ catch (e) {
42
+ if (e.code === 'EEXIST')
43
+ return false;
44
+ throw e;
45
+ }
46
+ finally {
47
+ fs.rmSync(tmp, { force: true });
48
+ }
49
+ }
50
+ /** The file's permission bits, or the fallback when the file does not exist. */
51
+ export function modeOf(file, fallback) {
52
+ try {
53
+ return fs.statSync(file).mode & 0o777;
54
+ }
55
+ catch {
56
+ return fallback;
57
+ }
58
+ }
59
+ /** A permission error: the directory or file cannot be written by this account. */
60
+ export function isPermissionError(e) {
61
+ const code = e?.code;
62
+ return code === 'EACCES' || code === 'EPERM' || code === 'EROFS';
63
+ }
64
+ export function readJsonFile(file) {
65
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
66
+ }
67
+ /**
68
+ * Create a directory and any missing parents with exactly this mode. The mode is set after each
69
+ * directory is created, so a restrictive umask (such as 077 under sudo) cannot hide a directory that
70
+ * every account must be able to read.
71
+ */
72
+ export function mkdirWithMode(dir, mode) {
73
+ const missing = [];
74
+ for (let d = path.resolve(dir); !fs.existsSync(d); d = path.dirname(d)) {
75
+ missing.unshift(d);
76
+ if (path.dirname(d) === d)
77
+ break;
78
+ }
79
+ for (const d of missing) {
80
+ fs.mkdirSync(d, { mode });
81
+ fs.chmodSync(d, mode);
82
+ }
83
+ }
84
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1,29 @@
1
+ // The Claude Code configuration directories this account installed noonsight into with --account.
2
+ // `noonsight check` reads the list to know which settings files to look at; the machine-wide install
3
+ // lives at a fixed path and needs no record.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { writeFileAtomic } from './files.js';
7
+ const FILE = 'installs.json';
8
+ /**
9
+ * What runs a hook, as the decision log records it: a machine-wide install, an install in a configuration
10
+ * directory, or the Claude Code plugin.
11
+ */
12
+ export const INSTALL_KINDS = ['managed', 'account', 'plugin'];
13
+ export function accountInstalls(stateDir) {
14
+ try {
15
+ const value = JSON.parse(fs.readFileSync(path.join(stateDir, FILE), 'utf8'));
16
+ return Array.isArray(value.accounts) ? value.accounts.filter((a) => typeof a === 'string') : [];
17
+ }
18
+ catch {
19
+ return [];
20
+ }
21
+ }
22
+ export function recordAccountInstall(stateDir, configDir, installed) {
23
+ const others = accountInstalls(stateDir).filter((d) => d !== configDir);
24
+ const accounts = installed ? [...others, configDir] : others;
25
+ fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
26
+ writeFileAtomic(path.join(stateDir, FILE), `${JSON.stringify({ schema: 1, accounts }, null, 2)}\n`, 0o600);
27
+ return accounts;
28
+ }
29
+ //# sourceMappingURL=installs.js.map
@@ -0,0 +1,90 @@
1
+ // The decision log: one JSON object per line, one line per decision a hook makes. It is only ever
2
+ // appended to, so it can be read with any line tool while sessions write to it.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ export const LOG_FILE = 'decisions.jsonl';
6
+ export const ROTATED_LOG_FILE = 'decisions.1.jsonl';
7
+ /** Past this size the log is moved to decisions.1.jsonl (replacing an older one) and a new log starts. */
8
+ export const LOG_MAX_BYTES = 20 * 1024 * 1024;
9
+ export function logFile(stateDir) {
10
+ return path.join(stateDir, LOG_FILE);
11
+ }
12
+ /** Append one decision. The caller decides what a failure means; hooks ignore it. */
13
+ export function appendDecision(stateDir, record) {
14
+ fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
15
+ const file = logFile(stateDir);
16
+ try {
17
+ if (fs.statSync(file).size >= LOG_MAX_BYTES)
18
+ fs.renameSync(file, path.join(stateDir, ROTATED_LOG_FILE));
19
+ }
20
+ catch {
21
+ // No log yet, or another session rotated it first.
22
+ }
23
+ // One write call per line, opened for append, so lines from concurrent sessions never interleave.
24
+ fs.appendFileSync(file, `${JSON.stringify(record)}\n`, { mode: 0o600 });
25
+ }
26
+ /**
27
+ * Every readable decision, oldest first: the moved-away log, then the current one. Lines that are
28
+ * not a JSON object, such as a line torn by a full disk, are skipped.
29
+ */
30
+ export function readDecisions(stateDir) {
31
+ return [path.join(stateDir, ROTATED_LOG_FILE), logFile(stateDir)].flatMap(readDecisionFile);
32
+ }
33
+ /** Every readable decision in one log file, oldest first; none when the file cannot be read. */
34
+ export function readDecisionFile(file) {
35
+ let text;
36
+ try {
37
+ text = fs.readFileSync(file, 'utf8');
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ const records = [];
43
+ for (const line of text.split('\n')) {
44
+ if (!line)
45
+ continue;
46
+ try {
47
+ const value = JSON.parse(line);
48
+ if (value && typeof value === 'object' && !Array.isArray(value))
49
+ records.push(value);
50
+ }
51
+ catch {
52
+ // A torn or foreign line.
53
+ }
54
+ }
55
+ return records;
56
+ }
57
+ /** The last line of the log, parsed, or null when there is no log or no readable line. */
58
+ export function lastDecision(stateDir) {
59
+ let text;
60
+ try {
61
+ // Only the end of the file is read, so the cost does not grow with the log.
62
+ const fd = fs.openSync(logFile(stateDir), 'r');
63
+ try {
64
+ const size = fs.fstatSync(fd).size;
65
+ const length = Math.min(size, 64 * 1024);
66
+ const buffer = Buffer.alloc(length);
67
+ fs.readSync(fd, buffer, 0, length, size - length);
68
+ text = buffer.toString('utf8');
69
+ }
70
+ finally {
71
+ fs.closeSync(fd);
72
+ }
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ const lines = text.trimEnd().split('\n');
78
+ for (let i = lines.length - 1; i >= 0; i--) {
79
+ try {
80
+ const value = JSON.parse(lines[i] ?? '');
81
+ if (value && typeof value === 'object' && !Array.isArray(value))
82
+ return value;
83
+ }
84
+ catch {
85
+ // A torn or foreign line; look further back.
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1,35 @@
1
+ // The Node.js the plugin's hooks run on. A Claude Code that was not started from a shell may have no
2
+ // `node` on its PATH, so each hook the plugin runs records the one it runs on, and the plugin's launcher
3
+ // (scripts/noonsight) looks there before it searches.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { dataDir } from '../config/paths.js';
7
+ import { writeFileAtomic } from './files.js';
8
+ export function nodeFile(home) {
9
+ return path.join(dataDir(home), 'node');
10
+ }
11
+ /** The Node.js recorded, or null when none is recorded or it can no longer be run. */
12
+ export function recordedNode(home) {
13
+ try {
14
+ const node = fs.readFileSync(nodeFile(home), 'utf8').trim();
15
+ fs.accessSync(node, fs.constants.X_OK);
16
+ return node === '' ? null : node;
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ /** Record this Node.js, unless one that can be run is recorded already. A failure only costs the search again. */
23
+ export function recordNode(home, node) {
24
+ try {
25
+ if (recordedNode(home) !== null)
26
+ return;
27
+ const file = nodeFile(home);
28
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
29
+ writeFileAtomic(file, `${node}\n`, 0o644);
30
+ }
31
+ catch {
32
+ // The launcher searches again.
33
+ }
34
+ }
35
+ //# sourceMappingURL=node.js.map