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,347 @@
1
+ // Subagent definitions, read where Claude Code reads them
2
+ // (https://code.claude.com/docs/en/sub-agents, "Choose the subagent scope"). When several places
3
+ // define one name, the highest-ranked wins:
4
+ //
5
+ // 1. managed: .claude/agents/ in the managed settings directory;
6
+ // 2. the --agents option of the claude command, inline JSON or, in claude -p, a JSON file;
7
+ // 3. project: every .claude/agents/ from the project directory up to the repository root, the
8
+ // closest first, then .claude/agents/ in each directory given with --add-dir;
9
+ // 4. user: agents/ in the Claude Code configuration directory;
10
+ // 5. a plugin's agents, whose names carry the plugin's name: plugin:agent.
11
+ //
12
+ // Managed, project and user folders are scanned recursively, and a subagent there is known by the name
13
+ // in its frontmatter. --setting-sources leaves out the project and user folders it does not list. A
14
+ // plugin's agents are the files its manifest lists under "agents", else every Markdown file under its
15
+ // agents/ folder, where each subfolder adds a part to the name; the last part is the frontmatter's
16
+ // name, else the file's name. Claude Code 2.1.330 orders the places so, as its bundled code reads and a
17
+ // stub session confirmed.
18
+ //
19
+ // The plugins read are those given with --plugin-dir or --plugin-dir-no-mcp, those in
20
+ // CLAUDE_CODE_PLUGIN_DIRS, and those installed from a marketplace (plugins/installed_plugins.json in the
21
+ // configuration directory) that the settings enable for the project. Plugins Claude Code gets any
22
+ // other way, such as ones an organization syncs to its members, are not read.
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { repositoryRoot } from '../../config/project.js';
26
+ import { NO_BOUNDARIES, optionValues, readObject, safeManagedDir, settingSources } from './launch.js';
27
+ import { enabledPlugins, installedPlugins } from './plugins.js';
28
+ import { isObject } from './settings.js';
29
+ const MAX_DEPTH = 6;
30
+ const MAX_FILES = 2000;
31
+ const HEAD_BYTES = 8192;
32
+ /** A lookup by subagent name, reading each place once, and only as far as the name needs. */
33
+ export function definitionFinder(places) {
34
+ const cmd = once(places.commandLine);
35
+ const flag = once(() => flagAgents(cmd(), places.projectDir));
36
+ const sources = once(() => settingSources(cmd()));
37
+ const plugins = once(() => pluginRoots(places, cmd()));
38
+ const seen = new Map();
39
+ const find = (name) => {
40
+ const managed = managedAgentsDir(places.env);
41
+ if (managed !== null) {
42
+ const found = findIn(managed, name, 'managed');
43
+ if (found !== null)
44
+ return { kind: 'found', definition: found };
45
+ }
46
+ const f = flag();
47
+ if (f.kind === 'unread')
48
+ return f;
49
+ const fromFlag = f.kind === 'found' ? f.definitions.get(name) : undefined;
50
+ if (fromFlag !== undefined)
51
+ return { kind: 'found', definition: fromFlag };
52
+ const s = sources();
53
+ const reads = (source) => s.kind !== 'listed' || s.sources.has(source);
54
+ if (reads('project'))
55
+ for (const dir of projectDirs(places.projectDir, cmd())) {
56
+ const found = findIn(dir, name, 'project');
57
+ if (found !== null)
58
+ return { kind: 'found', definition: found };
59
+ }
60
+ if (reads('user')) {
61
+ const found = findIn(path.join(places.configDir, 'agents'), name, 'user');
62
+ if (found !== null)
63
+ return { kind: 'found', definition: found };
64
+ }
65
+ if (name.includes(':'))
66
+ return pluginDefinition(plugins(), name);
67
+ return { kind: 'none' };
68
+ };
69
+ return (name) => {
70
+ if (!seen.has(name))
71
+ seen.set(name, find(name));
72
+ return seen.get(name);
73
+ };
74
+ }
75
+ /** .claude/agents/ in the managed settings directory. */
76
+ function managedAgentsDir(env) {
77
+ const dir = safeManagedDir(env);
78
+ return dir === null ? null : path.join(dir, '.claude', 'agents');
79
+ }
80
+ /** Every project folder of definitions, the highest-ranked first. */
81
+ function projectDirs(projectDir, cmd) {
82
+ const dirs = [];
83
+ if (projectDir !== null) {
84
+ const start = path.resolve(projectDir);
85
+ const top = repositoryRoot(start);
86
+ for (let d = start;; d = path.dirname(d)) {
87
+ dirs.push(path.join(d, '.claude', 'agents'));
88
+ if (d === top)
89
+ break;
90
+ }
91
+ }
92
+ for (const d of addDirs(cmd, projectDir))
93
+ dirs.push(path.join(d, '.claude', 'agents'));
94
+ return [...new Set(dirs)];
95
+ }
96
+ /** The directories given with --add-dir, which takes one or more directories each time it is given. */
97
+ function addDirs(cmd, cwd) {
98
+ if (cmd === null)
99
+ return [];
100
+ const dirs = [];
101
+ for (let i = 0; i < cmd.args.length; i++) {
102
+ const a = cmd.args[i] ?? '';
103
+ if (a === '--' && cmd.exact)
104
+ break;
105
+ if (a.startsWith('--add-dir='))
106
+ dirs.push(a.slice('--add-dir='.length));
107
+ else if (a === '--add-dir')
108
+ for (let j = i + 1; j < cmd.args.length && !(cmd.args[j] ?? '-').startsWith('-'); j++)
109
+ dirs.push(cmd.args[j] ?? '');
110
+ }
111
+ return dirs.filter((d) => d !== '').map((d) => path.resolve(cwd ?? '/', d));
112
+ }
113
+ function flagAgents(cmd, cwd) {
114
+ if (cmd === null)
115
+ return { kind: 'none' };
116
+ const values = cmd.exact ? optionValues(cmd, '--agents').slice(-1) : [...new Set(looseOption(cmd, '--agents'))];
117
+ if (values.length === 0)
118
+ return { kind: 'none' };
119
+ if (values.length > 1)
120
+ return { kind: 'unread', why: `the --agents value cannot be read: ${NO_BOUNDARIES}` };
121
+ const value = values[0] ?? '';
122
+ const inline = value.trimStart().startsWith('{');
123
+ let parsed = null;
124
+ if (inline)
125
+ try {
126
+ parsed = JSON.parse(value);
127
+ }
128
+ catch {
129
+ parsed = null;
130
+ }
131
+ else
132
+ parsed = readObject(path.resolve(cwd ?? '/', value));
133
+ if (!isObject(parsed))
134
+ return { kind: 'unread', why: inline ? 'the --agents value is not a JSON object' : `the --agents file ${value} cannot be read` };
135
+ const definitions = new Map();
136
+ for (const [name, d] of Object.entries(parsed))
137
+ if (isObject(d))
138
+ definitions.set(name, {
139
+ file: inline ? '--agents' : path.resolve(cwd ?? '/', value),
140
+ source: 'flag',
141
+ model: typeof d.model === 'string' && d.model.trim() !== '' ? d.model.trim() : null,
142
+ effort: typeof d.effort === 'string' && d.effort.trim() !== '' ? d.effort.trim() : null,
143
+ });
144
+ return { kind: 'found', definitions };
145
+ }
146
+ /**
147
+ * The values an option may have had on a command line read without argument boundaries, as `ps` prints
148
+ * it on macOS: the arguments joined by spaces, with control characters such as a newline written as a
149
+ * backslash and three octal digits. A value that opens a JSON object runs to the brace that closes it;
150
+ * any other value runs to the next space.
151
+ */
152
+ function looseOption(cmd, name) {
153
+ const text = cmd.args.join(' ').replace(/\\0([0-7]{2})/g, (_, o) => String.fromCharCode(parseInt(o, 8)));
154
+ const values = [];
155
+ const at = new RegExp(`(?:^|\\s)${name}(?:=|\\s+)`, 'g');
156
+ for (let m = at.exec(text); m !== null; m = at.exec(text)) {
157
+ const rest = text.slice(m.index + m[0].length);
158
+ if (rest.startsWith('{')) {
159
+ const end = objectEnd(rest);
160
+ values.push(end === null ? rest : rest.slice(0, end));
161
+ }
162
+ else {
163
+ const token = /^\S+/.exec(rest)?.[0];
164
+ if (token !== undefined)
165
+ values.push(token);
166
+ }
167
+ }
168
+ return values;
169
+ }
170
+ /** The index just past the brace that closes the JSON object `text` starts with, or null. */
171
+ function objectEnd(text) {
172
+ let depth = 0;
173
+ let quoted = false;
174
+ for (let i = 0; i < text.length; i++) {
175
+ const c = text[i];
176
+ if (quoted) {
177
+ if (c === '\\')
178
+ i++;
179
+ else if (c === '"')
180
+ quoted = false;
181
+ }
182
+ else if (c === '"')
183
+ quoted = true;
184
+ else if (c === '{')
185
+ depth++;
186
+ else if (c === '}' && --depth === 0)
187
+ return i + 1;
188
+ }
189
+ return null;
190
+ }
191
+ function pluginRoots(places, cmd) {
192
+ const cwd = places.projectDir;
193
+ const inline = [
194
+ ...(cmd === null ? [] : [...optionValues(cmd, '--plugin-dir'), ...optionValues(cmd, '--plugin-dir-no-mcp')]),
195
+ ...(places.env.CLAUDE_CODE_PLUGIN_DIRS ?? '').split(path.delimiter).map((d) => d.trim()),
196
+ ]
197
+ .filter((d) => d !== '')
198
+ .map((d) => path.resolve(cwd ?? '/', d));
199
+ const roots = inline.map((dir) => ({ dir, name: manifestOf(dir)?.name ?? path.basename(dir) }));
200
+ const enabled = enabledPlugins(places, cmd);
201
+ return [...roots, ...installedPlugins(places).filter((p) => enabled.get(p.id) === true).map((p) => ({ name: p.name, dir: p.dir }))];
202
+ }
203
+ function manifestOf(dir) {
204
+ const m = readObject(path.join(dir, '.claude-plugin', 'plugin.json'));
205
+ if (m === null)
206
+ return null;
207
+ const agents = typeof m.agents === 'string' ? [m.agents] : Array.isArray(m.agents) ? m.agents.filter((a) => typeof a === 'string') : undefined;
208
+ return { ...(typeof m.name === 'string' && m.name !== '' ? { name: m.name } : {}), ...(agents !== undefined ? { agents } : {}) };
209
+ }
210
+ /**
211
+ * The definition of plugin:...:agent among the plugins read. Two plugins of that name that define it
212
+ * differently leave it unread, since which one Claude Code loads is not known; a name none of them
213
+ * defines may come from a plugin noonsight does not read.
214
+ */
215
+ function pluginDefinition(roots, name) {
216
+ const plugin = name.slice(0, name.indexOf(':'));
217
+ const found = [];
218
+ for (const root of roots) {
219
+ if (root.name !== plugin)
220
+ continue;
221
+ const d = pluginAgent(root, name);
222
+ if (d !== null)
223
+ found.push(d);
224
+ }
225
+ const first = found[0];
226
+ if (first === undefined)
227
+ return { kind: 'unread', why: `no plugin noonsight reads defines ${name}` };
228
+ if (found.some((d) => d.model !== first.model || d.effort !== first.effort))
229
+ return { kind: 'unread', why: `more than one plugin named ${plugin} defines ${name}, with different models or efforts` };
230
+ return { kind: 'found', definition: first };
231
+ }
232
+ function pluginAgent(root, name) {
233
+ const manifest = manifestOf(root.dir);
234
+ if (manifest?.agents !== undefined) {
235
+ for (const file of manifest.agents) {
236
+ const full = path.resolve(root.dir, file);
237
+ const d = agentFile(full, [root.name], name, 'plugin');
238
+ if (d !== null)
239
+ return d;
240
+ }
241
+ return null;
242
+ }
243
+ let seen = 0;
244
+ const walk = (dir, parts, depth) => {
245
+ for (const e of entries(dir)) {
246
+ if (++seen > MAX_FILES)
247
+ return null;
248
+ const file = path.join(dir, e.name);
249
+ if (e.isFile() && e.name.endsWith('.md')) {
250
+ const d = agentFile(file, parts, name, 'plugin');
251
+ if (d !== null)
252
+ return d;
253
+ }
254
+ else if (e.isDirectory() && !e.name.startsWith('.') && depth < MAX_DEPTH) {
255
+ const d = walk(file, [...parts, e.name], depth + 1);
256
+ if (d !== null)
257
+ return d;
258
+ }
259
+ }
260
+ return null;
261
+ };
262
+ return walk(path.join(root.dir, 'agents'), [root.name], 0);
263
+ }
264
+ /** The definition in a plugin's agent file, when its full name, the prefix and its own name, is `name`. */
265
+ function agentFile(file, prefix, name, source) {
266
+ const fm = frontmatter(readHead(file));
267
+ const own = fm?.name ?? path.basename(file).replace(/\.md$/, '');
268
+ if ([...prefix, own].join(':') !== name)
269
+ return null;
270
+ return { file, source, model: fm?.model ?? null, effort: fm?.effort ?? null };
271
+ }
272
+ // ---------------------------------------------------------------------------------------------
273
+ // Folders of Markdown definitions, known by the name in their frontmatter.
274
+ function findIn(root, name, source) {
275
+ let seen = 0;
276
+ const walk = (dir, depth) => {
277
+ for (const e of entries(dir)) {
278
+ if (++seen > MAX_FILES)
279
+ return null;
280
+ const file = path.join(dir, e.name);
281
+ if (e.isFile() && e.name.endsWith('.md')) {
282
+ const fm = frontmatter(readHead(file));
283
+ if (fm !== null && fm.name === name)
284
+ return { file, source, model: fm.model ?? null, effort: fm.effort ?? null };
285
+ }
286
+ else if (e.isDirectory() && depth < MAX_DEPTH) {
287
+ const found = walk(file, depth + 1);
288
+ if (found !== null)
289
+ return found;
290
+ }
291
+ }
292
+ return null;
293
+ };
294
+ return walk(root, 0);
295
+ }
296
+ function entries(dir) {
297
+ try {
298
+ return fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
299
+ }
300
+ catch {
301
+ return [];
302
+ }
303
+ }
304
+ /** The top-level name, model and effort of a definition's YAML frontmatter, or null when it has none. */
305
+ export function frontmatter(text) {
306
+ const m = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
307
+ if (!m)
308
+ return null;
309
+ const fields = {};
310
+ for (const line of (m[1] ?? '').split(/\r?\n/)) {
311
+ const f = /^(name|model|effort):[ \t]*(.*?)[ \t]*(?:#.*)?$/.exec(line);
312
+ if (!f)
313
+ continue;
314
+ const value = (f[2] ?? '').replace(/^(['"])(.*)\1$/, '$2').trim();
315
+ if (value)
316
+ fields[f[1]] = value;
317
+ }
318
+ return fields;
319
+ }
320
+ function readHead(file) {
321
+ try {
322
+ const fd = fs.openSync(file, 'r');
323
+ try {
324
+ const buffer = Buffer.alloc(HEAD_BYTES);
325
+ const n = fs.readSync(fd, buffer, 0, HEAD_BYTES, 0);
326
+ return buffer.toString('utf8', 0, n);
327
+ }
328
+ finally {
329
+ fs.closeSync(fd);
330
+ }
331
+ }
332
+ catch {
333
+ return '';
334
+ }
335
+ }
336
+ function once(f) {
337
+ let done = false;
338
+ let value;
339
+ return () => {
340
+ if (!done) {
341
+ value = f();
342
+ done = true;
343
+ }
344
+ return value;
345
+ };
346
+ }
347
+ //# sourceMappingURL=definitions.js.map
@@ -0,0 +1,132 @@
1
+ // The conversation a fork copied. Claude Code forks a conversation three ways, each a session with a
2
+ // new id whose SessionStart has the source "fork":
3
+ //
4
+ // claude --resume <id> --fork-session a new process
5
+ // claude --continue --fork-session a new process
6
+ // /branch the same process
7
+ // /fork a background session
8
+ //
9
+ // The new id has no record of its own, while the conversation it starts with holds what the original
10
+ // held: the rules delivered to it, a delivery that may not have arrived yet, and the triggers it
11
+ // revealed. A fork in a new process also runs on the model the original last answered on, as a resume
12
+ // does. When the hook runs, the fork's own transcript holds the copied conversation only after /branch,
13
+ // so the original is found, in this order:
14
+ //
15
+ // 1. the fork's transcript: the entries /branch copies name the original in `forkedFrom.sessionId`;
16
+ // 2. the background job of /fork: `forkParentSessionId` in `state.json`, in the directory
17
+ // CLAUDE_JOB_DIR names, which also gives the model the job was started with (`--model` among its
18
+ // `respawnFlags`);
19
+ // 3. the Claude Code command line, with `--fork-session`: the session id given to `--resume` or
20
+ // `-r`; or, with `--continue` or `-c`, the transcript Claude Code continues, the most recently
21
+ // written one in the fork's transcript folder other than the fork's own.
22
+ //
23
+ // None of these is documented by Claude Code; each was recorded on 2.1.330 (docs/verification/claude-code.md).
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { optionCandidates } from './launch.js';
27
+ const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
28
+ /** A Claude Code session id. */
29
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
30
+ /** How far into the fork's transcript the link to the original is looked for. */
31
+ const HEAD_BYTES = 256 * 1024;
32
+ export function forkOrigin(transcriptPath, env, commandLine) {
33
+ const folder = transcriptPath !== null ? path.dirname(transcriptPath) : null;
34
+ const own = transcriptPath !== null ? path.basename(transcriptPath, '.jsonl') : null;
35
+ const transcriptOf = (id) => {
36
+ if (folder === null)
37
+ return null;
38
+ const file = path.join(folder, `${id}.jsonl`);
39
+ return fs.existsSync(file) ? file : null;
40
+ };
41
+ const found = (sessionId, via, model) => SAFE_ID.test(sessionId) && sessionId !== own ? { sessionId, transcript: transcriptOf(sessionId), via, ...(model !== undefined ? { model } : {}) } : null;
42
+ const branched = transcriptPath !== null ? forkedFrom(transcriptPath) : null;
43
+ if (branched !== null)
44
+ return found(branched, 'fork-transcript');
45
+ const job = backgroundJob(env);
46
+ if (job !== null)
47
+ return found(job.parent, 'background-job', job.model ?? undefined);
48
+ const cmd = commandLine();
49
+ if (cmd === null || !cmd.args.includes('--fork-session'))
50
+ return null;
51
+ const resumed = [...optionCandidates(cmd, '--resume'), ...optionCandidates(cmd, '-r')];
52
+ // `--resume` also takes a name or a search term, and alone opens a picker: only a session id names the original.
53
+ if (resumed.length === 1 && SESSION_ID.test(resumed[0]))
54
+ return found(resumed[0], 'resume-argument');
55
+ if (resumed.length === 0 && (cmd.args.includes('--continue') || cmd.args.includes('-c'))) {
56
+ const latest = latestTranscript(folder, own);
57
+ if (latest !== null)
58
+ return found(latest, 'continue');
59
+ }
60
+ return null;
61
+ }
62
+ /** The session id the first entry of a transcript that names one was forked from. */
63
+ function forkedFrom(file) {
64
+ let head;
65
+ try {
66
+ const fd = fs.openSync(file, 'r');
67
+ try {
68
+ const buffer = Buffer.alloc(HEAD_BYTES);
69
+ head = buffer.toString('utf8', 0, fs.readSync(fd, buffer, 0, HEAD_BYTES, 0));
70
+ }
71
+ finally {
72
+ fs.closeSync(fd);
73
+ }
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ for (const line of head.split('\n')) {
79
+ if (!line.includes('"forkedFrom"'))
80
+ continue;
81
+ try {
82
+ const id = JSON.parse(line).forkedFrom?.sessionId;
83
+ if (typeof id === 'string')
84
+ return id;
85
+ }
86
+ catch {
87
+ // A line the read cut, or not a record.
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+ /** The original of a background job's session, and the model the job was started with. */
93
+ function backgroundJob(env) {
94
+ const dir = env.CLAUDE_JOB_DIR;
95
+ if (!dir)
96
+ return null;
97
+ try {
98
+ const state = JSON.parse(fs.readFileSync(path.join(dir, 'state.json'), 'utf8'));
99
+ if (typeof state.forkParentSessionId !== 'string')
100
+ return null;
101
+ const flags = Array.isArray(state.respawnFlags) ? state.respawnFlags : [];
102
+ const at = flags.lastIndexOf('--model');
103
+ const model = at >= 0 && typeof flags[at + 1] === 'string' ? flags[at + 1] : null;
104
+ return { parent: state.forkParentSessionId, model };
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ /** The session id of the most recently written transcript in a folder, other than `own`. */
111
+ function latestTranscript(folder, own) {
112
+ if (folder === null)
113
+ return null;
114
+ let best = null;
115
+ try {
116
+ for (const name of fs.readdirSync(folder)) {
117
+ if (!name.endsWith('.jsonl'))
118
+ continue;
119
+ const id = name.slice(0, -'.jsonl'.length);
120
+ if (id === own)
121
+ continue;
122
+ const at = fs.statSync(path.join(folder, name)).mtimeMs;
123
+ if (best === null || at > best.at)
124
+ best = { id, at };
125
+ }
126
+ }
127
+ catch {
128
+ return null;
129
+ }
130
+ return best?.id ?? null;
131
+ }
132
+ //# sourceMappingURL=fork.js.map