@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/alert.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { appendFile, mkdir, readFile, rename, unlink } from "node:fs/promises";
2
+ import { isyHome, pendingAlertPath } from "./paths.js";
3
+
4
+ /**
5
+ * One line to the developer that had nowhere to go at the moment it happened.
6
+ *
7
+ * Three things produce such a line: Kimi and Codex discard hook stdout on their
8
+ * lifecycle events, and a sweep runs detached from any CLI at all — nobody is
9
+ * watching its stdout. A parked line is shown at the next SessionStart, which
10
+ * is the next time this developer is looking at a CLI rather than mid-thought.
11
+ *
12
+ * Never throws: an alert is not worth breaking a session over.
13
+ */
14
+ export async function parkAlert(message: string): Promise<void> {
15
+ try {
16
+ await mkdir(isyHome(), { recursive: true, mode: 0o700 });
17
+ await appendFile(pendingAlertPath(), `${message}\n`);
18
+ } catch {
19
+ return;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * The parked lines, taken rather than read: the file is renamed first, so a
25
+ * park landing between the read and the truncate is not lost — it creates a
26
+ * fresh file the next drain picks up. Two CLIs starting at once means one of
27
+ * them wins the rename and shows the backlog; neither shows it twice.
28
+ *
29
+ * A claim that cannot then be read is put back. Stranding it would lose every
30
+ * line in it silently, and a `.claimed-<pid>` nobody reads is not a backlog,
31
+ * it is litter.
32
+ */
33
+ export async function drainAlerts(): Promise<string> {
34
+ const claimed = `${pendingAlertPath()}.claimed-${process.pid}`;
35
+ try {
36
+ await rename(pendingAlertPath(), claimed);
37
+ } catch {
38
+ return "";
39
+ }
40
+
41
+ let parked: string;
42
+ try {
43
+ parked = await readFile(claimed, "utf8");
44
+ } catch {
45
+ try {
46
+ await rename(claimed, pendingAlertPath());
47
+ } catch {
48
+ // Nothing left to try; the alert is gone either way.
49
+ }
50
+ return "";
51
+ }
52
+
53
+ // Already read, so a failed unlink costs nothing but the file: the next drain
54
+ // from this pid renames over it.
55
+ try {
56
+ await unlink(claimed);
57
+ } catch {
58
+ // See above.
59
+ }
60
+
61
+ return parked.trim();
62
+ }
63
+
64
+ /** What to show now, with anything parked earlier ahead of it. */
65
+ export async function withParkedAlerts(message: string): Promise<string> {
66
+ const parked = await drainAlerts();
67
+ return [parked, message].filter((part) => part.length > 0).join("\n");
68
+ }
package/src/api.ts ADDED
@@ -0,0 +1,269 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promisify } from "node:util";
3
+ import { gzip } from "node:zlib";
4
+ import type { GitMetadata } from "./git.js";
5
+ import { errorMessage } from "./log.js";
6
+ import { parsePlan } from "./plan.js";
7
+ import type { PlanStatus } from "./plan.js";
8
+ import type { CommitMark } from "./state.js";
9
+
10
+ const gzipAsync = promisify(gzip);
11
+
12
+ export const UPLOAD_TIMEOUT_MS = 10_000;
13
+ /**
14
+ * The slowest uplink an upload is sized for. One fixed timeout cannot fit both
15
+ * ends: 10 s is plenty for a short session and hopeless for a long one, whose
16
+ * body is megabytes. On an ordinary home uplink such a session was aborted on
17
+ * every attempt and given up on without ever reaching the server.
18
+ */
19
+ export const MIN_UPLOAD_BYTES_PER_SECOND = 64 * 1024;
20
+ export const MAX_BODY_BYTES = 50 * 1024 * 1024;
21
+
22
+ /**
23
+ * How long one upload may take: the base for the round trip plus what the body
24
+ * needs at the slowest expected uplink. A run someone waits on passes its
25
+ * deadline — a CLI holding its exit for a SessionEnd hook must not be kept for
26
+ * minutes by one transcript — and a body that does not fit is queued, to go out
27
+ * with its whole allowance from a run nobody waits on (a sweep, a push).
28
+ */
29
+ export function uploadTimeoutMs(bodyBytes: number, deadline?: number, now = Date.now()): number {
30
+ const needed = UPLOAD_TIMEOUT_MS + Math.ceil((bodyBytes / MIN_UPLOAD_BYTES_PER_SECOND) * 1000);
31
+ if (deadline === undefined) return needed;
32
+ return Math.max(UPLOAD_TIMEOUT_MS, Math.min(needed, deadline - now));
33
+ }
34
+ export const DEFAULT_API_BASE_URL = "https://iseeyaai.com";
35
+
36
+ export interface UploadPayload {
37
+ sessionId: string;
38
+ /** Which CLI recorded this. The server cannot tell Codex from Claude Code. */
39
+ agent?: string;
40
+ contentHash: string;
41
+ startedAt: string;
42
+ endedAt: string;
43
+ claudeVersion: string;
44
+ isyVersion: string;
45
+ git: GitMetadata;
46
+ transcript: string;
47
+ /**
48
+ * How many records the transcript held at each commit this session spans,
49
+ * oldest first. Turns a record index into the commit it belongs to, which is
50
+ * what lets a report say when a decision was made rather than only where.
51
+ */
52
+ commits?: CommitMark[];
53
+ }
54
+
55
+ export type UploadOutcome =
56
+ | {
57
+ status: "ok";
58
+ sessionId?: string;
59
+ deduplicated?: boolean;
60
+ clientVersion?: string;
61
+ /** Where the account stands with its plan, as of this upload. */
62
+ plan?: PlanStatus;
63
+ }
64
+ | { status: "retry"; error: string }
65
+ | { status: "permanent"; error: string }
66
+ // Too many uploads this hour. Not a failure: the session is kept as it is,
67
+ // and the run stops rather than spending the retries of every session behind
68
+ // it on an answer that will not change.
69
+ | { status: "throttled" };
70
+
71
+ export interface ApiOptions {
72
+ baseUrl: string;
73
+ token: string;
74
+ timeoutMs?: number;
75
+ /** Epoch ms an upload has to finish by. Unset, it gets the whole time its size needs. */
76
+ deadline?: number;
77
+ }
78
+
79
+ export async function buildTranscriptFields(
80
+ lines: readonly string[],
81
+ ): Promise<{ contentHash: string; transcript: string }> {
82
+ const jsonl = lines.length > 0 ? `${lines.join("\n")}\n` : "";
83
+ const contentHash = `sha256:${createHash("sha256").update(jsonl).digest("hex")}`;
84
+ const transcript = (await gzipAsync(Buffer.from(jsonl, "utf8"))).toString("base64");
85
+ return { contentHash, transcript };
86
+ }
87
+
88
+ function accepted(body: string): UploadOutcome {
89
+ let parsed: unknown;
90
+ try {
91
+ parsed = JSON.parse(body);
92
+ } catch {
93
+ return { status: "ok" };
94
+ }
95
+
96
+ if (typeof parsed !== "object" || parsed === null) return { status: "ok" };
97
+ const record = parsed as {
98
+ id?: unknown;
99
+ deduplicated?: unknown;
100
+ clientVersion?: unknown;
101
+ plan?: unknown;
102
+ };
103
+
104
+ const plan = parsePlan(record.plan);
105
+ return {
106
+ status: "ok",
107
+ sessionId: typeof record.id === "string" ? record.id : undefined,
108
+ deduplicated: record.deduplicated === true,
109
+ // The upload is the one call every hook makes: the version the server
110
+ // expects rides back on it rather than costing a request of its own, and so
111
+ // does what is left of the plan.
112
+ ...(typeof record.clientVersion === "string" ? { clientVersion: record.clientVersion } : {}),
113
+ ...(plan ? { plan } : {}),
114
+ };
115
+ }
116
+
117
+ function classify(status: number, body: string): UploadOutcome {
118
+ if (status >= 200 && status < 300) return accepted(body);
119
+ if (status === 401 || status === 403) {
120
+ return { status: "permanent", error: `authentication rejected (${status}), run: isy init` };
121
+ }
122
+ if (status === 413) return { status: "permanent", error: "transcript rejected as too large (413)" };
123
+ // A backlog is drained over hours rather than given up on: a sweep can find
124
+ // more sessions than an hour's allowance, and they are not at fault for it.
125
+ if (status === 429) return { status: "throttled" };
126
+ if (status === 400 || status === 422) {
127
+ return { status: "permanent", error: `server rejected the payload (${status}) ${body}`.trim() };
128
+ }
129
+ return { status: "retry", error: `server returned ${status} ${body}`.trim() };
130
+ }
131
+
132
+ export async function uploadSession(
133
+ payload: UploadPayload,
134
+ options: ApiOptions,
135
+ ): Promise<UploadOutcome> {
136
+ const body = await gzipAsync(Buffer.from(JSON.stringify(payload), "utf8"));
137
+
138
+ if (body.byteLength > MAX_BODY_BYTES) {
139
+ return {
140
+ status: "permanent",
141
+ error: `compressed body is ${body.byteLength} bytes, above the ${MAX_BODY_BYTES} byte limit`,
142
+ };
143
+ }
144
+
145
+ let response: Response;
146
+ try {
147
+ response = await fetch(new URL("/api/v1/sessions", options.baseUrl), {
148
+ method: "POST",
149
+ headers: {
150
+ "Content-Type": "application/json",
151
+ "Content-Encoding": "gzip",
152
+ Authorization: `Bearer ${options.token}`,
153
+ },
154
+ body,
155
+ signal: AbortSignal.timeout(
156
+ options.timeoutMs ?? uploadTimeoutMs(body.byteLength, options.deadline),
157
+ ),
158
+ });
159
+ } catch (error) {
160
+ const reason = error instanceof Error ? error.message : String(error);
161
+ return { status: "retry", error: `upload failed: ${reason}` };
162
+ }
163
+
164
+ const text = await response.text().catch(() => "");
165
+ return classify(response.status, text.slice(0, 200));
166
+ }
167
+
168
+ export async function verifyToken(
169
+ options: ApiOptions,
170
+ ): Promise<{ ok: true; githubLogin?: string } | { ok: false; error: string }> {
171
+ let response: Response;
172
+ try {
173
+ response = await fetch(new URL("/api/v1/me", options.baseUrl), {
174
+ headers: { Authorization: `Bearer ${options.token}` },
175
+ signal: AbortSignal.timeout(options.timeoutMs ?? UPLOAD_TIMEOUT_MS),
176
+ });
177
+ } catch (error) {
178
+ const reason = error instanceof Error ? error.message : String(error);
179
+ return { ok: false, error: `could not reach ${options.baseUrl}: ${reason}` };
180
+ }
181
+
182
+ if (!response.ok) return { ok: false, error: `token rejected (${response.status})` };
183
+
184
+ const parsed: unknown = await response.json().catch(() => undefined);
185
+ const githubLogin =
186
+ typeof parsed === "object" && parsed !== null && "githubLogin" in parsed
187
+ ? String((parsed as { githubLogin: unknown }).githubLogin)
188
+ : undefined;
189
+
190
+ return { ok: true, githubLogin };
191
+ }
192
+
193
+ /** One finding as the terminal shows it, task included. */
194
+ export interface Note {
195
+ label: string;
196
+ severity: string;
197
+ confidence: number;
198
+ file: string | null;
199
+ line: number | null;
200
+ prompt: string;
201
+ }
202
+
203
+ export interface NotesResponse {
204
+ repo: string;
205
+ prNumber: number;
206
+ branch: string | null;
207
+ analysisId: string;
208
+ notes: Note[];
209
+ }
210
+
211
+ /**
212
+ * A call the user is waiting on. Errors are thrown rather than returned as an
213
+ * outcome union: unlike an upload there is nothing to queue and retry — someone
214
+ * is at the terminal and wants the reason now.
215
+ */
216
+ async function apiJson<T>(options: ApiOptions, path: string, body?: unknown): Promise<T> {
217
+ let response: Response;
218
+ try {
219
+ response = await fetch(new URL(path, options.baseUrl), {
220
+ method: body === undefined ? "GET" : "PUT",
221
+ headers: {
222
+ Authorization: `Bearer ${options.token}`,
223
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
224
+ },
225
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
226
+ signal: AbortSignal.timeout(options.timeoutMs ?? UPLOAD_TIMEOUT_MS),
227
+ });
228
+ } catch (error) {
229
+ throw new Error(`could not reach ${options.baseUrl}: ${errorMessage(error)}`);
230
+ }
231
+
232
+ const parsed: unknown = await response.json().catch(() => undefined);
233
+ if (!response.ok) {
234
+ const message =
235
+ typeof parsed === "object" && parsed !== null && "error" in parsed
236
+ ? String((parsed as { error: unknown }).error)
237
+ : `request failed (${response.status})`;
238
+ throw new Error(message);
239
+ }
240
+
241
+ return parsed as T;
242
+ }
243
+
244
+ /** The findings for one branch, already written as tasks for a coding agent. */
245
+ export async function fetchNotes(
246
+ options: ApiOptions & { repo: string; branch?: string; pr?: number },
247
+ ): Promise<NotesResponse> {
248
+ const query = new URLSearchParams({ repo: options.repo });
249
+ if (options.pr !== undefined) query.set("pr", String(options.pr));
250
+ else if (options.branch) query.set("branch", options.branch);
251
+
252
+ return apiJson<NotesResponse>(options, `/api/v1/notes?${query}`);
253
+ }
254
+
255
+ /**
256
+ * What this account chose to see, in the same words `.isy.yml` uses. Unknown
257
+ * keys never come back: the server answers with what it actually stored.
258
+ */
259
+ export type Settings = Record<string, unknown>;
260
+
261
+ export async function fetchSettings(options: ApiOptions): Promise<Settings> {
262
+ const { settings } = await apiJson<{ settings: Settings }>(options, "/api/v1/settings");
263
+ return settings ?? {};
264
+ }
265
+
266
+ export async function putSettings(options: ApiOptions, settings: Settings): Promise<Settings> {
267
+ const stored = await apiJson<{ settings: Settings }>(options, "/api/v1/settings", settings);
268
+ return stored.settings ?? {};
269
+ }
@@ -0,0 +1,308 @@
1
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import { codexAgent, kimiAgent } from "../agents/index.js";
4
+ import { isCodexTranscript } from "../agents/codex-records.js";
5
+ import { isKimiTranscript } from "../agents/kimi-records.js";
6
+ import { isKimiWireTranscript } from "../agents/kimi-wire.js";
7
+ import { readConfig } from "../config.js";
8
+ import { parseLines } from "../parser.js";
9
+ import { firstLine, packageVersion } from "../paths.js";
10
+ import { redactTranscriptFile } from "../redact.js";
11
+ import { countByCategory, runStage0 } from "../stage0.js";
12
+ import type { IneligibleReason, Stage0Result } from "../stage0.js";
13
+ import type { Candidate, SignalCategory } from "../types.js";
14
+
15
+ export const SUPPORTED_STAGES = new Set(["0", "stage0"]);
16
+
17
+ export interface AnalyzedSession {
18
+ file: string;
19
+ sessionId?: string;
20
+ records: number;
21
+ assistantRecords: number;
22
+ editToolUses: number;
23
+ thinkingBlocks: number;
24
+ eligible: boolean;
25
+ reason?: IneligibleReason;
26
+ knownGapReachable: boolean;
27
+ candidates: Candidate[];
28
+ }
29
+
30
+ export interface AnalyzeReport {
31
+ isyVersion: string;
32
+ stage: string;
33
+ sessions: AnalyzedSession[];
34
+ totals: {
35
+ files: number;
36
+ eligible: number;
37
+ silent: number;
38
+ candidates: number;
39
+ byCategory: Record<string, number>;
40
+ };
41
+ }
42
+
43
+ export async function expandInputs(inputs: readonly string[]): Promise<string[]> {
44
+ const files: string[] = [];
45
+
46
+ for (const input of inputs) {
47
+ let info;
48
+ try {
49
+ info = await stat(input);
50
+ } catch {
51
+ throw new Error(`cannot read ${input}`);
52
+ }
53
+
54
+ if (info.isDirectory()) {
55
+ for (const entry of await readdir(input, { withFileTypes: true, recursive: true })) {
56
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) {
57
+ files.push(join(entry.parentPath, entry.name));
58
+ }
59
+ }
60
+ continue;
61
+ }
62
+
63
+ files.push(input);
64
+ }
65
+
66
+ return [...new Set(files)].sort();
67
+ }
68
+
69
+ /**
70
+ * Which CLI wrote this file. Sniffing beats a flag: a directory handed to
71
+ * `isy analyze` can hold transcripts from more than one.
72
+ */
73
+ async function transcriptLines(
74
+ file: string,
75
+ extraPatterns: readonly string[] | undefined,
76
+ ): Promise<string[]> {
77
+ const head = await firstLine(file);
78
+
79
+ // Two Kimi layouts: the older `context.jsonl` and the newer event log.
80
+ if (isKimiTranscript(head) || isKimiWireTranscript(head)) {
81
+ return kimiAgent.redactedLines(file, { extraPatterns });
82
+ }
83
+ if (isCodexTranscript(head)) return codexAgent.redactedLines(file, { extraPatterns });
84
+
85
+ const { lines } = await redactTranscriptFile(file, { extraPatterns });
86
+ return lines;
87
+ }
88
+
89
+ export async function analyzeFiles(
90
+ files: readonly string[],
91
+ extraPatterns: readonly string[] | undefined,
92
+ ): Promise<AnalyzedSession[]> {
93
+ const sessions: AnalyzedSession[] = [];
94
+
95
+ for (const file of files) {
96
+ const lines = await transcriptLines(file, extraPatterns);
97
+ const session = parseLines(lines);
98
+ const result: Stage0Result = runStage0(session);
99
+
100
+ sessions.push({
101
+ file,
102
+ sessionId: result.sessionId,
103
+ records: session.records.length,
104
+ assistantRecords: session.meta.assistantRecords,
105
+ editToolUses: session.meta.editToolUses,
106
+ thinkingBlocks: result.thinkingBlocks,
107
+ eligible: result.eligible,
108
+ reason: result.reason,
109
+ knownGapReachable: result.knownGapReachable,
110
+ candidates: result.candidates,
111
+ });
112
+ }
113
+
114
+ return sessions;
115
+ }
116
+
117
+ export function buildReport(
118
+ isyVersion: string,
119
+ stage: string,
120
+ sessions: AnalyzedSession[],
121
+ ): AnalyzeReport {
122
+ const candidates = sessions.flatMap((session) => session.candidates);
123
+ const eligible = sessions.filter((session) => session.eligible);
124
+
125
+ return {
126
+ isyVersion,
127
+ stage,
128
+ sessions,
129
+ totals: {
130
+ files: sessions.length,
131
+ eligible: eligible.length,
132
+ silent: eligible.filter((session) => session.candidates.length === 0).length,
133
+ candidates: candidates.length,
134
+ byCategory: countByCategory(candidates),
135
+ },
136
+ };
137
+ }
138
+
139
+ export interface Snapshot {
140
+ session: string;
141
+ eligible: boolean;
142
+ reason?: IneligibleReason;
143
+ knownGapReachable: boolean;
144
+ candidates: {
145
+ category: SignalCategory;
146
+ filePath?: string;
147
+ recordIndex: number;
148
+ weight: number;
149
+ detail: string;
150
+ }[];
151
+ }
152
+
153
+ export type SnapshotStatus = "ok" | "changed" | "missing" | "written";
154
+
155
+ export function snapshotOf(session: AnalyzedSession): Snapshot {
156
+ return {
157
+ session: basename(session.file, ".jsonl"),
158
+ eligible: session.eligible,
159
+ ...(session.reason ? { reason: session.reason } : {}),
160
+ knownGapReachable: session.knownGapReachable,
161
+ candidates: session.candidates.map((candidate) => ({
162
+ category: candidate.category,
163
+ ...(candidate.filePath ? { filePath: candidate.filePath } : {}),
164
+ recordIndex: candidate.recordIndex,
165
+ weight: candidate.weight,
166
+ detail: candidate.detail,
167
+ })),
168
+ };
169
+ }
170
+
171
+ export async function compareExpected(
172
+ dir: string,
173
+ sessions: readonly AnalyzedSession[],
174
+ update: boolean,
175
+ ): Promise<{ name: string; status: SnapshotStatus }[]> {
176
+ if (update) await mkdir(dir, { recursive: true });
177
+
178
+ const results: { name: string; status: SnapshotStatus }[] = [];
179
+
180
+ for (const session of sessions) {
181
+ const snapshot = snapshotOf(session);
182
+ const path = join(dir, `${snapshot.session}.json`);
183
+ const rendered = `${JSON.stringify(snapshot, null, 2)}\n`;
184
+
185
+ if (update) {
186
+ await writeFile(path, rendered);
187
+ results.push({ name: snapshot.session, status: "written" });
188
+ continue;
189
+ }
190
+
191
+ let stored: string;
192
+ try {
193
+ stored = await readFile(path, "utf8");
194
+ } catch {
195
+ results.push({ name: snapshot.session, status: "missing" });
196
+ continue;
197
+ }
198
+
199
+ results.push({ name: snapshot.session, status: stored === rendered ? "ok" : "changed" });
200
+ }
201
+
202
+ return results;
203
+ }
204
+
205
+ /**
206
+ * `elapsedMs` is passed in rather than measured here so the report stays a pure
207
+ * function of the sessions — it is omitted from the last line when absent.
208
+ */
209
+ export function formatReport(report: AnalyzeReport, elapsedMs?: number): string {
210
+ const lines: string[] = [];
211
+
212
+ for (const session of report.sessions) {
213
+ lines.push(`${session.file}`);
214
+ lines.push(
215
+ ` session ${session.sessionId ?? "unknown"} · ${session.records} records · ` +
216
+ `${session.assistantRecords} assistant · ${session.editToolUses} file edits`,
217
+ );
218
+
219
+ if (!session.eligible) {
220
+ lines.push(` gated out: ${session.reason}`);
221
+ lines.push("");
222
+ continue;
223
+ }
224
+
225
+ if (session.candidates.length === 0) {
226
+ lines.push(" no candidates");
227
+ lines.push("");
228
+ continue;
229
+ }
230
+
231
+ for (const candidate of session.candidates) {
232
+ const where = candidate.filePath ? ` · ${candidate.filePath}` : "";
233
+ lines.push(
234
+ ` [${candidate.weight.toFixed(2)}] ${candidate.category}${where}\n` +
235
+ ` ${candidate.detail}`,
236
+ );
237
+ }
238
+ if (!session.knownGapReachable) {
239
+ lines.push(" note: no thinking blocks, known_gap is unreachable for this session");
240
+ }
241
+ lines.push("");
242
+ }
243
+
244
+ const totals = report.totals;
245
+ lines.push(
246
+ `${totals.files} file(s) · ${totals.eligible} eligible · ${totals.silent} silent · ` +
247
+ `${totals.candidates} candidate(s)`,
248
+ );
249
+ for (const [category, count] of Object.entries(totals.byCategory).sort()) {
250
+ lines.push(` ${String(count).padStart(4)} ${category}`);
251
+ }
252
+ lines.push("");
253
+ const took = elapsedMs === undefined ? "" : ` in ${(elapsedMs / 1000).toFixed(1)}s`;
254
+ lines.push(
255
+ `\u2714 ${totals.files} file(s) scanned${took} · 0 bytes sent · ` +
256
+ "stage 0 is deterministic, runs locally, no model calls",
257
+ );
258
+
259
+ return lines.join("\n");
260
+ }
261
+
262
+ export async function runAnalyze(
263
+ options: {
264
+ files: readonly string[];
265
+ stage?: string;
266
+ json: boolean;
267
+ expect?: string;
268
+ update?: boolean;
269
+ },
270
+ ): Promise<void> {
271
+ if (options.files.length === 0) {
272
+ throw new Error("no transcripts given. Usage: isy analyze <file.jsonl|directory> [--stage 0]");
273
+ }
274
+
275
+ const stage = options.stage ?? "0";
276
+ if (!SUPPORTED_STAGES.has(stage)) {
277
+ throw new Error(
278
+ `stage '${stage}' is not available offline. Stages 1 and 2 call the model provider and run server-side; use --stage 0`,
279
+ );
280
+ }
281
+
282
+ const files = await expandInputs(options.files);
283
+ if (files.length === 0) throw new Error("no .jsonl transcripts found");
284
+
285
+ const config = await readConfig();
286
+ const started = Date.now();
287
+ const sessions = await analyzeFiles(files, config.extraRedactPatterns);
288
+ const elapsedMs = Date.now() - started;
289
+ const report = buildReport(await packageVersion(), stage, sessions);
290
+
291
+ console.log(
292
+ options.json ? JSON.stringify(report, null, 2) : formatReport(report, elapsedMs),
293
+ );
294
+
295
+ if (!options.expect) return;
296
+
297
+ const results = await compareExpected(options.expect, sessions, options.update === true);
298
+ const note = options.json ? console.error : console.log;
299
+ for (const { name, status } of results) note(`${status.padEnd(8)} ${name}`);
300
+
301
+ const stale = results.filter((result) => result.status !== "ok" && result.status !== "written");
302
+ if (stale.length > 0) {
303
+ throw new Error(
304
+ `${stale.length} snapshot(s) do not match ${options.expect}: ` +
305
+ `${stale.map((result) => result.name).join(", ")}. Re-run with --update to accept`,
306
+ );
307
+ }
308
+ }