@nightloom/isy 1.0.5 → 1.0.6-next.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 (108) hide show
  1. package/README.md +17 -2
  2. package/dist/agents/claude.js +3 -2
  3. package/dist/agents/claude.js.map +1 -1
  4. package/dist/agents/codex.js +14 -5
  5. package/dist/agents/codex.js.map +1 -1
  6. package/dist/agents/index.d.ts +14 -10
  7. package/dist/agents/index.js +65 -15
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/agents/kimi.js +26 -8
  10. package/dist/agents/kimi.js.map +1 -1
  11. package/dist/agents/types.d.ts +12 -3
  12. package/dist/commands/commit.d.ts +6 -0
  13. package/dist/commands/commit.js +326 -16
  14. package/dist/commands/commit.js.map +1 -1
  15. package/dist/commands/health.js +1 -1
  16. package/dist/commands/health.js.map +1 -1
  17. package/dist/commands/init.js +30 -5
  18. package/dist/commands/init.js.map +1 -1
  19. package/dist/commands/status.d.ts +2 -0
  20. package/dist/commands/status.js +7 -4
  21. package/dist/commands/status.js.map +1 -1
  22. package/dist/commands/upload.d.ts +8 -1
  23. package/dist/commands/upload.js +46 -39
  24. package/dist/commands/upload.js.map +1 -1
  25. package/dist/detectors.d.ts +32 -0
  26. package/dist/detectors.js +279 -72
  27. package/dist/detectors.js.map +1 -1
  28. package/dist/git.d.ts +52 -0
  29. package/dist/git.js +166 -9
  30. package/dist/git.js.map +1 -1
  31. package/dist/githook.d.ts +18 -7
  32. package/dist/githook.js +147 -17
  33. package/dist/githook.js.map +1 -1
  34. package/dist/hook.d.ts +22 -2
  35. package/dist/hook.js +28 -3
  36. package/dist/hook.js.map +1 -1
  37. package/dist/index.js +14 -5
  38. package/dist/index.js.map +1 -1
  39. package/dist/mask-paths.d.ts +4 -3
  40. package/dist/mask-paths.js +4 -3
  41. package/dist/mask-paths.js.map +1 -1
  42. package/dist/parser.d.ts +58 -9
  43. package/dist/parser.js +337 -58
  44. package/dist/parser.js.map +1 -1
  45. package/dist/paths.d.ts +19 -1
  46. package/dist/paths.js +28 -3
  47. package/dist/paths.js.map +1 -1
  48. package/dist/redact.d.ts +2 -0
  49. package/dist/redact.js +956 -97
  50. package/dist/redact.js.map +1 -1
  51. package/dist/stage0.js +27 -8
  52. package/dist/stage0.js.map +1 -1
  53. package/dist/state.d.ts +15 -0
  54. package/dist/state.js +8 -0
  55. package/dist/state.js.map +1 -1
  56. package/dist/test/check.test.js +1 -1
  57. package/dist/test/check.test.js.map +1 -1
  58. package/dist/test/codex.test.js +27 -4
  59. package/dist/test/codex.test.js.map +1 -1
  60. package/dist/test/commit.test.js +1466 -6
  61. package/dist/test/commit.test.js.map +1 -1
  62. package/dist/test/e2e-harness.test.d.ts +1 -0
  63. package/dist/test/e2e-harness.test.js +53 -0
  64. package/dist/test/e2e-harness.test.js.map +1 -0
  65. package/dist/test/git.test.js +72 -2
  66. package/dist/test/git.test.js.map +1 -1
  67. package/dist/test/hook.test.js +138 -3
  68. package/dist/test/hook.test.js.map +1 -1
  69. package/dist/test/init.test.js +60 -1
  70. package/dist/test/init.test.js.map +1 -1
  71. package/dist/test/kimi-config.test.js +27 -5
  72. package/dist/test/kimi-config.test.js.map +1 -1
  73. package/dist/test/kimi-hook.test.js +1 -1
  74. package/dist/test/kimi-hook.test.js.map +1 -1
  75. package/dist/test/kimi-listing.test.js +42 -2
  76. package/dist/test/kimi-listing.test.js.map +1 -1
  77. package/dist/test/kimi.test.js +26 -2
  78. package/dist/test/kimi.test.js.map +1 -1
  79. package/dist/test/parser.test.js +527 -1
  80. package/dist/test/parser.test.js.map +1 -1
  81. package/dist/test/redact.test.js +2442 -14
  82. package/dist/test/redact.test.js.map +1 -1
  83. package/dist/test/stage0.test.js +617 -1
  84. package/dist/test/stage0.test.js.map +1 -1
  85. package/dist/test/sweep.test.js +99 -3
  86. package/dist/test/sweep.test.js.map +1 -1
  87. package/package.json +1 -1
  88. package/src/agents/claude.ts +3 -2
  89. package/src/agents/codex.ts +14 -5
  90. package/src/agents/index.ts +71 -16
  91. package/src/agents/kimi.ts +28 -8
  92. package/src/agents/types.ts +12 -3
  93. package/src/commands/commit.ts +354 -18
  94. package/src/commands/health.ts +1 -1
  95. package/src/commands/init.ts +37 -7
  96. package/src/commands/status.ts +9 -4
  97. package/src/commands/upload.ts +54 -54
  98. package/src/detectors.ts +284 -75
  99. package/src/git.ts +175 -9
  100. package/src/githook.ts +151 -19
  101. package/src/hook.ts +30 -3
  102. package/src/index.ts +15 -5
  103. package/src/mask-paths.ts +5 -4
  104. package/src/parser.ts +355 -51
  105. package/src/paths.ts +30 -3
  106. package/src/redact.ts +959 -100
  107. package/src/stage0.ts +28 -8
  108. package/src/state.ts +18 -0
package/src/git.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
2
4
  import { promisify } from "node:util";
3
5
 
4
6
  const run = promisify(execFile);
@@ -19,15 +21,24 @@ export type GitResult =
19
21
  | { ok: true; metadata: GitMetadata }
20
22
  | { ok: false; reason: GitFailure };
21
23
 
22
- async function git(cwd: string, args: string[]): Promise<string | undefined> {
24
+ async function gitOutput(cwd: string, args: string[], env?: NodeJS.ProcessEnv, timeout = GIT_TIMEOUT_MS): Promise<string> {
25
+ const { stdout } = await run("git", args, {
26
+ cwd,
27
+ env,
28
+ timeout,
29
+ maxBuffer: 4 * 1024 * 1024,
30
+ windowsHide: true,
31
+ });
32
+ return stdout;
33
+ }
34
+
35
+ async function git(
36
+ cwd: string,
37
+ args: string[],
38
+ env?: NodeJS.ProcessEnv,
39
+ ): Promise<string | undefined> {
23
40
  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();
41
+ const value = (await gitOutput(cwd, args, env)).trim();
31
42
  return value.length > 0 ? value : undefined;
32
43
  } catch {
33
44
  return undefined;
@@ -58,6 +69,14 @@ export function normalizeRemote(url: string): string | undefined {
58
69
  return `${parts[parts.length - 2]}/${parts[parts.length - 1]}`;
59
70
  }
60
71
 
72
+ /**
73
+ * The branch HEAD stands on, or `HEAD` when detached. By its full name, because
74
+ * `--abbrev-ref` says `heads/release` once a tag is called `release` too.
75
+ */
76
+ async function headName(cwd: string): Promise<string | undefined> {
77
+ return (await git(cwd, ["rev-parse", "--symbolic-full-name", "HEAD"]))?.replace(/^refs\/heads\//, "");
78
+ }
79
+
61
80
  export async function collectGitMetadata(cwd: string): Promise<GitResult> {
62
81
  const insideWorkTree = await git(cwd, ["rev-parse", "--is-inside-work-tree"]);
63
82
  if (insideWorkTree !== "true") return { ok: false, reason: "not-a-repository" };
@@ -69,7 +88,7 @@ export async function collectGitMetadata(cwd: string): Promise<GitResult> {
69
88
  const remote = remoteUrl ? normalizeRemote(remoteUrl) : undefined;
70
89
  if (!remote) return { ok: false, reason: "no-remote" };
71
90
 
72
- const branch = (await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])) ?? "HEAD";
91
+ const branch = (await headName(cwd)) ?? "HEAD";
73
92
  const log = await git(cwd, ["log", "--format=%H", "-n", String(RECENT_SHA_COUNT)]);
74
93
  const recentShas = log ? log.split("\n").map((line) => line.trim()).filter(Boolean) : [headSha];
75
94
 
@@ -84,3 +103,150 @@ export async function collectGitMetadata(cwd: string): Promise<GitResult> {
84
103
  export async function headSha(cwd: string): Promise<string | undefined> {
85
104
  return git(cwd, ["rev-parse", "HEAD"]);
86
105
  }
106
+
107
+ /**
108
+ * The branch a commit made now lands on. A rebase runs detached and fires the
109
+ * post-commit hook for every pick, so there it is the branch being rebased,
110
+ * which git keeps beside the rebase's own state.
111
+ */
112
+ export async function currentBranch(cwd: string): Promise<string | undefined> {
113
+ const branch = await headName(cwd);
114
+ if (branch !== "HEAD") return branch;
115
+ const state = await git(cwd, ["rev-parse", "--git-path", "rebase-merge/head-name"]);
116
+ try {
117
+ const name = (await readFile(resolve(cwd, state ?? ""), "utf8")).trim();
118
+ return name.startsWith("refs/heads/") ? name.slice("refs/heads/".length) : branch;
119
+ } catch {
120
+ return branch;
121
+ }
122
+ }
123
+
124
+ export async function branchExists(cwd: string, name: string): Promise<boolean> {
125
+ return (await git(cwd, ["rev-parse", "--verify", "-q", `refs/heads/${name}`])) !== undefined;
126
+ }
127
+
128
+ /** `git -c` by the environment, as `-c` ends a key at its first `=` and a merge driver's name may hold one. */
129
+ function withConfig(keys: string[], value: string): NodeJS.ProcessEnv {
130
+ const before = Number(process.env.GIT_CONFIG_COUNT ?? 0);
131
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_CONFIG_COUNT: String(before + keys.length) };
132
+ keys.forEach((key, index) => {
133
+ env[`GIT_CONFIG_KEY_${before + index}`] = key;
134
+ env[`GIT_CONFIG_VALUE_${before + index}`] = value;
135
+ });
136
+ return env;
137
+ }
138
+
139
+ /**
140
+ * The files HEAD changed, from the top of the repository wherever `cwd` is. For a
141
+ * merge those are the ones its author settled, whichever side they took, and none
142
+ * of what it brings in clean. A git older than 2.35 refuses the flag, and there a
143
+ * merge lists only what differs from both sides. The flag merges again, and a merge
144
+ * driver of the repository's may take any time and do anything besides, in a hook
145
+ * someone is waiting on, so each one stands in as `false`: a conflict that left its
146
+ * side as it was, which tells whether what was settled differs from it just as well.
147
+ */
148
+ export async function filesInHead(cwd: string): Promise<string[]> {
149
+ const show = ["show", "--root", "-z", "--format=", "--name-only", "--no-renames"];
150
+ const drivers = (await git(cwd, ["config", "--name-only", "--get-regexp", "^merge\\..*\\.driver$"]))?.split("\n") ?? [];
151
+ const files = (await git(cwd, [...show, "--remerge-diff", "HEAD", "--"], withConfig(drivers, "false"))) ?? (await git(cwd, [...show, "HEAD", "--"]));
152
+ return files ? files.split("\0").filter(Boolean) : [];
153
+ }
154
+
155
+ /**
156
+ * What the given commits left in each file they changed, by blob. A merge has none,
157
+ * as what it brings in is the other side's, and a commit gone from the repository
158
+ * is passed over.
159
+ */
160
+ export async function blobsOf(cwd: string, shas: string[]): Promise<Map<string, Set<string>>> {
161
+ const raw = await git(cwd, [
162
+ "log", "--root", "--no-walk", "--ignore-missing", "-z", "--format=", "--raw", "--no-abbrev", "--no-renames", ...shas, "--",
163
+ ]);
164
+ const fields = raw?.split("\0").filter(Boolean) ?? [];
165
+ const blobs = new Map<string, Set<string>>();
166
+ // `:100644 100644 <old> <new> M`, then the path.
167
+ for (let index = 0; index + 1 < fields.length; index += 2) {
168
+ const path = fields[index + 1]!;
169
+ blobs.set(path, (blobs.get(path) ?? new Set()).add(fields[index]!.split(" ")[3]!));
170
+ }
171
+ return blobs;
172
+ }
173
+
174
+ /**
175
+ * The lines the given commits add, in any file, or undefined when git could not say
176
+ * by `timeoutMs`. As in `blobsOf`, a merge adds none and a commit gone from the repository
177
+ * is passed over. What a hook someone waits on reads is the repository's text, so no
178
+ * textconv or external diff gets to run, and a partial clone goes to the network for
179
+ * none of it. A git older than 2.45 knows no such setting and may start that fetch,
180
+ * which outlives the timeout.
181
+ */
182
+ export async function addedLines(cwd: string, shas: string[], timeoutMs: number): Promise<string[] | undefined> {
183
+ let diff: string;
184
+ try {
185
+ diff = await gitOutput(cwd, [
186
+ "log", "--root", "--no-walk", "--ignore-missing", "--format=", "-p", "-U0", "--no-renames", "--no-color", "--no-ext-diff", "--no-textconv", ...shas, "--",
187
+ ], { ...process.env, GIT_NO_LAZY_FETCH: "1" }, timeoutMs);
188
+ } catch {
189
+ return undefined;
190
+ }
191
+ const lines: string[] = [];
192
+ // Past a file's `@@` every line is the diff's own, so `+++ b/path` above it is no line added.
193
+ let inHunk = false;
194
+ for (const line of diff.split("\n")) {
195
+ if (line.startsWith("diff --git ")) inHunk = false;
196
+ else if (line.startsWith("@@")) inHunk = true;
197
+ else if (inHunk && line.startsWith("+")) lines.push(line.slice(1));
198
+ }
199
+ return lines;
200
+ }
201
+
202
+ /**
203
+ * The commit HEAD replaced, in git's own record of it: the reflog's entry before an
204
+ * amend, or the pick a rebase stands on. Nothing an amend or a pick changed need look
205
+ * like what it replaced.
206
+ */
207
+ export async function commitHeadReplaced(cwd: string): Promise<string | undefined> {
208
+ const [last, before] = (await git(cwd, ["reflog", "-2", "--no-show-signature", "--format=%H %gs", "HEAD"]))?.split("\n") ?? [];
209
+ if (last && /^\S+ commit \(amend\): /.test(last)) return before?.split(" ")[0];
210
+ const done = await git(cwd, ["rev-parse", "--git-path", "rebase-merge/done"]);
211
+ try {
212
+ const pick = (await readFile(resolve(cwd, done ?? ""), "utf8")).trim().split("\n").at(-1)?.split(/\s+/)[1];
213
+ return pick && (await git(cwd, ["rev-parse", "--verify", "-q", `${pick}^{commit}`]));
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ }
218
+
219
+ /** The files a merge at HEAD changed on the branch it stands on. No merge, no files. */
220
+ export async function filesMergedIntoHead(cwd: string): Promise<string[]> {
221
+ if (!(await git(cwd, ["rev-parse", "-q", "--verify", "HEAD^2"]))) return [];
222
+ const files = await git(cwd, ["diff", "-z", "--name-only", "--no-renames", "HEAD^1", "HEAD", "--"]);
223
+ return files ? files.split("\0").filter(Boolean) : [];
224
+ }
225
+
226
+ /**
227
+ * For a question about a directory, which may not be the one a hook runs in: a
228
+ * post-commit hook in a linked worktree inherits `GIT_DIR`, and git then takes
229
+ * any directory it stands in for the top of the tree.
230
+ */
231
+ function withoutHookEnv(): NodeJS.ProcessEnv {
232
+ return { ...process.env, GIT_DIR: undefined, GIT_WORK_TREE: undefined };
233
+ }
234
+
235
+ /** The top of the work tree a directory belongs to, however that directory was reached. */
236
+ export async function workTreeTop(cwd: string): Promise<string | undefined> {
237
+ return git(cwd, ["rev-parse", "--show-toplevel"], withoutHookEnv());
238
+ }
239
+
240
+ /**
241
+ * The roots a session's transcript is masked by: the top of its repository, the
242
+ * form GitHub and every other session use, whichever subdirectory it started in.
243
+ * Counted up from `cwd` rather than asked for outright, because the toplevel git
244
+ * reports has its symlinks resolved and the transcript's paths may not.
245
+ */
246
+ export async function maskRootsFor(
247
+ cwd: string | undefined,
248
+ ): Promise<{ cwd?: string; base?: string }> {
249
+ if (!cwd) return {};
250
+ const up = await git(cwd, ["rev-parse", "--show-cdup"], withoutHookEnv());
251
+ return up ? { cwd: resolve(cwd, up), base: cwd } : { cwd };
252
+ }
package/src/githook.ts CHANGED
@@ -1,13 +1,21 @@
1
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";
2
+ import { chmod, lstat, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { promisify } from "node:util";
5
+ import { workTreeTop } from "./git.js";
6
+ import { NPX_ISY, NPX_ISY_CACHED } from "./hook.js";
7
+ import { logLine } from "./log.js";
5
8
 
6
9
  const run = promisify(execFile);
7
10
 
8
11
  const GIT_TIMEOUT_MS = 5000;
9
12
  const SHEBANG = "#!/bin/sh";
10
- const BEGIN = "# isy:begin — managed by isy, do not edit inside this block";
13
+ /**
14
+ * A hook is read and written as latin1, one character to a byte, so that what a
15
+ * user's script holds comes back out as it went in, valid UTF-8 or not. So the
16
+ * one character here that is not ASCII is spelled as its bytes.
17
+ */
18
+ const BEGIN = Buffer.from("# isy:begin — managed by isy, do not edit inside this block").toString("latin1");
11
19
  const END = "# isy:end";
12
20
 
13
21
  /**
@@ -15,7 +23,7 @@ const END = "# isy:end";
15
23
  * already happened. It is about the user's own script: a hook running under
16
24
  * `set -e` must not abort at our line.
17
25
  */
18
- export const COMMIT_COMMAND = "npx @nightloom/isy commit --hook || true";
26
+ export const COMMIT_COMMAND = `${NPX_ISY_CACHED} commit --hook || true`;
19
27
 
20
28
  /**
21
29
  * The push is the moment the analysis is actually waiting for: a pull request
@@ -33,7 +41,7 @@ export const COMMIT_COMMAND = "npx @nightloom/isy commit --hook || true";
33
41
  * someone else's pre-push it would hand git a 0 for a push their own hook had
34
42
  * just rejected.
35
43
  */
36
- export const PUSH_COMMAND = "npx @nightloom/isy upload --silent --all >/dev/null 2>&1 </dev/null &";
44
+ export const PUSH_COMMAND = `${NPX_ISY} upload --silent --all >/dev/null 2>&1 </dev/null &`;
37
45
 
38
46
  /**
39
47
  * The repository-side hooks, both written into the same managed block format.
@@ -50,12 +58,35 @@ export type GitHookOutcome =
50
58
  | "already-present"
51
59
  | "removed"
52
60
  | "absent"
53
- | "not-a-repository";
61
+ | "not-a-repository"
62
+ | "not-shell";
54
63
 
55
64
  function block(command: string): string {
56
65
  return `${BEGIN}\n${command}\n${END}`;
57
66
  }
58
67
 
68
+ /** The program a shebang line runs, looking through `env`. */
69
+ function interpreter(contents: string): string | undefined {
70
+ if (!contents.startsWith("#!")) return undefined;
71
+ const [program = "", ...rest] = contents.slice(2).split("\n", 1)[0]!.trim().split(/\s+/);
72
+ const name = basename(program);
73
+ if (name !== "env") return name;
74
+ return basename(rest.find((word) => !word.startsWith("-") && !word.includes("=")) ?? "");
75
+ }
76
+
77
+ /**
78
+ * Whether the block can stand in this hook. It is shell, and in a python, node or
79
+ * perl script it is a syntax error that takes the user's hook down with it: for
80
+ * pre-push, that rejects the push. Prepended to a compiled program it destroys it.
81
+ * A file with no shebang is shell: git hands it to sh. An interpreter not known
82
+ * here is left alone, which costs a hook and breaks nothing.
83
+ */
84
+ function takesBlock(contents: string): boolean {
85
+ if (contents.includes("\0")) return false;
86
+ const program = interpreter(contents);
87
+ return program === undefined || /^(?:a|ba|da|k|mk|pdk|y|z)?sh\d*$/.test(program);
88
+ }
89
+
59
90
  /**
60
91
  * Where a new block goes: straight after the shebang, ahead of whatever the
61
92
  * user's own script does.
@@ -113,12 +144,26 @@ export function prePushPath(cwd: string): Promise<string | undefined> {
113
144
 
114
145
  async function readHook(path: string): Promise<string | undefined> {
115
146
  try {
116
- return await readFile(path, "utf8");
147
+ return await readFile(path, "latin1");
117
148
  } catch {
118
149
  return undefined;
119
150
  }
120
151
  }
121
152
 
153
+ /**
154
+ * Swapped in whole rather than written over, with the mode it has now. A hook is
155
+ * rewritten by the very commands it runs, and a shell reads its script as it
156
+ * goes: written in place, bash would carry on from its old offset, in the middle
157
+ * of a line of the new text. A hook linked in from elsewhere stays linked.
158
+ */
159
+ async function replaceHook(path: string, contents: string): Promise<void> {
160
+ const target = await realpath(path);
161
+ const temporary = join(dirname(target), `.${basename(target)}.isy-${process.pid}`);
162
+ await writeFile(temporary, contents, "latin1");
163
+ await chmod(temporary, (await stat(target)).mode & 0o7777);
164
+ await rename(temporary, target);
165
+ }
166
+
122
167
  /** The managed block as it currently stands in this file, if it is there at all. */
123
168
  function existingBlock(contents: string): string | undefined {
124
169
  const start = contents.indexOf(BEGIN);
@@ -127,11 +172,20 @@ function existingBlock(contents: string): string | undefined {
127
172
  return stop < 0 ? undefined : contents.slice(start, stop + END.length);
128
173
  }
129
174
 
175
+ /** The file without its block and the newline `insert` gave it: what the user had before. */
176
+ function withoutBlock(contents: string, existing: string): string {
177
+ const start = contents.indexOf(existing);
178
+ const stop = start + existing.length;
179
+ return contents.slice(0, start) + contents.slice(contents[stop] === "\n" ? stop + 1 : stop);
180
+ }
181
+
130
182
  async function oneInstalled(cwd: string, hook: { name: string; command: string }): Promise<boolean> {
131
183
  const path = await hookPath(cwd, hook.name);
132
184
  if (!path) return false;
133
185
  const contents = await readHook(path);
134
- return contents !== undefined && existingBlock(contents) === block(hook.command);
186
+ if (contents === undefined) return false;
187
+ // Nothing is missing from a hook that takes no block, and `isy init` cannot add it.
188
+ return existingBlock(contents) === (takesBlock(contents) ? block(hook.command) : undefined);
135
189
  }
136
190
 
137
191
  /** True only with every hook in place: half-wired is not installed. */
@@ -140,6 +194,21 @@ export async function gitHookInstalled(cwd: string): Promise<boolean> {
140
194
  return true;
141
195
  }
142
196
 
197
+ /** The hooks that take no block, and what each would have to run: wiring them is the user's to do. */
198
+ export async function hooksLeftToTheUser(
199
+ cwd: string,
200
+ ): Promise<{ name: string; command: string; language: string }[]> {
201
+ const left: { name: string; command: string; language: string }[] = [];
202
+ for (const hook of GIT_HOOKS) {
203
+ const path = await hookPath(cwd, hook.name);
204
+ const contents = path === undefined ? undefined : await readHook(path);
205
+ if (contents !== undefined && !takesBlock(contents)) {
206
+ left.push({ ...hook, language: interpreter(contents) ?? "compiled" });
207
+ }
208
+ }
209
+ return left;
210
+ }
211
+
143
212
  async function installOne(
144
213
  cwd: string,
145
214
  hook: { name: string; command: string },
@@ -151,12 +220,21 @@ async function installOne(
151
220
  const desired = block(hook.command);
152
221
 
153
222
  if (contents === undefined) {
154
- await writeFile(path, `${SHEBANG}\n${desired}\n`, "utf8");
223
+ await writeFile(path, `${SHEBANG}\n${desired}\n`, "latin1");
155
224
  await chmod(path, 0o755);
156
225
  return "installed";
157
226
  }
158
227
 
159
228
  const existing = existingBlock(contents);
229
+ if (!takesBlock(contents)) {
230
+ // An older isy put it there, and every run of this hook has failed since.
231
+ if (existing !== undefined) {
232
+ await replaceHook(path, withoutBlock(contents, existing));
233
+ logLine(`git hooks: took the block back out of ${path}: not a shell script`);
234
+ }
235
+ return "not-shell";
236
+ }
237
+
160
238
  if (existing === desired) {
161
239
  // A hook git will not execute is not installed, whatever the file says.
162
240
  await chmod(path, 0o755);
@@ -165,7 +243,7 @@ async function installOne(
165
243
 
166
244
  const next = existing === undefined ? insert(contents, desired) : contents.replace(existing, desired);
167
245
 
168
- await writeFile(path, next, "utf8");
246
+ await replaceHook(path, next);
169
247
  await chmod(path, 0o755);
170
248
  return "installed";
171
249
  }
@@ -207,21 +285,75 @@ async function hookLocation(cwd: string): Promise<{ hooks: string; gitDir: strin
207
285
  }
208
286
  }
209
287
 
288
+ /**
289
+ * Whether core.hooksPath points out of the git directory — `.husky`, a team's
290
+ * `githooks/`. Such a directory is usually committed: a write there nobody asked
291
+ * for reaches every teammate, and until then leaves the tree dirty, which is
292
+ * enough for `git rebase` to refuse. Those are left to `isy init`, run on purpose.
293
+ */
294
+ function isShared(location: { hooks: string; gitDir: string }): boolean {
295
+ return !holds(location.gitDir, location.hooks);
296
+ }
297
+
298
+ function holds(directory: string, path: string): boolean {
299
+ const inside = relative(directory, path);
300
+ return !inside.startsWith("..") && !isAbsolute(inside);
301
+ }
302
+
303
+ /**
304
+ * Whether a hook is a link to a file in a work tree, which for the same reason as
305
+ * `isShared` waits for `isy init` to have what it holds rewritten. Asked of the file,
306
+ * since the tree it sits in need not be the one this runs from: all of a repository's
307
+ * worktrees share its hooks.
308
+ */
309
+ async function linkedIntoTree(path: string, gitDir: string): Promise<boolean> {
310
+ try {
311
+ if (!(await lstat(path)).isSymbolicLink()) return false;
312
+ const [target, git] = await Promise.all([realpath(path), realpath(gitDir)]);
313
+ return !holds(git, target) && (await workTreeTop(dirname(target))) !== undefined;
314
+ } catch {
315
+ return false;
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Bring the blocks an older isy wrote up to date where they stand, adding none:
321
+ * what every run from a hook does first, so that an upgrade reaches a repository
322
+ * the next time anything happens in it, with no `isy init` to go through. A block
323
+ * that is only old waits in a shared file. One that breaks its hook comes out
324
+ * wherever it is: the file goes back to what the user had, and a push stops failing.
325
+ */
326
+ export async function repairGitHook(cwd: string): Promise<void> {
327
+ const location = await hookLocation(cwd);
328
+ if (!location) return;
329
+
330
+ for (const hook of GIT_HOOKS) {
331
+ const path = resolve(location.hooks, hook.name);
332
+ const contents = await readHook(path);
333
+ if (contents === undefined) continue;
334
+ const existing = existingBlock(contents);
335
+ if (existing === undefined) continue;
336
+ const old =
337
+ existing !== block(hook.command) && !isShared(location) && !(await linkedIntoTree(path, location.gitDir));
338
+ if (old || !takesBlock(contents)) await installOne(cwd, hook);
339
+ }
340
+ }
341
+
210
342
  /**
211
343
  * What the SessionEnd hook runs in every repository a session happened in, so
212
344
  * `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.
345
+ * only where nobody else will see it (`isShared`).
217
346
  */
218
347
  export async function autoInstallGitHook(cwd: string): Promise<GitHookOutcome | "shared-hooks"> {
219
348
  const location = await hookLocation(cwd);
220
349
  if (!location) return "not-a-repository";
221
350
  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";
351
+ if (isShared(location)) return "shared-hooks";
352
+ for (const hook of GIT_HOOKS) {
353
+ const path = resolve(location.hooks, hook.name);
354
+ if (existingBlock((await readHook(path)) ?? "") === undefined) continue;
355
+ if (await linkedIntoTree(path, location.gitDir)) return "shared-hooks";
356
+ }
225
357
 
226
358
  // A repository created without templates has no hooks directory at all.
227
359
  await mkdir(location.hooks, { recursive: true });
@@ -238,14 +370,14 @@ async function removeOne(cwd: string, name: string): Promise<GitHookOutcome> {
238
370
  const existing = existingBlock(contents);
239
371
  if (existing === undefined) return "absent";
240
372
 
241
- const stripped = contents.replace(existing, "").replace(/\n{3,}/g, "\n\n");
373
+ const stripped = withoutBlock(contents, existing);
242
374
 
243
375
  if (stripped.replace(SHEBANG, "").trim().length === 0) {
244
376
  await rm(path, { force: true });
245
377
  return "removed";
246
378
  }
247
379
 
248
- await writeFile(path, stripped.endsWith("\n") ? stripped : `${stripped}\n`, "utf8");
380
+ await replaceHook(path, stripped);
249
381
  return "removed";
250
382
  }
251
383
 
package/src/hook.ts CHANGED
@@ -3,10 +3,32 @@ import { basename, dirname, join } from "node:path";
3
3
  import type { AgentHook } from "./agents/types.js";
4
4
  import { claudeConfigDir, claudeSettingsPath } from "./paths.js";
5
5
 
6
+ /**
7
+ * How every hook line starts. npx asks the registry for the newest version on
8
+ * every run, before it starts anything, and left to its defaults that held a
9
+ * commit for 70 seconds offline and 16 minutes on a network that never answers.
10
+ * With these it gives up after two seconds and runs what it has cached. Updates
11
+ * still arrive: the timeout is on an answer and on silence, not on a download.
12
+ */
13
+ export const NPX_ISY = "npx --fetch-retries=0 --fetch-timeout=2000 @nightloom/isy";
14
+
15
+ /**
16
+ * How a line someone is waiting on starts: a commit, a session starting. npm's
17
+ * timeout does not cover connecting, so on a network that drops packets on the way
18
+ * to the registry the line above still holds for over two minutes. This one asks
19
+ * nothing while there is a cached version to run. The lines that run in the
20
+ * background ask, and what they learn is in the cache this reads, so an update
21
+ * reaches it one background run later.
22
+ *
23
+ * ponytail: with nothing cached the first such line still asks, and holds that long
24
+ * once on such a network. A real limit there takes a wrapper around npx.
25
+ */
26
+ export const NPX_ISY_CACHED = "npx --prefer-offline --fetch-retries=0 --fetch-timeout=2000 @nightloom/isy";
27
+
6
28
  export const HOOK_EVENT = "SessionEnd";
7
- export const HOOK_COMMAND = "exec 3<&0; nohup npx @nightloom/isy upload --hook <&3 >/dev/null 2>&1 &";
29
+ export const HOOK_COMMAND = `exec 3<&0; nohup ${NPX_ISY} upload --hook <&3 >/dev/null 2>&1 &`;
8
30
  export const START_HOOK_EVENT = "SessionStart";
9
- export const START_HOOK_COMMAND = "npx @nightloom/isy check --hook";
31
+ export const START_HOOK_COMMAND = `${NPX_ISY_CACHED} check --hook`;
10
32
 
11
33
  /**
12
34
  * The scope is spelled out, and npx stays. npx resolves a bare name against the
@@ -40,9 +62,14 @@ export const ISY_HOOKS: (AgentHook & { superseded: string[] })[] = [
40
62
  "npx isy upload --silent",
41
63
  "npx isy upload --hook",
42
64
  "npx @nightloom/isy upload --hook",
65
+ "exec 3<&0; nohup npx @nightloom/isy upload --hook <&3 >/dev/null 2>&1 &",
43
66
  ],
44
67
  },
45
- { event: START_HOOK_EVENT, command: START_HOOK_COMMAND, superseded: ["npx isy check --hook"] },
68
+ {
69
+ event: START_HOOK_EVENT,
70
+ command: START_HOOK_COMMAND,
71
+ superseded: ["npx isy check --hook", "npx @nightloom/isy check --hook", `${NPX_ISY} check --hook`],
72
+ },
46
73
  ];
47
74
 
48
75
  /**
package/src/index.ts CHANGED
@@ -13,7 +13,8 @@ import { runNotes } from "./commands/notes.js";
13
13
  import { runSettings } from "./commands/settings.js";
14
14
  import { runStatus } from "./commands/status.js";
15
15
  import { formatUploadAlert, formatUploadReport, runUpload } from "./commands/upload.js";
16
- import { errorMessage, logError } from "./log.js";
16
+ import { repairGitHook } from "./githook.js";
17
+ import { errorMessage, logError, logLine } from "./log.js";
17
18
  import { packageVersion } from "./paths.js";
18
19
  import { spawnIsy } from "./spawn.js";
19
20
 
@@ -134,8 +135,8 @@ async function run(
134
135
  if (values.hook) {
135
136
  try {
136
137
  await runCommitCommand({ json: values.json, hook: true }, process.cwd());
137
- } catch {
138
- return;
138
+ } catch (error) {
139
+ logError(`commit: ${errorMessage(error)}`);
139
140
  }
140
141
  return;
141
142
  }
@@ -152,8 +153,8 @@ async function run(
152
153
  const alert = formatUploadAlert(report);
153
154
  // Each CLI displays a line its own way; the wording is the same.
154
155
  if (alert) await agentById(report.agent).deliver(alert, "SessionEnd");
155
- } catch {
156
- return;
156
+ } catch (error) {
157
+ logError(`upload: ${errorMessage(error)}`);
157
158
  }
158
159
  return;
159
160
  }
@@ -230,6 +231,15 @@ if (!COMMANDS.has(command)) {
230
231
  fail(`unknown command '${command}'. ${USAGE}`, silent);
231
232
  }
232
233
 
234
+ // Whatever a hook runs, git's or a CLI's, says `--hook`, or `--all` for pre-push.
235
+ // The next thing to happen in a repository is what brings its older blocks up to
236
+ // date, with no `isy init` to go through.
237
+ if (values.hook || values.all) {
238
+ await repairGitHook(process.cwd()).catch((error: unknown) => {
239
+ logLine(`git hooks: not brought up to date: ${errorMessage(error)}`);
240
+ });
241
+ }
242
+
233
243
  try {
234
244
  await run(command, values, positionals);
235
245
  } catch (error) {
package/src/mask-paths.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * the second segment is the leak; the rest is information a reviewer wants.
9
9
  * So a path is rewritten rather than blanked:
10
10
  *
11
- * inside the working directory → `src/a.ts`
11
+ * inside the repository → `src/a.ts`
12
12
  * elsewhere under a home → `~/.config/gh/hosts.yml`
13
13
  * anywhere else → left alone
14
14
  *
@@ -35,7 +35,7 @@ const MASK_HOST = marker("host");
35
35
  const MASK_PROJECT = marker("project");
36
36
 
37
37
  export interface MaskRoots {
38
- /** Where the session ran. Paths under it become repository-relative. */
38
+ /** The top of the session's repository. Paths under it become repository-relative. */
39
39
  cwd?: string;
40
40
  /** The developer's home. Paths under it become `~/…`. */
41
41
  home?: string;
@@ -403,12 +403,13 @@ export const PATH_KEYS: ReadonlySet<string> = new Set([
403
403
  * other path in that transcript is relative to. One rule, two callers: the
404
404
  * client learns it while redacting, the server while reading a transcript back
405
405
  * off disk — and they must agree, or a comment and a report page would spell
406
- * the same file two ways.
406
+ * the same file two ways. One that is not absolute was masked before it was
407
+ * stored, and taken for a root it would eat the same word out of other paths.
407
408
  */
408
409
  export function rootOf(record: unknown): string | undefined {
409
410
  if (typeof record !== "object" || record === null) return undefined;
410
411
  const cwd = (record as { cwd?: unknown }).cwd;
411
- return typeof cwd === "string" && cwd.length > 0 ? cwd : undefined;
412
+ return typeof cwd === "string" && looksAbsolute(cwd) ? cwd : undefined;
412
413
  }
413
414
 
414
415
  /**