@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
@@ -0,0 +1,444 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { presentAgents } from "../agents/index.js";
3
+ import { readConfig } from "../config.js";
4
+ import { errorMessage, readJournal, unresolvedErrors } from "../log.js";
5
+ import type { JournalEntry } from "../log.js";
6
+ import { configPath, isyHome, logPath, packageVersion, queueDir, sessionStatePath } from "../paths.js";
7
+ import { listFailed } from "../queue.js";
8
+ import { collectCheck, formatCheck } from "./check.js";
9
+ import { collectScan, formatScan } from "./scan.js";
10
+ import type { CheckReport } from "./check.js";
11
+
12
+ /** Journal lines carried into the work order: the ones before a failure tell the story. */
13
+ const JOURNAL_CONTEXT = 30;
14
+
15
+ /**
16
+ * One thing that is wrong, described as evidence rather than as a diagnosis.
17
+ * ISY deliberately does not say what caused it: a fixed table of causes only
18
+ * ever covers failures someone already saw, and reads as authoritative when it
19
+ * is wrong. Naming the cause is the repairing agent's job.
20
+ */
21
+ export interface HealthProblem {
22
+ id: string;
23
+ /** What ISY observed, in the past tense. Never "you should", never a cause. */
24
+ summary: string;
25
+ /** The operation that was running. */
26
+ attempted: string;
27
+ /** The failure verbatim, never reworded — the exact text is the evidence. */
28
+ evidence: string;
29
+ /** What ISY could not determine, so the agent knows where to start. */
30
+ unknown: string;
31
+ files: string[];
32
+ }
33
+
34
+ export interface HealthReport {
35
+ ok: boolean;
36
+ version: string;
37
+ problems: HealthProblem[];
38
+ /** Checks that passed, so a repairing agent does not spend turns re-running them. */
39
+ verified: string[];
40
+ /** Recent journal lines, both levels: an error is rarely legible on its own. */
41
+ journal: JournalEntry[];
42
+ /** Undefined when the configuration check itself threw. */
43
+ check?: CheckReport;
44
+ }
45
+
46
+ async function configProblems(verified: string[]): Promise<HealthProblem[]> {
47
+ try {
48
+ const config = await readConfig();
49
+ if (config.token) verified.push(`the config at ${configPath()} parses and holds a token`);
50
+ return [];
51
+ } catch (error) {
52
+ return [
53
+ {
54
+ id: "config-unreadable",
55
+ summary: "the config file could not be read",
56
+ attempted: `read and parse ${configPath()}`,
57
+ evidence: errorMessage(error),
58
+ unknown: "what left the file in this state",
59
+ files: [configPath()],
60
+ },
61
+ ];
62
+ }
63
+ }
64
+
65
+ function checkProblems(check: CheckReport, verified: string[]): HealthProblem[] {
66
+ const problems: HealthProblem[] = [];
67
+
68
+ if (!check.configured) {
69
+ problems.push({
70
+ id: "not-configured",
71
+ summary: "no API token is stored, so nothing is ever uploaded",
72
+ attempted: "read the token from the config",
73
+ evidence: `no "token" field in ${configPath()}`,
74
+ unknown: "whether the user ever ran isy init on this machine",
75
+ files: [configPath()],
76
+ });
77
+ }
78
+
79
+ if (check.missingHooks.length > 0) {
80
+ problems.push({
81
+ id: "hooks-missing",
82
+ summary: `${check.missingHooks.join(", ")} not installed, so sessions are never collected`,
83
+ attempted: "list the hooks each installed CLI has registered for isy",
84
+ evidence: `installed: ${check.agents
85
+ .map((agent) => `${agent.label} missing ${agent.missingHooks.join(", ") || "nothing"}`)
86
+ .join("; ")}`,
87
+ unknown: "whether the hook was never written or was removed later",
88
+ files: [isyHome()],
89
+ });
90
+ } else if (check.agents.length > 0) {
91
+ verified.push(`hooks are installed for ${check.agents.map((agent) => agent.label).join(", ")}`);
92
+ }
93
+
94
+ if (check.gitHook === "missing") {
95
+ problems.push({
96
+ id: "git-hook-missing",
97
+ summary: "this repository is missing an isy git hook, so commits or pushes do not trigger an upload",
98
+ attempted: "look for the isy block in the repository's post-commit and pre-push hooks",
99
+ evidence: "the managed block between '# isy:begin' and '# isy:end' is absent",
100
+ unknown: "whether another tool rewrote the hook file",
101
+ files: [],
102
+ });
103
+ } else if (check.gitHook === "installed") {
104
+ verified.push("the repository's post-commit and pre-push hooks carry the isy block");
105
+ }
106
+
107
+ if (check.api !== undefined && check.api !== "ok") {
108
+ problems.push({
109
+ id: "api-unreachable",
110
+ summary: `the server did not accept the token at ${check.apiBaseUrl}`,
111
+ attempted: `GET ${check.apiBaseUrl}/api/v1/me with the stored token`,
112
+ evidence: check.api,
113
+ unknown: "whether the token, the URL, or the network is at fault",
114
+ files: [configPath()],
115
+ });
116
+ } else if (check.api === "ok") {
117
+ verified.push(`the server at ${check.apiBaseUrl} answered and accepted the token`);
118
+ }
119
+
120
+ return problems;
121
+ }
122
+
123
+ /**
124
+ * The transcript directory is read on every upload, and `sessionsIn` reports an
125
+ * unreadable directory the same way it reports an empty one. Health reads it
126
+ * directly so the difference survives. A directory that does not exist yet is
127
+ * normal: no session has run in this repository.
128
+ */
129
+ async function agentProblems(cwd: string, verified: string[]): Promise<HealthProblem[]> {
130
+ const problems: HealthProblem[] = [];
131
+
132
+ for (const agent of await presentAgents()) {
133
+ const dir = agent.transcriptDir(cwd);
134
+ try {
135
+ await readdir(dir);
136
+ verified.push(`${agent.label}'s transcript directory ${dir} is readable`);
137
+ } catch (error) {
138
+ const code = (error as NodeJS.ErrnoException).code;
139
+ if (code === "ENOENT") continue;
140
+ problems.push({
141
+ id: `transcripts-unreadable-${agent.id}`,
142
+ summary: `${agent.label}'s transcripts could not be listed, so its sessions are invisible`,
143
+ attempted: `list ${dir}`,
144
+ evidence: errorMessage(error),
145
+ unknown: "why the directory cannot be read",
146
+ files: [dir],
147
+ });
148
+ }
149
+ }
150
+
151
+ return problems;
152
+ }
153
+
154
+ async function stateProblems(verified: string[]): Promise<HealthProblem[]> {
155
+ const path = sessionStatePath();
156
+
157
+ let contents: string;
158
+ try {
159
+ contents = await readFile(path, "utf8");
160
+ } catch (error) {
161
+ // Nothing uploaded yet on this machine, which is not a fault.
162
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
163
+ return [
164
+ {
165
+ id: "state-unreadable",
166
+ summary: "the upload cache could not be read, so every session looks unsent",
167
+ attempted: `read ${path}`,
168
+ evidence: errorMessage(error),
169
+ unknown: "why the file cannot be read",
170
+ files: [path],
171
+ },
172
+ ];
173
+ }
174
+
175
+ try {
176
+ JSON.parse(contents);
177
+ verified.push(`the upload cache at ${path} parses`);
178
+ return [];
179
+ } catch (error) {
180
+ return [
181
+ {
182
+ id: "state-corrupt",
183
+ summary: "the upload cache is not valid JSON, so every session looks unsent",
184
+ attempted: `parse ${path}`,
185
+ evidence: errorMessage(error),
186
+ unknown: "what interrupted the write that left it this way",
187
+ files: [path],
188
+ },
189
+ ];
190
+ }
191
+ }
192
+
193
+ /** Uploads that used up all three attempts. Their stored `lastError` is the evidence. */
194
+ async function queueProblems(): Promise<HealthProblem[]> {
195
+ const failed = await listFailed();
196
+ if (failed.length === 0) return [];
197
+
198
+ return [
199
+ {
200
+ id: "uploads-abandoned",
201
+ summary: `${failed.length} session${failed.length === 1 ? "" : "s"} never reached the server`,
202
+ attempted: "POST /api/v1/sessions for each queued session, three times",
203
+ evidence: failed
204
+ .map((item) => `${item.entry.sessionId}: ${item.entry.lastError ?? "no error recorded"}`)
205
+ .join("\n"),
206
+ unknown: "whether the cause was the payload, the token or the network",
207
+ files: [queueDir()],
208
+ },
209
+ ];
210
+ }
211
+
212
+ /**
213
+ * Failures nothing else here explains. This is the part that must not be a
214
+ * lookup table: an error ISY has never seen still lands in the work order with
215
+ * its text intact, and the agent reads it rather than a category ISY guessed.
216
+ */
217
+ function journalProblems(
218
+ entries: readonly JournalEntry[],
219
+ lastUploadAt: string | undefined,
220
+ explained: readonly HealthProblem[],
221
+ ): HealthProblem[] {
222
+ const unresolved = unresolvedErrors(lastUploadAt, [...entries]);
223
+ if (unresolved.length === 0) return [];
224
+
225
+ // The structural checks above already carry their own evidence; a journal
226
+ // entry is worth reporting on its own only when nothing else accounts for it.
227
+ if (explained.length > 0) return [];
228
+
229
+ return [
230
+ {
231
+ id: "journal-errors",
232
+ summary: `${unresolved.length} unattended failure${
233
+ unresolved.length === 1 ? "" : "s"
234
+ } recorded since the last successful upload, with everything else looking correct`,
235
+ attempted: unresolved[unresolved.length - 1]?.operation
236
+ ? `run isy ${unresolved[unresolved.length - 1]!.operation!}`
237
+ : "run isy in the background",
238
+ evidence: unresolved.map((entry) => `${entry.at} ${entry.message}`).join("\n"),
239
+ unknown:
240
+ "everything: the configuration, the server and the file system all check out, so the cause is not in the places isy knows to look",
241
+ files: [logPath()],
242
+ },
243
+ ];
244
+ }
245
+
246
+ export async function collectHealth(cwd: string): Promise<HealthReport> {
247
+ const version = await packageVersion();
248
+ const verified: string[] = [];
249
+ const problems: HealthProblem[] = [];
250
+
251
+ problems.push(...(await configProblems(verified)));
252
+
253
+ let check: CheckReport | undefined;
254
+ try {
255
+ check = await collectCheck({ ping: true, cwd });
256
+ problems.push(...checkProblems(check, verified));
257
+ } catch (error) {
258
+ // A diagnostic that dies on a broken system is useless exactly when needed.
259
+ problems.push({
260
+ id: "check-threw",
261
+ summary: "the configuration check itself threw before it could finish",
262
+ attempted: "collect the report that `isy check` prints",
263
+ evidence: errorMessage(error),
264
+ unknown: "which of the checks threw",
265
+ files: [isyHome()],
266
+ });
267
+ }
268
+
269
+ problems.push(...(await agentProblems(cwd, verified)));
270
+ problems.push(...(await stateProblems(verified)));
271
+ problems.push(...(await queueProblems()));
272
+
273
+ const journal = readJournal(JOURNAL_CONTEXT);
274
+ const config = check ? { lastUploadAt: check.lastUploadAt } : {};
275
+ problems.push(...journalProblems(journal, config.lastUploadAt, problems));
276
+
277
+ return { ok: problems.length === 0, version, problems, verified, journal, check };
278
+ }
279
+
280
+ export function formatHealth(report: HealthReport, now: number): string {
281
+ if (report.ok && report.check) return formatCheck(report.check, now);
282
+ if (report.ok) return `ISY ${report.version} healthy`;
283
+
284
+ const count = report.problems.length;
285
+ const lines = [`ISY ${report.version} · ${count} problem${count === 1 ? "" : "s"}`, ""];
286
+
287
+ report.problems.forEach((problem, index) => {
288
+ lines.push(`${index + 1}. ${problem.summary}`);
289
+ lines.push(` tried ${problem.attempted}`);
290
+ for (const line of problem.evidence.split("\n")) lines.push(` got ${line}`);
291
+ lines.push("");
292
+ });
293
+
294
+ lines.push("run: isy health --fix — writes a work order for your coding agent");
295
+ return lines.join("\n");
296
+ }
297
+
298
+ /**
299
+ * The prompt handed to a coding agent. It states what was tried, what happened
300
+ * and what has already been ruled out, then stops: no suggested cause, no
301
+ * suggested patch. The agent has the whole repository and can read further; a
302
+ * cause invented here would only anchor it on ISY's guess.
303
+ */
304
+ export function formatWorkOrder(report: HealthReport, cwd: string): string {
305
+ const sections: string[] = [
306
+ "# ISY self-repair work order",
307
+ "",
308
+ "ISY is a CLI that collects coding-agent session transcripts and uploads them to a",
309
+ "server, which analyses them and comments on the matching pull request. It has just",
310
+ "failed its own health check. Find the cause and fix it.",
311
+ "",
312
+ "## Environment",
313
+ "",
314
+ "```",
315
+ `isy ${report.version}`,
316
+ `node ${process.version} on ${process.platform}`,
317
+ `cwd ${cwd}`,
318
+ `home ${isyHome()}`,
319
+ `config ${configPath()}`,
320
+ `journal ${logPath()}`,
321
+ "```",
322
+ "",
323
+ "## What is broken",
324
+ "",
325
+ ];
326
+
327
+ report.problems.forEach((problem, index) => {
328
+ sections.push(`### ${index + 1}. ${problem.summary}`);
329
+ sections.push("");
330
+ sections.push(`- **Operation:** ${problem.attempted}`);
331
+ sections.push("- **Result, verbatim:**");
332
+ sections.push("");
333
+ sections.push("```");
334
+ sections.push(problem.evidence);
335
+ sections.push("```");
336
+ sections.push("");
337
+ sections.push(`- **Not determined:** ${problem.unknown}`);
338
+ if (problem.files.length > 0) {
339
+ sections.push(`- **Paths involved:** ${problem.files.join(", ")}`);
340
+ }
341
+ sections.push("");
342
+ });
343
+
344
+ if (report.verified.length > 0) {
345
+ sections.push("## Already verified — do not spend turns re-checking these");
346
+ sections.push("");
347
+ for (const item of report.verified) sections.push(`- ${item}`);
348
+ sections.push("");
349
+ }
350
+
351
+ if (report.journal.length > 0) {
352
+ sections.push(`## Journal, last ${report.journal.length} entries`);
353
+ sections.push("");
354
+ sections.push("```");
355
+ for (const entry of report.journal) {
356
+ sections.push(`${entry.at} ${entry.level} ${entry.message}`);
357
+ }
358
+ sections.push("```");
359
+ sections.push("");
360
+ }
361
+
362
+ sections.push(
363
+ "## How to work this",
364
+ "",
365
+ "1. The headings above are what ISY observed, not a diagnosis. ISY does not know the",
366
+ " cause — if it did, it would have fixed it. Read the verbatim output and the",
367
+ " journal and work out the cause yourself; do not take a heading as the answer.",
368
+ "2. Reproduce before you change anything. `isy health --json` prints the same state",
369
+ " in machine-readable form.",
370
+ "3. Change the smallest thing that makes the check pass. Never make a check pass by",
371
+ " disabling, skipping or loosening the check itself.",
372
+ "4. If the cause is the user's environment rather than ISY's code — a revoked token,",
373
+ " a permission, a missing directory — say so and stop. Do not edit ISY's source to",
374
+ " work around a broken machine.",
375
+ "",
376
+ "## Done when",
377
+ "",
378
+ "`isy health` exits 0. Run it and show the output.",
379
+ );
380
+
381
+ return sections.join("\n");
382
+ }
383
+
384
+ /**
385
+ * Both go to stderr, never to stdout: stdout is the prompt itself, and a line
386
+ * telling the reader to paste it somewhere would be nonsense inside the prompt.
387
+ * Shown only on a terminal — a pipe means the user already knows where it goes.
388
+ *
389
+ * Printed at both ends because the work order is long: a banner only at the top
390
+ * scrolls away, and one only at the bottom is read after the user has already
391
+ * started reading a prompt that was never addressed to them.
392
+ */
393
+ const RULE = " " + "\u2550".repeat(72);
394
+
395
+ export const FIX_BANNER = [
396
+ "",
397
+ RULE,
398
+ " \u26a0 THIS IS A PROMPT FOR AN AI AGENT \u2014 NOT A REPORT FOR YOU TO READ.",
399
+ "",
400
+ " COPY EVERYTHING BELOW AND PASTE IT INTO YOUR CODING AGENT",
401
+ " (Claude Code, Kimi CLI, Codex \u2014 whichever you use). IT WILL FIX ISY.",
402
+ "",
403
+ " Or hand it over directly: isy health --fix | claude -p",
404
+ RULE,
405
+ "",
406
+ ].join("\n");
407
+
408
+ export const FIX_REMINDER = [
409
+ "",
410
+ RULE,
411
+ " \u26a0 EVERYTHING ABOVE IS THE PROMPT. PASTE IT INTO YOUR CODING AGENT.",
412
+ RULE,
413
+ "",
414
+ ].join("\n");
415
+
416
+ export async function runHealth(
417
+ options: { json?: boolean; fix?: boolean; scan?: boolean },
418
+ cwd: string,
419
+ ): Promise<void> {
420
+ // A scan is a different question from a health check: not "is this install
421
+ // working" but "where does this machine keep its sessions at all". It reports
422
+ // rather than judges, so it never sets an exit code.
423
+ if (options.scan) {
424
+ const scan = await collectScan();
425
+ console.log(options.json ? JSON.stringify(scan, null, 2) : formatScan(scan));
426
+ return;
427
+ }
428
+
429
+ const report = await collectHealth(cwd);
430
+
431
+ // A work order for a healthy install would be a prompt to fix nothing.
432
+ if (options.json) {
433
+ console.log(JSON.stringify(report, null, 2));
434
+ } else if (options.fix && !report.ok) {
435
+ if (process.stdout.isTTY) console.error(FIX_BANNER);
436
+ console.log(formatWorkOrder(report, cwd));
437
+ if (process.stdout.isTTY) console.error(FIX_REMINDER);
438
+ } else {
439
+ console.log(formatHealth(report, Date.now()));
440
+ }
441
+
442
+ // The exit code is the contract a repairing agent checks against.
443
+ if (!report.ok) process.exitCode = 1;
444
+ }
@@ -0,0 +1,186 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { DEFAULT_API_BASE_URL, verifyToken } from "../api.js";
4
+ import { readConfig, writeConfig } from "../config.js";
5
+ import { presentAgents } from "../agents/index.js";
6
+ import { GIT_HOOKS, gitHooksDir, installGitHook } from "../githook.js";
7
+ import { logLine } from "../log.js";
8
+ import { awaitPairedKey, openPairing } from "../pairing.js";
9
+ import type { Pairing } from "../pairing.js";
10
+ import { configPath } from "../paths.js";
11
+
12
+ function openBrowser(url: string): void {
13
+ const command =
14
+ process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
15
+ try {
16
+ execFile(command, [url], { windowsHide: true }, () => undefined);
17
+ } catch {
18
+ return;
19
+ }
20
+ }
21
+
22
+ /**
23
+ * The paste, still on offer.
24
+ *
25
+ * It is no longer the way in — the browser hands the key over by itself — but
26
+ * it is the way in that works everywhere: a browser signed in on another
27
+ * machine, a server too old to know the pairing route, a page the reader closed
28
+ * and reopened from their own history.
29
+ */
30
+ async function promptForToken(prompt: string, signal?: AbortSignal): Promise<string | undefined> {
31
+ if (!process.stdin.isTTY) return undefined;
32
+
33
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
34
+ try {
35
+ const answer = signal
36
+ ? await reader.question(prompt, { signal })
37
+ : await reader.question(prompt);
38
+ const token = answer.trim();
39
+ return token.length > 0 ? token : undefined;
40
+ } catch {
41
+ // Aborted: the browser answered first, and the question is moot.
42
+ return undefined;
43
+ } finally {
44
+ reader.close();
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Whichever arrives first — the key the browser hands over, or one pasted here.
50
+ *
51
+ * Neither is allowed to end the wait by coming back empty: a machine with no
52
+ * TTY has nothing to paste with, and a pairing that expires while the reader is
53
+ * still signing in should leave the paste standing rather than take the prompt
54
+ * away from under them.
55
+ */
56
+ function firstOf(
57
+ attempts: readonly Promise<string | undefined>[],
58
+ ): Promise<string | undefined> {
59
+ return new Promise((resolve) => {
60
+ let left = attempts.length;
61
+ const settle = (token: string | undefined) => {
62
+ if (token) resolve(token);
63
+ else if (--left === 0) resolve(undefined);
64
+ };
65
+ for (const attempt of attempts) void attempt.then(settle, () => settle(undefined));
66
+ });
67
+ }
68
+
69
+ /**
70
+ * Sign in through the keys screen.
71
+ *
72
+ * `isy init` opens `/settings/api_keys` rather than the sign-in page that
73
+ * prints a token: the screen there can make a key, name it, and revoke the one
74
+ * a lost machine still holds, and it hands what it makes straight back to this
75
+ * terminal (`pairing.ts`). Signing in comes free with it — the page is behind
76
+ * the session, so a browser that is not signed in goes through GitHub on its
77
+ * way and lands back on the page it was asked for.
78
+ */
79
+ async function keyFromBrowser(baseUrl: string, pairing: Pairing): Promise<string | undefined> {
80
+ console.log(`Opening ${pairing.connectUrl}`);
81
+ console.log("If the browser does not open, visit that URL yourself.");
82
+ // The code is the check, not the connection: that page is reached by a link,
83
+ // and a link can be sent by someone else. A page showing a different code is
84
+ // waiting for a different terminal.
85
+ console.log(`That page should show the code ${pairing.userCode}. Create a key there.`);
86
+ openBrowser(pairing.connectUrl);
87
+
88
+ const controller = new AbortController();
89
+ try {
90
+ return await firstOf([
91
+ awaitPairedKey(baseUrl, pairing, controller.signal).then((key) => {
92
+ if (!key) return undefined;
93
+ const who = key.githubLogin ? ` (${key.githubLogin})` : "";
94
+ console.log(`Key received from the browser${who}.`);
95
+ return key.token;
96
+ }),
97
+ promptForToken("Waiting for that page — or paste a key here: ", controller.signal),
98
+ ]);
99
+ } finally {
100
+ // Whichever lost is still running: the poll holds a socket, the prompt
101
+ // holds stdin, and either would keep the process from exiting.
102
+ controller.abort();
103
+ }
104
+ }
105
+
106
+ /** The flow before the keys screen could answer: a page that prints a token, and a paste. */
107
+ async function signInAndPaste(authUrl: string): Promise<string | undefined> {
108
+ console.log(`Opening ${authUrl}`);
109
+ console.log("If the browser does not open, visit that URL yourself.");
110
+ openBrowser(authUrl);
111
+ return promptForToken("Paste the token from that page: ");
112
+ }
113
+
114
+ export async function runInit(options: { token?: string }, cwd: string): Promise<void> {
115
+ const config = await readConfig();
116
+ const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;
117
+ const authUrl = new URL("/auth/github", baseUrl).toString();
118
+
119
+ let token = options.token;
120
+ if (!token) {
121
+ // Only when the pairing could not be opened at all — a server that predates
122
+ // it, or one with no dashboard address. A pairing that was opened and then
123
+ // ran out has already had its browser window; a second one would be two
124
+ // tabs and two codes for one sign-in.
125
+ const pairing = await openPairing(baseUrl);
126
+ token = pairing ? await keyFromBrowser(baseUrl, pairing) : await signInAndPaste(authUrl);
127
+ }
128
+
129
+ if (!token) {
130
+ throw new Error(`no token provided. Visit ${authUrl}, then run: isy init --token <token>`);
131
+ }
132
+
133
+ // The keys screen lists every key by its preview, `isy_abcd…wxyz`, and that is
134
+ // what gets copied off it. Sent as it is, the ellipsis cannot go into an HTTP
135
+ // header, and the failure read as though the server could not be reached.
136
+ if (token.includes("…") || token.includes("...")) {
137
+ throw new Error(
138
+ "that is a key's preview, not the key: the whole key is shown once, when it is created. " +
139
+ `Run isy init again and create a key on the page it opens, or at ${new URL("/settings/api_keys", baseUrl)}`,
140
+ );
141
+ }
142
+
143
+ const verified = await verifyToken({ baseUrl, token });
144
+ if (!verified.ok) throw new Error(verified.error);
145
+
146
+ await writeConfig({ ...config, token, githubLogin: verified.githubLogin });
147
+ console.log(`Token stored in ${configPath()}`);
148
+
149
+ // Hooks go into every CLI actually installed here, and none that is not.
150
+ const agents = await presentAgents();
151
+ if (agents.length === 0) {
152
+ logLine("init: token stored, no supported CLI found");
153
+ console.log("No supported CLI found. Looked for Claude Code, Kimi CLI and Codex CLI.");
154
+ }
155
+
156
+ for (const agent of agents) {
157
+ const hook = await agent.installHooks();
158
+ logLine(`init: ${agent.id} hooks ${hook}`);
159
+ console.log(
160
+ hook === "installed"
161
+ ? `Added ${agent.label} hooks (${agent.hooks().map((entry) => entry.event).join(", ")}) in ${agent.configLocation()}`
162
+ : `${agent.label} hooks already present in ${agent.configLocation()}`,
163
+ );
164
+ if (hook === "installed" && agent.afterInstall) console.log(agent.afterInstall);
165
+ }
166
+
167
+ // The commit is what starts the loop: it is the first moment the transcript
168
+ // and the SHA it belongs to both exist. The push is when the analysis is
169
+ // waiting for it. Per repository, so this only touches the one the user ran
170
+ // init in.
171
+ const gitHook = await installGitHook(cwd);
172
+ logLine(`init: git hooks ${gitHook}`);
173
+ if (gitHook === "not-a-repository") {
174
+ console.log(`${cwd} is not a git repository, so no git hooks were added.`);
175
+ } else {
176
+ const names = GIT_HOOKS.map((hook) => hook.name).join(" and ");
177
+ const where = await gitHooksDir(cwd);
178
+ console.log(
179
+ gitHook === "installed"
180
+ ? `Added the ${names} hooks in ${where}`
181
+ : `The ${names} hooks are already present in ${where}`,
182
+ );
183
+ }
184
+
185
+ if (verified.githubLogin) console.log(`Signed in as ${verified.githubLogin}`);
186
+ }
@@ -0,0 +1,33 @@
1
+ import { presentAgents } from "../agents/index.js";
2
+ import { removeGitHook } from "../githook.js";
3
+ import { readConfig, writeConfig } from "../config.js";
4
+ import { logLine } from "../log.js";
5
+ import { configPath } from "../paths.js";
6
+
7
+ export async function runLogout(cwd: string): Promise<void> {
8
+ const config = await readConfig();
9
+ const hadToken = typeof config.token === "string" && config.token.length > 0;
10
+
11
+ const { token: _token, githubLogin: _githubLogin, ...rest } = config;
12
+ await writeConfig(rest);
13
+ console.log(hadToken ? `Token removed from ${configPath()}` : "No token was configured");
14
+
15
+ let removed = 0;
16
+ for (const agent of await presentAgents()) {
17
+ const hook = await agent.removeHooks();
18
+ logLine(`logout: ${agent.id} hooks ${hook}`);
19
+ if (hook === "removed") {
20
+ removed += 1;
21
+ console.log(`${agent.label} hooks removed from ${agent.configLocation()}`);
22
+ }
23
+ }
24
+
25
+ const gitHook = await removeGitHook(cwd);
26
+ logLine(`logout: git hooks ${gitHook}`);
27
+ if (gitHook === "removed") {
28
+ removed += 1;
29
+ console.log("git hooks removed from this repository");
30
+ }
31
+
32
+ if (removed === 0) console.log("No ISY hooks were installed");
33
+ }