@nightloom/isy 1.0.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 (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -0
  3. package/dist/agents/claude.d.ts +6 -0
  4. package/dist/agents/claude.js +66 -0
  5. package/dist/agents/claude.js.map +1 -0
  6. package/dist/agents/codex-records.d.ts +34 -0
  7. package/dist/agents/codex-records.js +492 -0
  8. package/dist/agents/codex-records.js.map +1 -0
  9. package/dist/agents/codex.d.ts +5 -0
  10. package/dist/agents/codex.js +205 -0
  11. package/dist/agents/codex.js.map +1 -0
  12. package/dist/agents/index.d.ts +25 -0
  13. package/dist/agents/index.js +50 -0
  14. package/dist/agents/index.js.map +1 -0
  15. package/dist/agents/kimi-records.d.ts +24 -0
  16. package/dist/agents/kimi-records.js +252 -0
  17. package/dist/agents/kimi-records.js.map +1 -0
  18. package/dist/agents/kimi-wire.d.ts +8 -0
  19. package/dist/agents/kimi-wire.js +158 -0
  20. package/dist/agents/kimi-wire.js.map +1 -0
  21. package/dist/agents/kimi.d.ts +6 -0
  22. package/dist/agents/kimi.js +332 -0
  23. package/dist/agents/kimi.js.map +1 -0
  24. package/dist/agents/types.d.ts +83 -0
  25. package/dist/agents/types.js +2 -0
  26. package/dist/agents/types.js.map +1 -0
  27. package/dist/alert.d.ts +24 -0
  28. package/dist/alert.js +68 -0
  29. package/dist/alert.js.map +1 -0
  30. package/dist/api.d.ts +103 -0
  31. package/dist/api.js +171 -0
  32. package/dist/api.js.map +1 -0
  33. package/dist/commands/analyze.d.ts +61 -0
  34. package/dist/commands/analyze.js +198 -0
  35. package/dist/commands/analyze.js.map +1 -0
  36. package/dist/commands/check.d.ts +55 -0
  37. package/dist/commands/check.js +180 -0
  38. package/dist/commands/check.js.map +1 -0
  39. package/dist/commands/commit.d.ts +26 -0
  40. package/dist/commands/commit.js +130 -0
  41. package/dist/commands/commit.js.map +1 -0
  42. package/dist/commands/health.d.ts +47 -0
  43. package/dist/commands/health.js +366 -0
  44. package/dist/commands/health.js.map +1 -0
  45. package/dist/commands/init.d.ts +3 -0
  46. package/dist/commands/init.js +173 -0
  47. package/dist/commands/init.js.map +1 -0
  48. package/dist/commands/logout.d.ts +1 -0
  49. package/dist/commands/logout.js +30 -0
  50. package/dist/commands/logout.js.map +1 -0
  51. package/dist/commands/notes.d.ts +11 -0
  52. package/dist/commands/notes.js +49 -0
  53. package/dist/commands/notes.js.map +1 -0
  54. package/dist/commands/scan.d.ts +47 -0
  55. package/dist/commands/scan.js +199 -0
  56. package/dist/commands/scan.js.map +1 -0
  57. package/dist/commands/settings.d.ts +15 -0
  58. package/dist/commands/settings.js +94 -0
  59. package/dist/commands/settings.js.map +1 -0
  60. package/dist/commands/status.d.ts +61 -0
  61. package/dist/commands/status.js +151 -0
  62. package/dist/commands/status.js.map +1 -0
  63. package/dist/commands/upload.d.ts +42 -0
  64. package/dist/commands/upload.js +429 -0
  65. package/dist/commands/upload.js.map +1 -0
  66. package/dist/config.d.ts +4 -0
  67. package/dist/config.js +32 -0
  68. package/dist/config.js.map +1 -0
  69. package/dist/detectors.d.ts +43 -0
  70. package/dist/detectors.js +1026 -0
  71. package/dist/detectors.js.map +1 -0
  72. package/dist/git.d.ts +22 -0
  73. package/dist/git.js +68 -0
  74. package/dist/git.js.map +1 -0
  75. package/dist/githook.d.ts +71 -0
  76. package/dist/githook.js +238 -0
  77. package/dist/githook.js.map +1 -0
  78. package/dist/hook.d.ts +39 -0
  79. package/dist/hook.js +173 -0
  80. package/dist/hook.js.map +1 -0
  81. package/dist/index.d.ts +2 -0
  82. package/dist/index.js +205 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/log.d.ts +19 -0
  85. package/dist/log.js +97 -0
  86. package/dist/log.js.map +1 -0
  87. package/dist/mask-paths.d.ts +75 -0
  88. package/dist/mask-paths.js +364 -0
  89. package/dist/mask-paths.js.map +1 -0
  90. package/dist/pairing.d.ts +60 -0
  91. package/dist/pairing.js +137 -0
  92. package/dist/pairing.js.map +1 -0
  93. package/dist/parser.d.ts +48 -0
  94. package/dist/parser.js +516 -0
  95. package/dist/parser.js.map +1 -0
  96. package/dist/paths.d.ts +41 -0
  97. package/dist/paths.js +181 -0
  98. package/dist/paths.js.map +1 -0
  99. package/dist/plan.d.ts +25 -0
  100. package/dist/plan.js +39 -0
  101. package/dist/plan.js.map +1 -0
  102. package/dist/queue.d.ts +26 -0
  103. package/dist/queue.js +120 -0
  104. package/dist/queue.js.map +1 -0
  105. package/dist/redact.d.ts +29 -0
  106. package/dist/redact.js +254 -0
  107. package/dist/redact.js.map +1 -0
  108. package/dist/spawn.d.ts +13 -0
  109. package/dist/spawn.js +32 -0
  110. package/dist/spawn.js.map +1 -0
  111. package/dist/stage0.d.ts +20 -0
  112. package/dist/stage0.js +90 -0
  113. package/dist/stage0.js.map +1 -0
  114. package/dist/state.d.ts +84 -0
  115. package/dist/state.js +150 -0
  116. package/dist/state.js.map +1 -0
  117. package/dist/test/analyze.test.d.ts +1 -0
  118. package/dist/test/analyze.test.js +408 -0
  119. package/dist/test/analyze.test.js.map +1 -0
  120. package/dist/test/check.test.d.ts +1 -0
  121. package/dist/test/check.test.js +193 -0
  122. package/dist/test/check.test.js.map +1 -0
  123. package/dist/test/cli.test.d.ts +1 -0
  124. package/dist/test/cli.test.js +132 -0
  125. package/dist/test/cli.test.js.map +1 -0
  126. package/dist/test/codex.test.d.ts +1 -0
  127. package/dist/test/codex.test.js +585 -0
  128. package/dist/test/codex.test.js.map +1 -0
  129. package/dist/test/commit.test.d.ts +1 -0
  130. package/dist/test/commit.test.js +430 -0
  131. package/dist/test/commit.test.js.map +1 -0
  132. package/dist/test/git.test.d.ts +1 -0
  133. package/dist/test/git.test.js +75 -0
  134. package/dist/test/git.test.js.map +1 -0
  135. package/dist/test/health.test.d.ts +1 -0
  136. package/dist/test/health.test.js +156 -0
  137. package/dist/test/health.test.js.map +1 -0
  138. package/dist/test/hook.test.d.ts +1 -0
  139. package/dist/test/hook.test.js +144 -0
  140. package/dist/test/hook.test.js.map +1 -0
  141. package/dist/test/kimi.test.d.ts +1 -0
  142. package/dist/test/kimi.test.js +349 -0
  143. package/dist/test/kimi.test.js.map +1 -0
  144. package/dist/test/mask-paths.test.d.ts +1 -0
  145. package/dist/test/mask-paths.test.js +230 -0
  146. package/dist/test/mask-paths.test.js.map +1 -0
  147. package/dist/test/notes.test.d.ts +1 -0
  148. package/dist/test/notes.test.js +41 -0
  149. package/dist/test/notes.test.js.map +1 -0
  150. package/dist/test/pairing.test.d.ts +1 -0
  151. package/dist/test/pairing.test.js +138 -0
  152. package/dist/test/pairing.test.js.map +1 -0
  153. package/dist/test/parser.test.d.ts +1 -0
  154. package/dist/test/parser.test.js +312 -0
  155. package/dist/test/parser.test.js.map +1 -0
  156. package/dist/test/plan.test.d.ts +1 -0
  157. package/dist/test/plan.test.js +34 -0
  158. package/dist/test/plan.test.js.map +1 -0
  159. package/dist/test/redact.test.d.ts +1 -0
  160. package/dist/test/redact.test.js +303 -0
  161. package/dist/test/redact.test.js.map +1 -0
  162. package/dist/test/settings.test.d.ts +1 -0
  163. package/dist/test/settings.test.js +32 -0
  164. package/dist/test/settings.test.js.map +1 -0
  165. package/dist/test/stage0.test.d.ts +1 -0
  166. package/dist/test/stage0.test.js +607 -0
  167. package/dist/test/stage0.test.js.map +1 -0
  168. package/dist/test/sweep.test.d.ts +1 -0
  169. package/dist/test/sweep.test.js +298 -0
  170. package/dist/test/sweep.test.js.map +1 -0
  171. package/dist/test/update.test.d.ts +1 -0
  172. package/dist/test/update.test.js +26 -0
  173. package/dist/test/update.test.js.map +1 -0
  174. package/dist/test/upload.test.d.ts +1 -0
  175. package/dist/test/upload.test.js +331 -0
  176. package/dist/test/upload.test.js.map +1 -0
  177. package/dist/types.d.ts +142 -0
  178. package/dist/types.js +2 -0
  179. package/dist/types.js.map +1 -0
  180. package/dist/update.d.ts +17 -0
  181. package/dist/update.js +46 -0
  182. package/dist/update.js.map +1 -0
  183. package/package.json +60 -0
  184. package/src/agents/claude.ts +89 -0
  185. package/src/agents/codex-records.ts +533 -0
  186. package/src/agents/codex.ts +238 -0
  187. package/src/agents/index.ts +58 -0
  188. package/src/agents/kimi-records.ts +274 -0
  189. package/src/agents/kimi-wire.ts +179 -0
  190. package/src/agents/kimi.ts +390 -0
  191. package/src/agents/types.ts +92 -0
  192. package/src/alert.ts +68 -0
  193. package/src/api.ts +269 -0
  194. package/src/commands/analyze.ts +308 -0
  195. package/src/commands/check.ts +239 -0
  196. package/src/commands/commit.ts +179 -0
  197. package/src/commands/health.ts +444 -0
  198. package/src/commands/init.ts +186 -0
  199. package/src/commands/logout.ts +33 -0
  200. package/src/commands/notes.ts +57 -0
  201. package/src/commands/scan.ts +278 -0
  202. package/src/commands/settings.ts +107 -0
  203. package/src/commands/status.ts +236 -0
  204. package/src/commands/upload.ts +524 -0
  205. package/src/config.ts +33 -0
  206. package/src/detectors.ts +1138 -0
  207. package/src/git.ts +86 -0
  208. package/src/githook.ts +269 -0
  209. package/src/hook.ts +237 -0
  210. package/src/index.ts +229 -0
  211. package/src/log.ts +113 -0
  212. package/src/mask-paths.ts +434 -0
  213. package/src/pairing.ts +190 -0
  214. package/src/parser.ts +581 -0
  215. package/src/paths.ts +191 -0
  216. package/src/plan.ts +56 -0
  217. package/src/queue.ts +145 -0
  218. package/src/redact.ts +335 -0
  219. package/src/spawn.ts +33 -0
  220. package/src/stage0.ts +121 -0
  221. package/src/state.ts +208 -0
  222. package/src/types.ts +165 -0
  223. package/src/update.ts +46 -0
package/src/parser.ts ADDED
@@ -0,0 +1,581 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import type {
4
+ ContentBlock,
5
+ FileEdit,
6
+ ParsedSession,
7
+ SkipStats,
8
+ ToolResult,
9
+ ToolUse,
10
+ TranscriptRecord,
11
+ } from "./types.js";
12
+
13
+ export const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
14
+ export const LOOKUP_TOOLS = new Set(["Read", "Grep", "Glob"]);
15
+
16
+ const KNOWN_RECORD_TYPES = new Set([
17
+ "user",
18
+ "assistant",
19
+ "attachment",
20
+ "system",
21
+ "ai-title",
22
+ "agent-name",
23
+ "mode",
24
+ "permission-mode",
25
+ "queue-operation",
26
+ "last-prompt",
27
+ "bridge-session",
28
+ "file-history-snapshot",
29
+ "file-history-delta",
30
+ ]);
31
+
32
+ interface ParseState {
33
+ records: TranscriptRecord[];
34
+ blocks: ContentBlock[];
35
+ toolUses: ToolUse[];
36
+ toolUseById: Map<string, ToolUse>;
37
+ fileEdits: Map<string, FileEdit[]>;
38
+ filesRead: Set<string>;
39
+ skipped: SkipStats;
40
+ thinkingBlocks: number;
41
+ editToolUses: number;
42
+ shellWrote: boolean;
43
+ sawUnknownTool: boolean;
44
+ }
45
+
46
+ function isObject(value: unknown): value is Record<string, unknown> {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+
50
+ function asString(value: unknown): string | undefined {
51
+ return typeof value === "string" && value.length > 0 ? value : undefined;
52
+ }
53
+
54
+ function createState(): ParseState {
55
+ return {
56
+ records: [],
57
+ blocks: [],
58
+ toolUses: [],
59
+ toolUseById: new Map(),
60
+ fileEdits: new Map(),
61
+ filesRead: new Set(),
62
+ skipped: { lines: 0, blank: 0, malformedJson: 0, notAnObject: 0, unknownTypes: {} },
63
+ thinkingBlocks: 0,
64
+ editToolUses: 0,
65
+ shellWrote: false,
66
+ sawUnknownTool: false,
67
+ };
68
+ }
69
+
70
+ function blockText(block: Record<string, unknown>): string {
71
+ const content = block.content;
72
+ if (typeof content === "string") return content;
73
+ if (!Array.isArray(content)) return "";
74
+ const parts: string[] = [];
75
+ for (const part of content) {
76
+ if (typeof part === "string") parts.push(part);
77
+ else if (isObject(part) && typeof part.text === "string") parts.push(part.text);
78
+ }
79
+ return parts.join("\n");
80
+ }
81
+
82
+ function extractText(block: Record<string, unknown>): string | undefined {
83
+ if (block.type === "text") return asString(block.text);
84
+ if (block.type === "thinking") return asString(block.thinking);
85
+ if (block.type === "tool_result") return blockText(block);
86
+ return undefined;
87
+ }
88
+
89
+ function buildToolResult(
90
+ record: TranscriptRecord,
91
+ block: Record<string, unknown>,
92
+ recordIndex: number,
93
+ ): ToolResult {
94
+ const detail = isObject(record.toolUseResult) ? record.toolUseResult : undefined;
95
+ const fallback = typeof record.toolUseResult === "string" ? record.toolUseResult : "";
96
+ const file = detail && isObject(detail.file) ? detail.file : undefined;
97
+ const whole = file && file.startLine === 1 && file.numLines === file.totalLines;
98
+
99
+ return {
100
+ recordIndex,
101
+ uuid: record.uuid,
102
+ timestamp: record.timestamp,
103
+ isError: block.is_error === true,
104
+ text: blockText(block) || fallback,
105
+ stdout: detail && typeof detail.stdout === "string" ? detail.stdout : undefined,
106
+ stderr: detail && typeof detail.stderr === "string" ? detail.stderr : undefined,
107
+ fileContent: whole && typeof file.content === "string" ? file.content : undefined,
108
+ interrupted: detail?.interrupted === true,
109
+ };
110
+ }
111
+
112
+ function pushFileEdits(state: ParseState, use: ToolUse): void {
113
+ const filePath = asString(use.input.file_path) ?? asString(use.input.notebook_path);
114
+ if (!filePath) return;
115
+
116
+ const base = {
117
+ toolUseId: use.id,
118
+ tool: use.name,
119
+ filePath,
120
+ recordIndex: use.recordIndex,
121
+ uuid: use.uuid,
122
+ timestamp: use.timestamp,
123
+ };
124
+
125
+ const entries: FileEdit[] = [];
126
+ if (Array.isArray(use.input.edits)) {
127
+ for (const edit of use.input.edits) {
128
+ if (!isObject(edit)) continue;
129
+ entries.push({
130
+ ...base,
131
+ oldString: asString(edit.old_string),
132
+ newString: asString(edit.new_string),
133
+ });
134
+ }
135
+ } else {
136
+ entries.push({
137
+ ...base,
138
+ oldString: asString(use.input.old_string),
139
+ newString: asString(use.input.new_string) ?? asString(use.input.new_source),
140
+ content: asString(use.input.content),
141
+ });
142
+ }
143
+
144
+ const existing = state.fileEdits.get(filePath);
145
+ if (existing) existing.push(...entries);
146
+ else state.fileEdits.set(filePath, entries);
147
+ }
148
+
149
+ function pushLookup(state: ParseState, use: ToolUse): void {
150
+ const target = asString(use.input.file_path) ?? asString(use.input.path);
151
+ if (target) state.filesRead.add(target);
152
+ }
153
+
154
+ /**
155
+ * A heredoc opener: `<<EOF`, `<<-EOF`, `<<'PY'`. The delimiter is what ends the
156
+ * body, and quoting it changes nothing about where the body stops.
157
+ */
158
+ const HEREDOC = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/;
159
+
160
+ /**
161
+ * The command with every heredoc body cut out.
162
+ *
163
+ * `python3 - <<'PY' … PY` carries a whole file inside one command: a document
164
+ * quoting `npm install`, a fixture holding `DROP DATABASE`, a test asserting on
165
+ * `rm -rf`. Everything that reads a command reads it segment by segment, and a
166
+ * body's lines are segments, so without this the detectors report a dozen
167
+ * commands the agent never ran. The opening line stays — that one really
168
+ * did run.
169
+ */
170
+ export function withoutHeredocs(command: string): string {
171
+ if (!command.includes("<<")) return command;
172
+
173
+ const kept: string[] = [];
174
+ let terminator: string | undefined;
175
+
176
+ for (const line of command.split("\n")) {
177
+ if (terminator !== undefined) {
178
+ if (line.trim() === terminator) terminator = undefined;
179
+ continue;
180
+ }
181
+ kept.push(line);
182
+ terminator = HEREDOC.exec(line)?.[2];
183
+ }
184
+
185
+ return kept.join("\n");
186
+ }
187
+
188
+ /**
189
+ * A command split into the pieces a shell would run on its own, with quoting
190
+ * honoured: `grep -E "DELETE FROM|DROP TABLE" file` is one reader, not a reader
191
+ * followed by a DROP. The corpus trips over exactly that — an alternation
192
+ * inside a search pattern is the commonest way a `|` shows up in a command that
193
+ * runs nothing at all.
194
+ *
195
+ * ponytail: quotes nest as a single state, and a backslash escape only counts
196
+ * inside double quotes, which is what a shell does anyway. Real parsing is a
197
+ * dependency, and this is here to stop three regexes from lying.
198
+ */
199
+ export function commandSegments(command: string): string[] {
200
+ const segments: string[] = [];
201
+ let current = "";
202
+ let quote: string | undefined;
203
+
204
+ // A command substitution runs its own command: `node x $(grep -rl "DROP TABLE" .)`
205
+ // greps, it does not drop. Lifted out first so it is judged on its own, and
206
+ // so the text it carries stops belonging to the command around it.
207
+ const substituted: string[] = [];
208
+ const flat = command.replace(/\$\(([^()]*)\)/g, (_match, body: string) => {
209
+ substituted.push(body);
210
+ return " ";
211
+ });
212
+
213
+ for (let i = 0; i < flat.length; i += 1) {
214
+ const char = flat[i]!;
215
+
216
+ if (quote !== undefined) {
217
+ current += char;
218
+ if (char === quote && (quote === "'" || flat[i - 1] !== "\\")) quote = undefined;
219
+ continue;
220
+ }
221
+ if (char === '"' || char === "'" || char === "`") {
222
+ quote = char;
223
+ current += char;
224
+ continue;
225
+ }
226
+ if (char === "\n" || char === ";") {
227
+ segments.push(current);
228
+ current = "";
229
+ continue;
230
+ }
231
+ if (char === "|" || char === "&") {
232
+ // `&&` and `||` split in the same place their single-character forms do.
233
+ if (flat[i + 1] === char) i += 1;
234
+ segments.push(current);
235
+ current = "";
236
+ continue;
237
+ }
238
+ current += char;
239
+ }
240
+
241
+ segments.push(current);
242
+ // The bodies hold no substitutions of their own — the pattern above stops at
243
+ // the first parenthesis — so this recursion is one level deep.
244
+ return [...segments, ...substituted.flatMap((body) => commandSegments(body))];
245
+ }
246
+
247
+ const SHELL_READERS =
248
+ /^\s*(?:sudo\s+)?(cat|head|tail|less|more|bat|nl|wc|sed|awk|rg|grep|egrep|fgrep|jq|yq|xxd|od|file|stat|diff|git\s+show|git\s+diff|git\s+log|git\s+blame)\b/;
249
+
250
+ /**
251
+ * Tools known not to write a file. Anything outside these and the edit tools is
252
+ * a name some CLI invented — Kimi's `StrReplaceFile` next to its plain `Grep`,
253
+ * the next Codex harness — and the parser cannot say whether it wrote one.
254
+ */
255
+ const OTHER_KNOWN_TOOLS = new Set([
256
+ // Claude Code
257
+ "Task", "Agent", "TodoWrite", "WebFetch", "WebSearch", "Skill", "AskUserQuestion",
258
+ "EnterPlanMode", "ExitPlanMode", "ToolSearch", "BashOutput", "KillShell", "KillBash",
259
+ "TaskOutput", "TaskStop", "Monitor", "LS", "NotebookRead", "SlashCommand",
260
+ "ListMcpResourcesTool", "ReadMcpResourceTool",
261
+ // Codex, kept under its own name by agents/codex-records.ts
262
+ "update_plan", "view_image", "web_search", "web__run", "image_gen__imagegen", "wait",
263
+ ]);
264
+
265
+ function isKnownTool(name: string): boolean {
266
+ return (
267
+ EDIT_TOOLS.has(name) ||
268
+ LOOKUP_TOOLS.has(name) ||
269
+ name === "Bash" ||
270
+ name.startsWith("mcp__") ||
271
+ OTHER_KNOWN_TOOLS.has(name)
272
+ );
273
+ }
274
+
275
+ /** A redirect into a file: `> a.ts`, `>> log`, `2> out`. Not `2>&1`, not `/dev/null`. */
276
+ const REDIRECT_WRITE = /(?:^|[^<>&\d])\d*>>?(?!&)\s*(?!\/dev\/|\/tmp\/)[^\s&|;<>]/;
277
+ const TEE_WRITE = /\btee\s+(?:-a\s+)?(?!\/dev\/|\/tmp\/)[^\s&|;-]/;
278
+ const FILE_MUTATORS =
279
+ /^\s*(?:sudo\s+)?(?:patch|truncate|mv|cp|git\s+(?:apply|mv|rm|restore|checkout\s+--))\b/;
280
+ const IN_PLACE_EDITORS = /^\s*(?:sudo\s+)?(?:g?sed|perl)\b/;
281
+ /** An interpreter fed a script on stdin: whatever the script writes, the command line cannot say. */
282
+ const INTERPRETER_HEREDOC =
283
+ /(?:^|[\s;&|(])(?:python[0-9.]*|node|deno|bun|tsx|ruby|perl|php|bash|sh|zsh)\b[^\n]*<</;
284
+
285
+ /**
286
+ * Whether a shell command could have changed a file in the repository.
287
+ *
288
+ * This answers only "did this session touch files at all", which is what the
289
+ * no-file-edits gate asks, and never "which file" — so it errs toward yes. A
290
+ * wrong yes costs one pass of stage 0 with no model call; a wrong no drops the
291
+ * whole session from its pull request, which is what happened to every agent
292
+ * that edits through the shell before this existed.
293
+ *
294
+ * ponytail: no paths. A heredoc into python writes where the script says, and
295
+ * the script is not read here. Parse the command properly and feed the
296
+ * detectors if a signal ever needs to name a file written this way.
297
+ * Plain `rm` is left out on purpose: it is mostly `rm -rf dist`, and `git rm`
298
+ * covers a tracked file.
299
+ */
300
+ export function shellWrites(command: string): boolean {
301
+ const ran = withoutHeredocs(command);
302
+ if (INTERPRETER_HEREDOC.test(ran)) return true;
303
+
304
+ for (const segment of commandSegments(ran)) {
305
+ // What sits inside quotes is an argument, not an operator: `grep "->" a`.
306
+ const bare = segment.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''");
307
+ if (REDIRECT_WRITE.test(bare) || TEE_WRITE.test(bare) || FILE_MUTATORS.test(bare)) return true;
308
+ if (IN_PLACE_EDITORS.test(bare) && (IN_PLACE.test(bare) || /\bperl\s+-\w*i/.test(bare))) return true;
309
+ }
310
+ return false;
311
+ }
312
+
313
+ /** `sed -i` rewrites the file; whatever else it is, it is not a look at it. */
314
+ const IN_PLACE = /(?:^|\s)(?:-i(?:\.\S+)?|--in-place)(?:\s|$)/;
315
+
316
+ /** Tools whose first non-flag argument is a program, not a path. */
317
+ const SCRIPTED = /^\s*(?:sudo\s+)?(?:sed|awk)\b/;
318
+
319
+ export function shellReadPaths(command: string): string[] {
320
+ const paths: string[] = [];
321
+
322
+ for (const segment of commandSegments(withoutHeredocs(command))) {
323
+ if (!SHELL_READERS.test(segment)) continue;
324
+ if (IN_PLACE.test(segment)) continue;
325
+
326
+ // `sed 's/^/UNPUSHED: /'` has slashes in it and is not a path: read as one
327
+ // it yields "/", which then matches every absolute path there is.
328
+ let script = SCRIPTED.test(segment);
329
+
330
+ for (const raw of segment.trim().split(/\s+/).slice(1)) {
331
+ if (/^\d*[<>]|^&/.test(raw)) break;
332
+
333
+ const token = raw.replace(/["'`]/g, "");
334
+ if (token.startsWith("-") || token.startsWith("$")) continue;
335
+ if (script) {
336
+ script = false;
337
+ continue;
338
+ }
339
+
340
+ const path = token.includes(":") ? token.slice(token.lastIndexOf(":") + 1) : token;
341
+ if (path.includes("*") || path.includes("?")) continue;
342
+ // "/" and "." name no file, and "/" matches every path there is.
343
+ if (/^[./]+$/.test(path)) continue;
344
+ if (!/\.[A-Za-z0-9]+$/.test(path) && !path.includes("/")) continue;
345
+
346
+ paths.push(path.replace(/^\.\//, ""));
347
+ }
348
+ }
349
+
350
+ return paths;
351
+ }
352
+
353
+ function pushToolUse(
354
+ state: ParseState,
355
+ record: TranscriptRecord,
356
+ block: Record<string, unknown>,
357
+ recordIndex: number,
358
+ ): void {
359
+ const id = asString(block.id);
360
+ const name = asString(block.name);
361
+ if (!id || !name) return;
362
+
363
+ const use: ToolUse = {
364
+ id,
365
+ name,
366
+ input: isObject(block.input) ? block.input : {},
367
+ recordIndex,
368
+ uuid: record.uuid,
369
+ timestamp: record.timestamp,
370
+ isSidechain: record.isSidechain === true,
371
+ };
372
+
373
+ state.toolUses.push(use);
374
+ state.toolUseById.set(id, use);
375
+
376
+ if (EDIT_TOOLS.has(name)) {
377
+ state.editToolUses += 1;
378
+ pushFileEdits(state, use);
379
+ }
380
+ if (LOOKUP_TOOLS.has(name)) pushLookup(state, use);
381
+ if (name === "Bash" && typeof use.input.command === "string") {
382
+ for (const path of shellReadPaths(use.input.command)) state.filesRead.add(path);
383
+ if (shellWrites(use.input.command)) state.shellWrote = true;
384
+ }
385
+
386
+ if (!isKnownTool(name)) state.sawUnknownTool = true;
387
+ }
388
+
389
+ function pushBlocks(state: ParseState, record: TranscriptRecord, recordIndex: number): void {
390
+ const content = record.message?.content;
391
+ const raw: unknown[] = typeof content === "string"
392
+ ? [{ type: "text", text: content }]
393
+ : Array.isArray(content)
394
+ ? content
395
+ : [];
396
+
397
+ for (const item of raw) {
398
+ if (!isObject(item)) continue;
399
+ const type = asString(item.type) ?? "unknown";
400
+
401
+ state.blocks.push({
402
+ type,
403
+ recordIndex,
404
+ uuid: record.uuid,
405
+ timestamp: record.timestamp,
406
+ isSidechain: record.isSidechain === true,
407
+ text: extractText(item),
408
+ raw: item,
409
+ });
410
+
411
+ if (type === "thinking") state.thinkingBlocks += 1;
412
+ if (type === "tool_use") pushToolUse(state, record, item, recordIndex);
413
+ if (type === "tool_result") {
414
+ const target = asString(item.tool_use_id);
415
+ const use = target ? state.toolUseById.get(target) : undefined;
416
+ if (use) use.result = buildToolResult(record, item, recordIndex);
417
+ }
418
+ }
419
+ }
420
+
421
+ function pushLine(state: ParseState, line: string): void {
422
+ state.skipped.lines += 1;
423
+
424
+ const trimmed = line.trim();
425
+ if (trimmed.length === 0) {
426
+ state.skipped.blank += 1;
427
+ return;
428
+ }
429
+
430
+ let parsed: unknown;
431
+ try {
432
+ parsed = JSON.parse(trimmed);
433
+ } catch {
434
+ state.skipped.malformedJson += 1;
435
+ return;
436
+ }
437
+
438
+ if (!isObject(parsed)) {
439
+ state.skipped.notAnObject += 1;
440
+ return;
441
+ }
442
+
443
+ const type = asString(parsed.type) ?? "unknown";
444
+ if (!KNOWN_RECORD_TYPES.has(type)) {
445
+ state.skipped.unknownTypes[type] = (state.skipped.unknownTypes[type] ?? 0) + 1;
446
+ }
447
+
448
+ const record = { ...parsed, type } as TranscriptRecord;
449
+ state.records.push(record);
450
+ pushBlocks(state, record, state.records.length - 1);
451
+ }
452
+
453
+ function buildByUuid(records: TranscriptRecord[]): Map<string, TranscriptRecord> {
454
+ const byUuid = new Map<string, TranscriptRecord>();
455
+ for (const record of records) {
456
+ if (typeof record.uuid === "string") byUuid.set(record.uuid, record);
457
+ }
458
+ return byUuid;
459
+ }
460
+
461
+ function buildMainPath(
462
+ records: TranscriptRecord[],
463
+ byUuid: Map<string, TranscriptRecord>,
464
+ ): Set<string> {
465
+ let tip: TranscriptRecord | undefined;
466
+ for (let i = records.length - 1; i >= 0; i -= 1) {
467
+ const record = records[i]!;
468
+ if (typeof record.uuid === "string" && record.isSidechain !== true) {
469
+ tip = record;
470
+ break;
471
+ }
472
+ }
473
+
474
+ const path = new Set<string>();
475
+ let current = tip;
476
+ while (current && typeof current.uuid === "string" && !path.has(current.uuid)) {
477
+ path.add(current.uuid);
478
+ current = typeof current.parentUuid === "string" ? byUuid.get(current.parentUuid) : undefined;
479
+ }
480
+ return path;
481
+ }
482
+
483
+ function finish(state: ParseState): ParsedSession {
484
+ let sessionId: string | undefined;
485
+ let cwd: string | undefined;
486
+ let gitBranch: string | undefined;
487
+ let claudeVersion: string | undefined;
488
+ let startedAt: string | undefined;
489
+ let endedAt: string | undefined;
490
+ let assistantRecords = 0;
491
+ let sidechainRecords = 0;
492
+
493
+ for (const record of state.records) {
494
+ sessionId ??= asString(record.sessionId);
495
+ cwd = asString(record.cwd) ?? cwd;
496
+ gitBranch = asString(record.gitBranch) ?? gitBranch;
497
+ claudeVersion = asString(record.version) ?? claudeVersion;
498
+ const timestamp = asString(record.timestamp);
499
+ if (timestamp) {
500
+ startedAt ??= timestamp;
501
+ endedAt = timestamp;
502
+ }
503
+ if (record.type === "assistant") assistantRecords += 1;
504
+ if (record.isSidechain === true) sidechainRecords += 1;
505
+ }
506
+
507
+ const byUuid = buildByUuid(state.records);
508
+
509
+ return {
510
+ sessionId,
511
+ records: state.records,
512
+ blocks: state.blocks,
513
+ toolUses: state.toolUses,
514
+ fileEdits: state.fileEdits,
515
+ filesRead: state.filesRead,
516
+ byUuid,
517
+ mainPath: buildMainPath(state.records, byUuid),
518
+ meta: {
519
+ cwd,
520
+ gitBranch,
521
+ claudeVersion,
522
+ startedAt,
523
+ endedAt,
524
+ assistantRecords,
525
+ thinkingBlocks: state.thinkingBlocks,
526
+ editToolUses: state.editToolUses,
527
+ // Not the same question as editToolUses > 0: a file written from the
528
+ // shell counts, and a tool this parser does not know is "cannot tell",
529
+ // which must not read as "edited nothing".
530
+ hasFileEdits: state.editToolUses > 0 || state.shellWrote || state.sawUnknownTool,
531
+ sidechainRecords,
532
+ },
533
+ skipped: state.skipped,
534
+ };
535
+ }
536
+
537
+ export function parseLines(lines: Iterable<string>): ParsedSession {
538
+ const state = createState();
539
+ for (const line of lines) pushLine(state, line);
540
+ return finish(state);
541
+ }
542
+
543
+ export async function parseTranscriptFile(filePath: string): Promise<ParsedSession> {
544
+ const state = createState();
545
+ const input = createReadStream(filePath, { encoding: "utf8" });
546
+ const reader = createInterface({ input, crlfDelay: Infinity });
547
+ for await (const line of reader) pushLine(state, line);
548
+ const session = finish(state);
549
+ session.filePath = filePath;
550
+ return session;
551
+ }
552
+
553
+ export function onMainPath(session: ParsedSession, uuid: string | undefined): boolean {
554
+ return typeof uuid === "string" && session.mainPath.has(uuid);
555
+ }
556
+
557
+ export function onAbandonedBranch(session: ParsedSession, uuid: string | undefined): boolean {
558
+ if (typeof uuid !== "string" || session.mainPath.size === 0) return false;
559
+ if (session.mainPath.has(uuid)) return false;
560
+
561
+ const visited = new Set<string>();
562
+ let current = session.byUuid.get(uuid);
563
+
564
+ while (current && typeof current.uuid === "string" && !visited.has(current.uuid)) {
565
+ visited.add(current.uuid);
566
+ const parent = current.parentUuid;
567
+ if (typeof parent !== "string") return false;
568
+ if (session.mainPath.has(parent)) return true;
569
+ current = session.byUuid.get(parent);
570
+ }
571
+
572
+ return false;
573
+ }
574
+
575
+ export function hasSkips(skipped: SkipStats): boolean {
576
+ return (
577
+ skipped.malformedJson > 0 ||
578
+ skipped.notAnObject > 0 ||
579
+ Object.keys(skipped.unknownTypes).length > 0
580
+ );
581
+ }