@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/git.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+
4
+ const run = promisify(execFile);
5
+
6
+ const GIT_TIMEOUT_MS = 5000;
7
+ const RECENT_SHA_COUNT = 50;
8
+
9
+ export interface GitMetadata {
10
+ remote: string;
11
+ branch: string;
12
+ headSha: string;
13
+ recentShas: string[];
14
+ }
15
+
16
+ export type GitFailure = "not-a-repository" | "no-commits" | "no-remote";
17
+
18
+ export type GitResult =
19
+ | { ok: true; metadata: GitMetadata }
20
+ | { ok: false; reason: GitFailure };
21
+
22
+ async function git(cwd: string, args: string[]): Promise<string | undefined> {
23
+ try {
24
+ const { stdout } = await run("git", args, {
25
+ cwd,
26
+ timeout: GIT_TIMEOUT_MS,
27
+ maxBuffer: 4 * 1024 * 1024,
28
+ windowsHide: true,
29
+ });
30
+ const value = stdout.trim();
31
+ return value.length > 0 ? value : undefined;
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ }
36
+
37
+ function remotePath(url: string): string | undefined {
38
+ const trimmed = url.trim().replace(/\.git$/i, "").replace(/\/+$/, "");
39
+ if (trimmed.length === 0) return undefined;
40
+
41
+ const scp = /^(?:[^@/]+@)?([^/:]+):(?!\/\/)(.+)$/.exec(trimmed);
42
+ if (scp) return scp[2];
43
+
44
+ try {
45
+ return new URL(trimmed).pathname;
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ export function normalizeRemote(url: string): string | undefined {
52
+ const path = remotePath(url);
53
+ if (!path) return undefined;
54
+
55
+ const parts = path.split("/").filter((part) => part.length > 0);
56
+ if (parts.length < 2) return undefined;
57
+
58
+ return `${parts[parts.length - 2]}/${parts[parts.length - 1]}`;
59
+ }
60
+
61
+ export async function collectGitMetadata(cwd: string): Promise<GitResult> {
62
+ const insideWorkTree = await git(cwd, ["rev-parse", "--is-inside-work-tree"]);
63
+ if (insideWorkTree !== "true") return { ok: false, reason: "not-a-repository" };
64
+
65
+ const headSha = await git(cwd, ["rev-parse", "HEAD"]);
66
+ if (!headSha) return { ok: false, reason: "no-commits" };
67
+
68
+ const remoteUrl = await git(cwd, ["config", "--get", "remote.origin.url"]);
69
+ const remote = remoteUrl ? normalizeRemote(remoteUrl) : undefined;
70
+ if (!remote) return { ok: false, reason: "no-remote" };
71
+
72
+ const branch = (await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])) ?? "HEAD";
73
+ const log = await git(cwd, ["log", "--format=%H", "-n", String(RECENT_SHA_COUNT)]);
74
+ const recentShas = log ? log.split("\n").map((line) => line.trim()).filter(Boolean) : [headSha];
75
+
76
+ return { ok: true, metadata: { remote, branch, headSha, recentShas } };
77
+ }
78
+
79
+ /**
80
+ * HEAD alone, without the remote a full upload needs. A repository with no
81
+ * remote still deserves local signals, so this must not fail where
82
+ * `collectGitMetadata` does.
83
+ */
84
+ export async function headSha(cwd: string): Promise<string | undefined> {
85
+ return git(cwd, ["rev-parse", "HEAD"]);
86
+ }
package/src/githook.ts ADDED
@@ -0,0 +1,269 @@
1
+ import { execFile } from "node:child_process";
2
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve } from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const run = promisify(execFile);
7
+
8
+ const GIT_TIMEOUT_MS = 5000;
9
+ const SHEBANG = "#!/bin/sh";
10
+ const BEGIN = "# isy:begin — managed by isy, do not edit inside this block";
11
+ const END = "# isy:end";
12
+
13
+ /**
14
+ * `|| true` is not about git — git ignores what post-commit returns, the commit
15
+ * already happened. It is about the user's own script: a hook running under
16
+ * `set -e` must not abort at our line.
17
+ */
18
+ export const COMMIT_COMMAND = "npx @nightloom/isy commit --hook || true";
19
+
20
+ /**
21
+ * The push is the moment the analysis is actually waiting for: a pull request
22
+ * is opened or updated seconds later, and matching is by commit SHA. The
23
+ * commit hook alone leaves a gap — a session that kept working after the last
24
+ * commit, or a commit made before isy was installed in this repository.
25
+ *
26
+ * Backgrounded rather than run: git waits for pre-push, and a push must not
27
+ * stop for the network. Its exit code is therefore never ours, which is also
28
+ * why nothing here can reject a push. stdin is closed explicitly — git writes
29
+ * the refs being pushed to it, and the upload has no use for them.
30
+ *
31
+ * Backgrounding is also why the block has to go at the top of the file rather
32
+ * than the bottom (`insert`): `&` always succeeds, so as the last line of
33
+ * someone else's pre-push it would hand git a 0 for a push their own hook had
34
+ * just rejected.
35
+ */
36
+ export const PUSH_COMMAND = "npx @nightloom/isy upload --silent --all >/dev/null 2>&1 </dev/null &";
37
+
38
+ /**
39
+ * The repository-side hooks, both written into the same managed block format.
40
+ * One list, because every operation here — install, inspect, remove — has to
41
+ * cover all of them or leave the repository half-wired.
42
+ */
43
+ export const GIT_HOOKS: { name: string; command: string }[] = [
44
+ { name: "post-commit", command: COMMIT_COMMAND },
45
+ { name: "pre-push", command: PUSH_COMMAND },
46
+ ];
47
+
48
+ export type GitHookOutcome =
49
+ | "installed"
50
+ | "already-present"
51
+ | "removed"
52
+ | "absent"
53
+ | "not-a-repository";
54
+
55
+ function block(command: string): string {
56
+ return `${BEGIN}\n${command}\n${END}`;
57
+ }
58
+
59
+ /**
60
+ * Where a new block goes: straight after the shebang, ahead of whatever the
61
+ * user's own script does.
62
+ *
63
+ * Two reasons, one position. A hook whose last statement is `exec` or `exit`
64
+ * never reaches a block appended below it — and isy would still report it as
65
+ * installed, because the text is in the file. And the hook's exit status is the
66
+ * status of its last command, so a block at the bottom answers git on the
67
+ * user's behalf: for pre-push that turns a rejection into a push.
68
+ */
69
+ function insert(contents: string, desired: string): string {
70
+ if (!contents.startsWith("#!")) return `${desired}\n${contents}`;
71
+
72
+ // A file that is nothing but a shebang has no line to insert before.
73
+ const cut = contents.indexOf("\n");
74
+ if (cut < 0) return `${contents}\n${desired}\n`;
75
+
76
+ return `${contents.slice(0, cut + 1)}${desired}\n${contents.slice(cut + 1)}`;
77
+ }
78
+
79
+ /**
80
+ * Where git will actually look for hooks in this repository. `--git-path`
81
+ * honours `core.hooksPath`, so a repo driven by husky or lefthook gets the
82
+ * block in the directory those tools own rather than in a `.git/hooks` git
83
+ * never reads.
84
+ */
85
+ export async function gitHooksDir(cwd: string): Promise<string | undefined> {
86
+ try {
87
+ const { stdout } = await run("git", ["rev-parse", "--git-path", "hooks"], {
88
+ cwd,
89
+ timeout: GIT_TIMEOUT_MS,
90
+ windowsHide: true,
91
+ });
92
+ const path = stdout.trim();
93
+ if (path.length === 0) return undefined;
94
+ return isAbsolute(path) ? path : resolve(cwd, path);
95
+ } catch {
96
+ return undefined;
97
+ }
98
+ }
99
+
100
+ /** Where git would look for one of our hooks in this repository. */
101
+ export async function hookPath(cwd: string, name: string): Promise<string | undefined> {
102
+ const dir = await gitHooksDir(cwd);
103
+ return dir === undefined ? undefined : resolve(dir, name);
104
+ }
105
+
106
+ export function postCommitPath(cwd: string): Promise<string | undefined> {
107
+ return hookPath(cwd, "post-commit");
108
+ }
109
+
110
+ export function prePushPath(cwd: string): Promise<string | undefined> {
111
+ return hookPath(cwd, "pre-push");
112
+ }
113
+
114
+ async function readHook(path: string): Promise<string | undefined> {
115
+ try {
116
+ return await readFile(path, "utf8");
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ /** The managed block as it currently stands in this file, if it is there at all. */
123
+ function existingBlock(contents: string): string | undefined {
124
+ const start = contents.indexOf(BEGIN);
125
+ if (start < 0) return undefined;
126
+ const stop = contents.indexOf(END, start);
127
+ return stop < 0 ? undefined : contents.slice(start, stop + END.length);
128
+ }
129
+
130
+ async function oneInstalled(cwd: string, hook: { name: string; command: string }): Promise<boolean> {
131
+ const path = await hookPath(cwd, hook.name);
132
+ if (!path) return false;
133
+ const contents = await readHook(path);
134
+ return contents !== undefined && existingBlock(contents) === block(hook.command);
135
+ }
136
+
137
+ /** True only with every hook in place: half-wired is not installed. */
138
+ export async function gitHookInstalled(cwd: string): Promise<boolean> {
139
+ for (const hook of GIT_HOOKS) if (!(await oneInstalled(cwd, hook))) return false;
140
+ return true;
141
+ }
142
+
143
+ async function installOne(
144
+ cwd: string,
145
+ hook: { name: string; command: string },
146
+ ): Promise<GitHookOutcome> {
147
+ const path = await hookPath(cwd, hook.name);
148
+ if (!path) return "not-a-repository";
149
+
150
+ const contents = await readHook(path);
151
+ const desired = block(hook.command);
152
+
153
+ if (contents === undefined) {
154
+ await writeFile(path, `${SHEBANG}\n${desired}\n`, "utf8");
155
+ await chmod(path, 0o755);
156
+ return "installed";
157
+ }
158
+
159
+ const existing = existingBlock(contents);
160
+ if (existing === desired) {
161
+ // A hook git will not execute is not installed, whatever the file says.
162
+ await chmod(path, 0o755);
163
+ return "already-present";
164
+ }
165
+
166
+ const next = existing === undefined ? insert(contents, desired) : contents.replace(existing, desired);
167
+
168
+ await writeFile(path, next, "utf8");
169
+ await chmod(path, 0o755);
170
+ return "installed";
171
+ }
172
+
173
+ /**
174
+ * Adds the block to each of this repository's hooks, creating the file where
175
+ * there is none and inserting above the user's own script where there is
176
+ * (`insert`). An older block is replaced in place rather than stacked — which is also how a
177
+ * repository wired by an isy that only knew about post-commit picks up
178
+ * pre-push: it reports "installed" until every hook is there.
179
+ */
180
+ export async function installGitHook(cwd: string): Promise<GitHookOutcome> {
181
+ let outcome: GitHookOutcome = "already-present";
182
+
183
+ for (const hook of GIT_HOOKS) {
184
+ const result = await installOne(cwd, hook);
185
+ if (result === "not-a-repository") return result;
186
+ if (result === "installed") outcome = "installed";
187
+ }
188
+
189
+ return outcome;
190
+ }
191
+
192
+ /**
193
+ * The hooks directory and the git directory, both absolute and both resolved by
194
+ * git, so a worktree or a symlinked checkout compares like for like.
195
+ */
196
+ async function hookLocation(cwd: string): Promise<{ hooks: string; gitDir: string } | undefined> {
197
+ try {
198
+ const { stdout } = await run(
199
+ "git",
200
+ ["rev-parse", "--path-format=absolute", "--git-path", "hooks", "--git-common-dir"],
201
+ { cwd, timeout: GIT_TIMEOUT_MS, windowsHide: true },
202
+ );
203
+ const [hooks, gitDir] = stdout.split("\n").map((line) => line.trim());
204
+ return hooks && gitDir ? { hooks, gitDir } : undefined;
205
+ } catch {
206
+ return undefined;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * What the SessionEnd hook runs in every repository a session happened in, so
212
+ * `isy init` is once per machine rather than once per repository. It writes
213
+ * only where nobody else will see it: a hooks directory inside the git
214
+ * directory. One that core.hooksPath points elsewhere — `.husky`, a team's
215
+ * `githooks/` — is usually committed, and writing there would hand the hook to
216
+ * every teammate. That one is left to `isy init`, run on purpose.
217
+ */
218
+ export async function autoInstallGitHook(cwd: string): Promise<GitHookOutcome | "shared-hooks"> {
219
+ const location = await hookLocation(cwd);
220
+ if (!location) return "not-a-repository";
221
+ if (await gitHookInstalled(cwd)) return "already-present";
222
+
223
+ const inside = relative(location.gitDir, location.hooks);
224
+ if (inside.startsWith("..") || isAbsolute(inside)) return "shared-hooks";
225
+
226
+ // A repository created without templates has no hooks directory at all.
227
+ await mkdir(location.hooks, { recursive: true });
228
+ return installGitHook(cwd);
229
+ }
230
+
231
+ async function removeOne(cwd: string, name: string): Promise<GitHookOutcome> {
232
+ const path = await hookPath(cwd, name);
233
+ if (!path) return "not-a-repository";
234
+
235
+ const contents = await readHook(path);
236
+ if (contents === undefined) return "absent";
237
+
238
+ const existing = existingBlock(contents);
239
+ if (existing === undefined) return "absent";
240
+
241
+ const stripped = contents.replace(existing, "").replace(/\n{3,}/g, "\n\n");
242
+
243
+ if (stripped.replace(SHEBANG, "").trim().length === 0) {
244
+ await rm(path, { force: true });
245
+ return "removed";
246
+ }
247
+
248
+ await writeFile(path, stripped.endsWith("\n") ? stripped : `${stripped}\n`, "utf8");
249
+ return "removed";
250
+ }
251
+
252
+ /**
253
+ * Strips the block from every hook it is in. A file that held nothing but our
254
+ * block is deleted rather than left as an empty script, so uninstalling puts
255
+ * the repo back as it was. "removed" when anything was there to remove: a
256
+ * repository wired by an older isy has only the post-commit block, and that is
257
+ * still an uninstall.
258
+ */
259
+ export async function removeGitHook(cwd: string): Promise<GitHookOutcome> {
260
+ let outcome: GitHookOutcome = "absent";
261
+
262
+ for (const hook of GIT_HOOKS) {
263
+ const result = await removeOne(cwd, hook.name);
264
+ if (result === "not-a-repository") return result;
265
+ if (result === "removed") outcome = "removed";
266
+ }
267
+
268
+ return outcome;
269
+ }
package/src/hook.ts ADDED
@@ -0,0 +1,237 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
3
+ import type { AgentHook } from "./agents/types.js";
4
+ import { claudeConfigDir, claudeSettingsPath } from "./paths.js";
5
+
6
+ export const HOOK_EVENT = "SessionEnd";
7
+ export const HOOK_COMMAND = "npx @nightloom/isy upload --hook";
8
+ export const START_HOOK_EVENT = "SessionStart";
9
+ export const START_HOOK_COMMAND = "npx @nightloom/isy check --hook";
10
+
11
+ /**
12
+ * The scope is spelled out, and npx stays. npx resolves a bare name against the
13
+ * registry rather than against PATH, and the registry's `isy` is an unrelated
14
+ * package — this one publishes as `@nightloom/isy`, so a hook saying `npx isy`
15
+ * would fetch a stranger. Keeping npx is what lets a machine that was set up
16
+ * with `npx @nightloom/isy init` and never installed anything globally keep
17
+ * working. Every command an older isy wrote is listed as superseded, so
18
+ * installing over it rewrites that line in place instead of leaving two hooks
19
+ * to fire.
20
+ */
21
+ export const ISY_HOOKS: { event: string; command: string; superseded: string[] }[] = [
22
+ {
23
+ event: HOOK_EVENT,
24
+ command: HOOK_COMMAND,
25
+ superseded: ["npx isy upload --silent", "npx isy upload --hook"],
26
+ },
27
+ { event: START_HOOK_EVENT, command: START_HOOK_COMMAND, superseded: ["npx isy check --hook"] },
28
+ ];
29
+
30
+ /**
31
+ * A JSON file holding hooks under a top-level `hooks` key. Claude Code's
32
+ * settings.json and Codex CLI's hooks.json use the same shape down to the
33
+ * matcher group, so one implementation serves both.
34
+ */
35
+ export interface HookFile {
36
+ path: string;
37
+ hooks: readonly AgentHook[];
38
+ }
39
+
40
+ export function claudeHookFile(): HookFile {
41
+ return { path: claudeSettingsPath(), hooks: ISY_HOOKS };
42
+ }
43
+
44
+ interface HookCommand {
45
+ type?: string;
46
+ command?: string;
47
+ [key: string]: unknown;
48
+ }
49
+
50
+ interface HookMatcher {
51
+ hooks?: HookCommand[];
52
+ [key: string]: unknown;
53
+ }
54
+
55
+ function isObject(value: unknown): value is Record<string, unknown> {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value);
57
+ }
58
+
59
+ async function readSettings(file: HookFile): Promise<Record<string, unknown>> {
60
+ let contents: string;
61
+ try {
62
+ contents = await readFile(file.path, "utf8");
63
+ } catch {
64
+ return {};
65
+ }
66
+
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(contents);
70
+ } catch (cause) {
71
+ const reason = cause instanceof Error ? cause.message : String(cause);
72
+ throw new Error(`${file.path} is not valid JSON: ${reason}`);
73
+ }
74
+
75
+ if (!isObject(parsed)) {
76
+ throw new Error(`${file.path} does not contain a JSON object`);
77
+ }
78
+ return parsed;
79
+ }
80
+
81
+ async function writeSettings(file: HookFile, settings: Record<string, unknown>): Promise<void> {
82
+ await mkdir(dirname(file.path), { recursive: true });
83
+
84
+ const temporary = join(dirname(file.path), `.${basename(file.path)}.isy-${process.pid}`);
85
+ await writeFile(temporary, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
86
+ await rename(temporary, file.path);
87
+ }
88
+
89
+ function matchers(settings: Record<string, unknown>, event: string): HookMatcher[] {
90
+ const hooks = settings.hooks;
91
+ if (!isObject(hooks)) return [];
92
+ const entries = hooks[event];
93
+ return Array.isArray(entries) ? (entries.filter(isObject) as HookMatcher[]) : [];
94
+ }
95
+
96
+ function hasHook(
97
+ settings: Record<string, unknown>,
98
+ event: string,
99
+ commands: readonly string[],
100
+ ): boolean {
101
+ return matchers(settings, event).some((matcher) =>
102
+ Array.isArray(matcher.hooks) &&
103
+ matcher.hooks.some(
104
+ (entry) => isObject(entry) && typeof entry.command === "string" && commands.includes(entry.command),
105
+ ),
106
+ );
107
+ }
108
+
109
+ function stripHook(
110
+ settings: Record<string, unknown>,
111
+ hooks: Record<string, unknown>,
112
+ event: string,
113
+ commands: readonly string[],
114
+ ): void {
115
+ const kept: unknown[] = [];
116
+
117
+ for (const matcher of matchers(settings, event)) {
118
+ if (!Array.isArray(matcher.hooks)) {
119
+ kept.push(matcher);
120
+ continue;
121
+ }
122
+ const remaining = matcher.hooks.filter(
123
+ (entry) =>
124
+ !(isObject(entry) && typeof entry.command === "string" && commands.includes(entry.command)),
125
+ );
126
+ if (remaining.length > 0) kept.push({ ...matcher, hooks: remaining });
127
+ }
128
+
129
+ if (kept.length > 0) hooks[event] = kept;
130
+ else delete hooks[event];
131
+ }
132
+
133
+ /**
134
+ * Swap the first superseded command for its replacement at the same group and
135
+ * position, dropping any further copies, so no group's index moves.
136
+ */
137
+ function replaceSuperseded(
138
+ groups: unknown[],
139
+ commands: readonly string[],
140
+ command: string,
141
+ ): boolean {
142
+ let replaced = false;
143
+ for (const group of groups) {
144
+ if (!isObject(group) || !Array.isArray(group.hooks)) continue;
145
+ group.hooks = (group.hooks as unknown[]).filter((entry: unknown) => {
146
+ if (!isObject(entry) || typeof entry.command !== "string" || !commands.includes(entry.command)) {
147
+ return true;
148
+ }
149
+ if (replaced) return false;
150
+ entry.command = command;
151
+ replaced = true;
152
+ return true;
153
+ });
154
+ }
155
+ return replaced;
156
+ }
157
+
158
+ export async function installedHooksIn(file: HookFile): Promise<string[]> {
159
+ const settings = await readSettings(file);
160
+ return file.hooks.filter((hook) => hasHook(settings, hook.event, [hook.command])).map(
161
+ (hook) => hook.event,
162
+ );
163
+ }
164
+
165
+ export async function installHookIn(file: HookFile): Promise<"installed" | "already-present"> {
166
+ const settings = await readSettings(file);
167
+ const missing = file.hooks.filter((hook) => !hasHook(settings, hook.event, [hook.command]));
168
+ if (missing.length === 0) return "already-present";
169
+
170
+ const hooks = isObject(settings.hooks) ? { ...settings.hooks } : {};
171
+ for (const hook of missing) {
172
+ // Appended, never prepended: Codex keys its hook trust ledger by position
173
+ // (`hooks.json:session_start:0:0`), so inserting ahead of an existing group
174
+ // would silently untrust the user's own hooks.
175
+ const existing = Array.isArray(hooks[hook.event]) ? [...(hooks[hook.event] as unknown[])] : [];
176
+
177
+ // An older isy wrote a different command for the same job: swap it in
178
+ // place. Strip-then-append would move it to the end, shifting the groups
179
+ // after it — and with them the positions Codex keys its approvals on, so
180
+ // the user's hooks would lose their approval and ours would inherit one it
181
+ // was never given.
182
+ const replaced =
183
+ hook.superseded !== undefined && replaceSuperseded(existing, hook.superseded, hook.command);
184
+ if (!replaced) existing.push({ hooks: [{ type: "command", command: hook.command }] });
185
+
186
+ hooks[hook.event] = existing;
187
+ }
188
+
189
+ await writeSettings(file, { ...settings, hooks });
190
+ return "installed";
191
+ }
192
+
193
+ export async function removeHookIn(file: HookFile): Promise<"removed" | "absent"> {
194
+ const settings = await readSettings(file);
195
+ const present = file.hooks.filter((hook) =>
196
+ hasHook(settings, hook.event, [hook.command, ...(hook.superseded ?? [])]),
197
+ );
198
+ if (present.length === 0) return "absent";
199
+
200
+ const hooks = isObject(settings.hooks) ? { ...settings.hooks } : {};
201
+ for (const hook of present) {
202
+ stripHook(settings, hooks, hook.event, [hook.command, ...(hook.superseded ?? [])]);
203
+ }
204
+
205
+ const next: Record<string, unknown> = { ...settings };
206
+ if (Object.keys(hooks).length > 0) next.hooks = hooks;
207
+ else delete next.hooks;
208
+
209
+ await writeSettings(file, next);
210
+ return "removed";
211
+ }
212
+
213
+ export async function isHookInstalled(): Promise<boolean> {
214
+ const file = claudeHookFile();
215
+ const settings = await readSettings(file);
216
+ return ISY_HOOKS.every((hook) => hasHook(settings, hook.event, [hook.command]));
217
+ }
218
+
219
+ export function installedHooks(): Promise<string[]> {
220
+ return installedHooksIn(claudeHookFile());
221
+ }
222
+
223
+ export function installHook(): Promise<"installed" | "already-present"> {
224
+ return installHookIn(claudeHookFile());
225
+ }
226
+
227
+ export function removeHook(): Promise<"removed" | "absent"> {
228
+ return removeHookIn(claudeHookFile());
229
+ }
230
+
231
+ export function settingsLocation(): string {
232
+ return claudeSettingsPath();
233
+ }
234
+
235
+ export function configDirectory(): string {
236
+ return claudeConfigDir();
237
+ }