@nightloom/isy 1.0.0 → 1.0.2

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 (131) hide show
  1. package/README.md +1 -1
  2. package/dist/agents/claude.js +18 -7
  3. package/dist/agents/claude.js.map +1 -1
  4. package/dist/agents/codex-records.js +35 -12
  5. package/dist/agents/codex-records.js.map +1 -1
  6. package/dist/agents/index.d.ts +16 -5
  7. package/dist/agents/index.js +21 -6
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/agents/kimi-cli-wire.d.ts +17 -0
  10. package/dist/agents/kimi-cli-wire.js +312 -0
  11. package/dist/agents/kimi-cli-wire.js.map +1 -0
  12. package/dist/agents/kimi-config.d.ts +29 -0
  13. package/dist/agents/kimi-config.js +193 -0
  14. package/dist/agents/kimi-config.js.map +1 -0
  15. package/dist/agents/kimi-records.d.ts +0 -6
  16. package/dist/agents/kimi-records.js +51 -31
  17. package/dist/agents/kimi-records.js.map +1 -1
  18. package/dist/agents/kimi-tools.d.ts +30 -0
  19. package/dist/agents/kimi-tools.js +100 -0
  20. package/dist/agents/kimi-tools.js.map +1 -0
  21. package/dist/agents/kimi-wire.d.ts +8 -0
  22. package/dist/agents/kimi-wire.js +245 -80
  23. package/dist/agents/kimi-wire.js.map +1 -1
  24. package/dist/agents/kimi.d.ts +13 -2
  25. package/dist/agents/kimi.js +633 -114
  26. package/dist/agents/kimi.js.map +1 -1
  27. package/dist/agents/timeline.d.ts +36 -0
  28. package/dist/agents/timeline.js +61 -0
  29. package/dist/agents/timeline.js.map +1 -0
  30. package/dist/agents/types.d.ts +12 -0
  31. package/dist/commands/analyze.d.ts +2 -0
  32. package/dist/commands/analyze.js +63 -6
  33. package/dist/commands/analyze.js.map +1 -1
  34. package/dist/commands/check.js +11 -0
  35. package/dist/commands/check.js.map +1 -1
  36. package/dist/commands/init.js +17 -2
  37. package/dist/commands/init.js.map +1 -1
  38. package/dist/commands/upload.js +8 -4
  39. package/dist/commands/upload.js.map +1 -1
  40. package/dist/detectors.js +40 -5
  41. package/dist/detectors.js.map +1 -1
  42. package/dist/hook.d.ts +12 -5
  43. package/dist/hook.js +73 -17
  44. package/dist/hook.js.map +1 -1
  45. package/dist/lines.d.ts +8 -0
  46. package/dist/lines.js +32 -0
  47. package/dist/lines.js.map +1 -0
  48. package/dist/parser.d.ts +41 -0
  49. package/dist/parser.js +328 -32
  50. package/dist/parser.js.map +1 -1
  51. package/dist/paths.d.ts +4 -0
  52. package/dist/paths.js +39 -39
  53. package/dist/paths.js.map +1 -1
  54. package/dist/redact.d.ts +10 -0
  55. package/dist/redact.js +49 -8
  56. package/dist/redact.js.map +1 -1
  57. package/dist/stage0.d.ts +7 -1
  58. package/dist/stage0.js +10 -3
  59. package/dist/stage0.js.map +1 -1
  60. package/dist/state.d.ts +6 -3
  61. package/dist/state.js +21 -5
  62. package/dist/state.js.map +1 -1
  63. package/dist/subagents.d.ts +49 -0
  64. package/dist/subagents.js +237 -0
  65. package/dist/subagents.js.map +1 -0
  66. package/dist/test/analyze.test.js +15 -11
  67. package/dist/test/analyze.test.js.map +1 -1
  68. package/dist/test/check.test.js +25 -3
  69. package/dist/test/check.test.js.map +1 -1
  70. package/dist/test/codex.test.js +43 -0
  71. package/dist/test/codex.test.js.map +1 -1
  72. package/dist/test/commit.test.js +9 -1
  73. package/dist/test/commit.test.js.map +1 -1
  74. package/dist/test/hook.test.js +66 -2
  75. package/dist/test/hook.test.js.map +1 -1
  76. package/dist/test/init.test.d.ts +1 -0
  77. package/dist/test/init.test.js +94 -0
  78. package/dist/test/init.test.js.map +1 -0
  79. package/dist/test/kimi-cli.test.d.ts +1 -0
  80. package/dist/test/kimi-cli.test.js +231 -0
  81. package/dist/test/kimi-cli.test.js.map +1 -0
  82. package/dist/test/kimi-code.test.d.ts +1 -0
  83. package/dist/test/kimi-code.test.js +302 -0
  84. package/dist/test/kimi-code.test.js.map +1 -0
  85. package/dist/test/kimi-config.test.d.ts +1 -0
  86. package/dist/test/kimi-config.test.js +224 -0
  87. package/dist/test/kimi-config.test.js.map +1 -0
  88. package/dist/test/kimi-hook.test.d.ts +1 -0
  89. package/dist/test/kimi-hook.test.js +163 -0
  90. package/dist/test/kimi-hook.test.js.map +1 -0
  91. package/dist/test/kimi-listing.test.d.ts +1 -0
  92. package/dist/test/kimi-listing.test.js +193 -0
  93. package/dist/test/kimi-listing.test.js.map +1 -0
  94. package/dist/test/kimi.test.js +52 -7
  95. package/dist/test/kimi.test.js.map +1 -1
  96. package/dist/test/parser.test.js +192 -5
  97. package/dist/test/parser.test.js.map +1 -1
  98. package/dist/test/redact.test.js +71 -7
  99. package/dist/test/redact.test.js.map +1 -1
  100. package/dist/test/stage0.test.js +74 -4
  101. package/dist/test/stage0.test.js.map +1 -1
  102. package/dist/test/subagents.test.d.ts +1 -0
  103. package/dist/test/subagents.test.js +272 -0
  104. package/dist/test/subagents.test.js.map +1 -0
  105. package/dist/types.d.ts +16 -0
  106. package/package.json +3 -2
  107. package/src/agents/claude.ts +17 -7
  108. package/src/agents/codex-records.ts +33 -12
  109. package/src/agents/index.ts +21 -6
  110. package/src/agents/kimi-cli-wire.ts +350 -0
  111. package/src/agents/kimi-config.ts +210 -0
  112. package/src/agents/kimi-records.ts +52 -29
  113. package/src/agents/kimi-tools.ts +128 -0
  114. package/src/agents/kimi-wire.ts +270 -82
  115. package/src/agents/kimi.ts +653 -113
  116. package/src/agents/timeline.ts +68 -0
  117. package/src/agents/types.ts +12 -0
  118. package/src/commands/analyze.ts +62 -6
  119. package/src/commands/check.ts +11 -0
  120. package/src/commands/init.ts +18 -2
  121. package/src/commands/upload.ts +8 -4
  122. package/src/detectors.ts +39 -5
  123. package/src/hook.ts +81 -24
  124. package/src/lines.ts +31 -0
  125. package/src/parser.ts +343 -31
  126. package/src/paths.ts +36 -33
  127. package/src/redact.ts +53 -10
  128. package/src/stage0.ts +9 -2
  129. package/src/state.ts +24 -5
  130. package/src/subagents.ts +283 -0
  131. package/src/types.ts +16 -0
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Subagent logs merged into their session's by time — the rule `subagents.ts`
3
+ * applies to Claude Code's files as they stream, here for the Kimi readers,
4
+ * which hold every log in memory already.
5
+ *
6
+ * A subagent's records go in when they happened, never ahead of the event that
7
+ * started it: the detectors read order as time, and a subagent does not always
8
+ * run inside its call. One started in the background works alongside the
9
+ * session, and one resumed later goes on in the same log.
10
+ */
11
+
12
+ /** An item and the moment it stands for, in epoch milliseconds. */
13
+ export interface Timed<T> {
14
+ at: number;
15
+ item: T;
16
+ }
17
+
18
+ /**
19
+ * Each item's moment: its own, or — for one recorded without a time — the last
20
+ * moment before it in the same log, and `from` for those ahead of any.
21
+ */
22
+ export function stamped<T>(items: Iterable<T>, timeOf: (item: T) => number | undefined, from: number): Timed<T>[] {
23
+ const out: Timed<T>[] = [];
24
+ let at = from;
25
+ for (const item of items) {
26
+ at = timeOf(item) ?? at;
27
+ out.push({ at, item });
28
+ }
29
+ return out;
30
+ }
31
+
32
+ /**
33
+ * The bound a session's event puts on the subagents it started. A session that
34
+ * has named no moment yet bounds nothing: a log without times puts a subagent
35
+ * right after the event that started it, whole.
36
+ */
37
+ export function boundOf(at: number): number {
38
+ return at === -Infinity ? Infinity : at;
39
+ }
40
+
41
+ /** The logs a session has started, each waiting at its next item. */
42
+ export class Timelines<T> {
43
+ private readonly heads: { items: Timed<T>[]; next: number }[] = [];
44
+
45
+ add(items: Timed<T>[]): void {
46
+ if (items.length > 0) this.heads.push({ items, next: 0 });
47
+ }
48
+
49
+ /**
50
+ * Every item due by `at`, earliest first — on a tie, the log that started
51
+ * first. A log added while this runs is read too.
52
+ */
53
+ *until(at: number): Generator<Timed<T>> {
54
+ for (;;) {
55
+ let earliest: { items: Timed<T>[]; next: number } | undefined;
56
+ for (const head of this.heads) {
57
+ const next = head.items[head.next]!;
58
+ if (next.at <= at && (earliest === undefined || next.at < earliest.items[earliest.next]!.at)) earliest = head;
59
+ }
60
+ if (earliest === undefined) return;
61
+
62
+ const next = earliest.items[earliest.next]!;
63
+ earliest.next += 1;
64
+ if (earliest.next >= earliest.items.length) this.heads.splice(this.heads.indexOf(earliest), 1);
65
+ yield next;
66
+ }
67
+ }
68
+ }
@@ -20,6 +20,11 @@ export interface HookInput {
20
20
  export interface AgentHook {
21
21
  event: string;
22
22
  command: string;
23
+ /**
24
+ * Seconds the CLI should wait for the hook, written beside the command. A hook
25
+ * with the right command and the wrong timeout is not installed yet.
26
+ */
27
+ timeout?: number;
23
28
  /** Commands an older isy wrote for the same job: replace, never stack. */
24
29
  superseded?: string[];
25
30
  }
@@ -82,6 +87,13 @@ export interface Agent {
82
87
  hooksInstalled(): Promise<string[]>;
83
88
  installHooks(): Promise<"installed" | "already-present">;
84
89
  removeHooks(): Promise<"removed" | "absent">;
90
+ /**
91
+ * Bring isy's own hooks an older isy wrote up to date in place, adding none,
92
+ * with no sign-in — what a SessionStart hook runs, so an upgrade does not
93
+ * wait on `isy init`. Whether anything changed. Absent where rewriting a hook
94
+ * takes the user's say-so: Codex asks again for every hook it has not seen.
95
+ */
96
+ repairHooks?(): Promise<boolean>;
85
97
 
86
98
  /**
87
99
  * Show one line to the user. Each CLI displays text its own way, and the same
@@ -1,13 +1,15 @@
1
1
  import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
2
- import { basename, join } from "node:path";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
3
  import { codexAgent, kimiAgent } from "../agents/index.js";
4
4
  import { isCodexTranscript } from "../agents/codex-records.js";
5
+ import { isKimiCliWire } from "../agents/kimi-cli-wire.js";
5
6
  import { isKimiTranscript } from "../agents/kimi-records.js";
6
7
  import { isKimiWireTranscript } from "../agents/kimi-wire.js";
7
8
  import { readConfig } from "../config.js";
8
9
  import { parseLines } from "../parser.js";
9
- import { firstLine, packageVersion } from "../paths.js";
10
- import { redactTranscriptFile } from "../redact.js";
10
+ import { firstLine, firstLines, packageVersion } from "../paths.js";
11
+ import { redactLineStream } from "../redact.js";
12
+ import { isSubagentTranscript, sessionLines } from "../subagents.js";
11
13
  import { countByCategory, runStage0 } from "../stage0.js";
12
14
  import type { IneligibleReason, Stage0Result } from "../stage0.js";
13
15
  import type { Candidate, SignalCategory } from "../types.js";
@@ -21,6 +23,8 @@ export interface AnalyzedSession {
21
23
  assistantRecords: number;
22
24
  editToolUses: number;
23
25
  thinkingBlocks: number;
26
+ /** Reasoning recorded with its text left out: why `known_gap` can be out of reach. */
27
+ hiddenThinkingBlocks: number;
24
28
  eligible: boolean;
25
29
  reason?: IneligibleReason;
26
30
  knownGapReachable: boolean;
@@ -63,7 +67,52 @@ export async function expandInputs(inputs: readonly string[]): Promise<string[]>
63
67
  files.push(input);
64
68
  }
65
69
 
66
- return [...new Set(files)].sort();
70
+ // One file however it was named: `./a/s.jsonl` beside `a/s.jsonl`, or a
71
+ // directory walked with the platform's separator beside a path typed with `/`.
72
+ const unique = new Map<string, string>();
73
+ for (const file of files) if (!unique.has(resolve(file))) unique.set(resolve(file), file);
74
+ const kept: string[] = [];
75
+ for (const [path, file] of unique) {
76
+ // A subagent is part of its session, which reads it in — Claude's from
77
+ // `subagents/` (`subagents.ts`), Kimi's from its own event log: analysed
78
+ // beside it, it would count twice, once as a session of its own. Asked
79
+ // about without its session, it is all there is to read.
80
+ if (owningSessions(path).some((session) => unique.has(session))) continue;
81
+ // Kimi CLI keeps one session twice: the event log and the model's context.
82
+ // The log is the session; the context beside it would be a second copy.
83
+ if (basename(file) === "context.jsonl" && (await isKimiCliSession(join(dirname(file), "wire.jsonl")))) continue;
84
+ kept.push(file);
85
+ }
86
+ return kept.sort();
87
+ }
88
+
89
+ /**
90
+ * The transcripts a subagent's file belongs to: Claude's
91
+ * `<session>/subagents/…/agent-<id>.jsonl` is `<session>.jsonl`'s, Kimi CLI's
92
+ * `<session>/subagents/<id>/wire.jsonl` is `<session>/wire.jsonl`'s, and Kimi
93
+ * Code's `<session>/agents/<id>/wire.jsonl` is `<session>/agents/main/wire.jsonl`'s.
94
+ */
95
+ function owningSessions(file: string): string[] {
96
+ const agent = dirname(file);
97
+ if (basename(file) === "wire.jsonl" && basename(dirname(agent)) === "agents" && basename(agent) !== "main") {
98
+ return [join(dirname(agent), "main", "wire.jsonl")];
99
+ }
100
+ let subagents = dirname(file);
101
+ while (basename(subagents) !== "subagents") {
102
+ if (dirname(subagents) === subagents) return [];
103
+ subagents = dirname(subagents);
104
+ }
105
+ const session = dirname(subagents);
106
+ if (isSubagentTranscript(file)) return [`${session}.jsonl`];
107
+ return [join(session, "wire.jsonl"), join(session, "context.jsonl")];
108
+ }
109
+
110
+ async function isKimiCliSession(wire: string): Promise<boolean> {
111
+ try {
112
+ return isKimiCliWire(await firstLines(wire, 3));
113
+ } catch {
114
+ return false;
115
+ }
67
116
  }
68
117
 
69
118
  /**
@@ -82,7 +131,8 @@ async function transcriptLines(
82
131
  }
83
132
  if (isCodexTranscript(head)) return codexAgent.redactedLines(file, { extraPatterns });
84
133
 
85
- const { lines } = await redactTranscriptFile(file, { extraPatterns });
134
+ // Claude Code: the session with its subagents read in, as the upload sends it.
135
+ const { lines } = await redactLineStream(sessionLines(file), { extraPatterns });
86
136
  return lines;
87
137
  }
88
138
 
@@ -104,6 +154,7 @@ export async function analyzeFiles(
104
154
  assistantRecords: session.meta.assistantRecords,
105
155
  editToolUses: session.meta.editToolUses,
106
156
  thinkingBlocks: result.thinkingBlocks,
157
+ hiddenThinkingBlocks: session.meta.hiddenThinkingBlocks,
107
158
  eligible: result.eligible,
108
159
  reason: result.reason,
109
160
  knownGapReachable: result.knownGapReachable,
@@ -236,7 +287,12 @@ export function formatReport(report: AnalyzeReport, elapsedMs?: number): string
236
287
  );
237
288
  }
238
289
  if (!session.knownGapReachable) {
239
- lines.push(" note: no thinking blocks, known_gap is unreachable for this session");
290
+ lines.push(
291
+ session.hiddenThinkingBlocks > 0
292
+ ? ` note: ${session.hiddenThinkingBlocks} thinking block(s) recorded without their text, ` +
293
+ "known_gap is unreachable for this session"
294
+ : " note: no thinking blocks, known_gap is unreachable for this session",
295
+ );
240
296
  }
241
297
  lines.push("");
242
298
  }
@@ -211,6 +211,17 @@ export async function runCheck(
211
211
  // A SessionStart hook must never delay or break the session it announces:
212
212
  // no network, and any failure means silence rather than a broken launch.
213
213
  try {
214
+ // Hooks an older isy wrote are rewritten where they stand before they are
215
+ // judged: `isy init` would do the same, but it signs in again first, and
216
+ // on a plan with one key that means revoking the key in use.
217
+ for (const agent of await presentAgents()) {
218
+ try {
219
+ await agent.repairHooks?.();
220
+ } catch {
221
+ // A config that will not parse is reported by the line below, as before.
222
+ }
223
+ }
224
+
214
225
  // Deliberately without `cwd`: the post-commit hook is per repository and
215
226
  // only an accelerator — SessionEnd still uploads without it. Nagging about
216
227
  // it at the start of every session in every repo would be noise, so it is
@@ -117,6 +117,21 @@ export async function runInit(options: { token?: string }, cwd: string): Promise
117
117
  const authUrl = new URL("/auth/github", baseUrl).toString();
118
118
 
119
119
  let token = options.token;
120
+ let verified: Awaited<ReturnType<typeof verifyToken>> | undefined;
121
+
122
+ // A key this machine already holds, and the server still takes, is kept.
123
+ // `init` is also how hooks are refreshed and a CLI installed since is added,
124
+ // and pairing again for that issued a second key — which a plan with one key
125
+ // refuses until the reader revokes the key in use.
126
+ if (!token && config.token) {
127
+ const held = await verifyToken({ baseUrl, token: config.token });
128
+ if (held.ok) {
129
+ token = config.token;
130
+ verified = held;
131
+ console.log(`Using the key already in ${configPath()}. To sign in as someone else, run isy logout first.`);
132
+ }
133
+ }
134
+
120
135
  if (!token) {
121
136
  // Only when the pairing could not be opened at all — a server that predates
122
137
  // it, or one with no dashboard address. A pairing that was opened and then
@@ -140,11 +155,12 @@ export async function runInit(options: { token?: string }, cwd: string): Promise
140
155
  );
141
156
  }
142
157
 
143
- const verified = await verifyToken({ baseUrl, token });
158
+ const kept = verified !== undefined;
159
+ verified ??= await verifyToken({ baseUrl, token });
144
160
  if (!verified.ok) throw new Error(verified.error);
145
161
 
146
162
  await writeConfig({ ...config, token, githubLogin: verified.githubLogin });
147
- console.log(`Token stored in ${configPath()}`);
163
+ if (!kept) console.log(`Token stored in ${configPath()}`);
148
164
 
149
165
  // Hooks go into every CLI actually installed here, and none that is not.
150
166
  const agents = await presentAgents();
@@ -1,4 +1,3 @@
1
- import { stat } from "node:fs/promises";
2
1
  import { detectAgent, presentAgents } from "../agents/index.js";
3
2
  import type { Agent, AgentId, HookInput } from "../agents/index.js";
4
3
  import { DEFAULT_API_BASE_URL, buildTranscriptFields, uploadSession } from "../api.js";
@@ -16,6 +15,7 @@ import { updateNotice } from "../update.js";
16
15
  import { planNotice } from "../plan.js";
17
16
  import type { PlanStatus } from "../plan.js";
18
17
  import { looksUnchanged, readState, updateSession } from "../state.js";
18
+ import { sessionFingerprint } from "../subagents.js";
19
19
  import type { ClientState, CommitMark } from "../state.js";
20
20
 
21
21
  export const TOTAL_BUDGET_MS = 30_000;
@@ -258,13 +258,17 @@ async function sweptSessions(state: ClientState, report: UploadReport): Promise<
258
258
  return targets.sort((a, b) => a.file!.sizeBytes - b.file!.sizeBytes);
259
259
  }
260
260
 
261
- /** Size and mtime of a transcript, for the "did it change" check on the next run. */
261
+ /**
262
+ * Size and mtime of a transcript, for the "did it change" check on the next run.
263
+ * The same measure a listing takes (`paths.ts`), subagents included, or the next
264
+ * scan would read every session a hook uploaded as changed.
265
+ */
262
266
  async function fingerprint(target: Target): Promise<{ sizeBytes: number; modifiedMs: number }> {
263
267
  if (target.file) {
264
268
  return { sizeBytes: target.file.sizeBytes, modifiedMs: target.file.modifiedAt.getTime() };
265
269
  }
266
- const info = await stat(target.path);
267
- return { sizeBytes: info.size, modifiedMs: info.mtime.getTime() };
270
+ const whole = await sessionFingerprint(target.path);
271
+ return { sizeBytes: whole.sizeBytes, modifiedMs: whole.modifiedAt.getTime() };
268
272
  }
269
273
 
270
274
  async function sendOne(
package/src/detectors.ts CHANGED
@@ -97,6 +97,26 @@ export function detectTestModifiedToPass(session: ParsedSession): Candidate[] {
97
97
  if (!isTestFile(filePath)) continue;
98
98
 
99
99
  for (const edit of edits) {
100
+ if (edit.tool === "Bash") {
101
+ // `sed -i` on a test says where, never what (`parser.ts:shellEditPaths`),
102
+ // so whether it weakened the test is the model's to read. Right after a
103
+ // failure it is worth the read; any other time it is noise.
104
+ const failure = failedBefore(session, edit.recordIndex);
105
+ if (!failure) continue;
106
+ candidates.push({
107
+ category: "test_modified_to_pass",
108
+ sessionId: session.sessionId,
109
+ uuid: edit.uuid,
110
+ toolUseId: edit.toolUseId,
111
+ filePath,
112
+ recordIndex: edit.recordIndex,
113
+ startedAt: failure.timestamp,
114
+ endedAt: edit.timestamp,
115
+ weight: 0.5,
116
+ detail: "test rewritten in place by a shell command shortly after a failing command",
117
+ });
118
+ continue;
119
+ }
100
120
  if (edit.oldString === undefined || edit.newString === undefined) continue;
101
121
 
102
122
  const reason = weakensTest(edit.oldString, edit.newString);
@@ -690,17 +710,30 @@ export function detectExternalDependency(session: ParsedSession): Candidate[] {
690
710
  }
691
711
 
692
712
  /**
693
- * Whether two paths name the same file. Reads are recorded as the agent typed
694
- * them — `src/api.ts` from a shell, `/repo/src/api.ts` from the Read tool — so
695
- * a relative path matches any absolute one ending in it, and a directory
696
- * matches everything under it.
713
+ * Whether two paths name the same file. Reads and shell edits are recorded as
714
+ * the agent typed them — `src/api.ts` from a shell, `/repo/src/api.ts` from the
715
+ * Read tool — so a relative path matches any absolute one ending in it, either
716
+ * way round, a directory matches everything under it, and a glob from
717
+ * `cat src/*.js` matches every file it could have expanded to.
697
718
  */
698
719
  function samePath(known: string, filePath: string): boolean {
699
720
  if (known === filePath) return true;
721
+ if (/[*?]/.test(known)) return globMatches(known, filePath);
700
722
  if (filePath.startsWith(known.endsWith("/") ? known : `${known}/`)) return true;
723
+ if (!filePath.startsWith("/") && known.endsWith(`/${filePath}`)) return true;
701
724
  return !known.startsWith("/") && filePath.endsWith(`/${known}`);
702
725
  }
703
726
 
727
+ const GLOB_PARTS: Record<string, string> = { "?": "[^/]", "*": "[^/]*", "**": ".*", "**/": "(?:.*/)?" };
728
+
729
+ /** `*` and `?` within one path segment, `**` across them; a relative glob matches by suffix, like a relative path. */
730
+ function globMatches(glob: string, filePath: string): boolean {
731
+ const body = glob
732
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
733
+ .replace(/\*\*\/?|\*|\?/g, (wildcard) => GLOB_PARTS[wildcard]!);
734
+ return new RegExp(glob.startsWith("/") ? `^${body}$` : `(?:^|/)${body}$`).test(filePath);
735
+ }
736
+
704
737
  function wasLookedUp(session: ParsedSession, filePath: string): boolean {
705
738
  for (const known of session.filesRead) {
706
739
  if (samePath(known, filePath)) return true;
@@ -714,7 +747,8 @@ export function detectUnverifiedAssumption(session: ParsedSession): Candidate[]
714
747
  for (const [filePath, edits] of session.fileEdits) {
715
748
  const first = edits[0];
716
749
  if (!first) continue;
717
- if (first.tool !== "Edit" && first.tool !== "MultiEdit") continue;
750
+ // `sed -i` edits in place like Edit does, on the same picture of the file.
751
+ if (first.tool !== "Edit" && first.tool !== "MultiEdit" && first.tool !== "Bash") continue;
718
752
  if (wasLookedUp(session, filePath)) continue;
719
753
 
720
754
  candidates.push({
package/src/hook.ts CHANGED
@@ -4,7 +4,7 @@ import type { AgentHook } from "./agents/types.js";
4
4
  import { claudeConfigDir, claudeSettingsPath } from "./paths.js";
5
5
 
6
6
  export const HOOK_EVENT = "SessionEnd";
7
- export const HOOK_COMMAND = "npx @nightloom/isy upload --hook";
7
+ export const HOOK_COMMAND = "exec 3<&0; nohup npx @nightloom/isy upload --hook <&3 >/dev/null 2>&1 &";
8
8
  export const START_HOOK_EVENT = "SessionStart";
9
9
  export const START_HOOK_COMMAND = "npx @nightloom/isy check --hook";
10
10
 
@@ -18,11 +18,29 @@ export const START_HOOK_COMMAND = "npx @nightloom/isy check --hook";
18
18
  * installing over it rewrites that line in place instead of leaving two hooks
19
19
  * to fire.
20
20
  */
21
- export const ISY_HOOKS: { event: string; command: string; superseded: string[] }[] = [
21
+ export const ISY_HOOKS: (AgentHook & { superseded: string[] })[] = [
22
22
  {
23
23
  event: HOOK_EVENT,
24
+ // Detached, the way Kimi CLI's and Codex's are. Claude Code 2.1 cancels a
25
+ // SessionEnd hook after 1.5 seconds unless it asks for more — before `npx`
26
+ // has even started node, so every upload at the end of a session was
27
+ // killed — and it waits out whatever a hook asks for on `/clear` and
28
+ // `/resume` too, so a hook given the upload's own thirty seconds froze
29
+ // both for as long as the upload took. The shell returns at once and the
30
+ // upload outlives it. A background job's stdin is /dev/null, so the
31
+ // payload is handed over on fd 3 first: without it the upload took the
32
+ // newest session in the cwd, the wrong one whenever two share a directory.
33
+ // Its line is parked for the next session start (`claude.ts:deliver`).
34
+ //
35
+ // ponytail: POSIX `&`. Claude Code runs hooks through bash (Git Bash on
36
+ // Windows), so this holds wherever it does; a hook shell without `nohup`
37
+ // loses the upload to the sweep at the next session start.
24
38
  command: HOOK_COMMAND,
25
- superseded: ["npx isy upload --silent", "npx isy upload --hook"],
39
+ superseded: [
40
+ "npx isy upload --silent",
41
+ "npx isy upload --hook",
42
+ "npx @nightloom/isy upload --hook",
43
+ ],
26
44
  },
27
45
  { event: START_HOOK_EVENT, command: START_HOOK_COMMAND, superseded: ["npx isy check --hook"] },
28
46
  ];
@@ -93,16 +111,20 @@ function matchers(settings: Record<string, unknown>, event: string): HookMatcher
93
111
  return Array.isArray(entries) ? (entries.filter(isObject) as HookMatcher[]) : [];
94
112
  }
95
113
 
114
+ /** An entry running one of `commands`, and — when one is asked for — with that timeout. */
115
+ function runs(entry: unknown, commands: readonly string[], timeout?: number): boolean {
116
+ if (!isObject(entry) || typeof entry.command !== "string" || !commands.includes(entry.command)) return false;
117
+ return timeout === undefined || entry.timeout === timeout;
118
+ }
119
+
96
120
  function hasHook(
97
121
  settings: Record<string, unknown>,
98
122
  event: string,
99
123
  commands: readonly string[],
124
+ timeout?: number,
100
125
  ): boolean {
101
126
  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
- ),
127
+ Array.isArray(matcher.hooks) && matcher.hooks.some((entry) => runs(entry, commands, timeout)),
106
128
  );
107
129
  }
108
130
 
@@ -131,23 +153,20 @@ function stripHook(
131
153
  }
132
154
 
133
155
  /**
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.
156
+ * Swap the first entry running one of `commands` for the hook as it should be
157
+ * written, at the same group and position, dropping any further copies, so no
158
+ * group's index moves. The same swap brings an older command up to date and
159
+ * gives the current one a timeout it was written without.
136
160
  */
137
- function replaceSuperseded(
138
- groups: unknown[],
139
- commands: readonly string[],
140
- command: string,
141
- ): boolean {
161
+ function replaceSuperseded(groups: unknown[], commands: readonly string[], hook: AgentHook): boolean {
142
162
  let replaced = false;
143
163
  for (const group of groups) {
144
164
  if (!isObject(group) || !Array.isArray(group.hooks)) continue;
145
165
  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
- }
166
+ if (!isObject(entry) || !runs(entry, commands)) return true;
149
167
  if (replaced) return false;
150
- entry.command = command;
168
+ entry.command = hook.command;
169
+ if (hook.timeout !== undefined) entry.timeout = hook.timeout;
151
170
  replaced = true;
152
171
  return true;
153
172
  });
@@ -155,16 +174,45 @@ function replaceSuperseded(
155
174
  return replaced;
156
175
  }
157
176
 
177
+ /**
178
+ * Bring the entries an older isy wrote up to date, in place, and add nothing:
179
+ * a hook that is not there at all stays away — that is the reader's call, and
180
+ * `isy check` names it. The SessionStart hook runs this, so an upgrade needs no
181
+ * `isy init`, which pairs the browser again, and on a plan with one key asks
182
+ * the reader to revoke the key in use first. Whether anything changed.
183
+ */
184
+ export async function repairHooksIn(file: HookFile): Promise<boolean> {
185
+ const settings = await readSettings(file);
186
+ const stale = file.hooks.filter(
187
+ (hook) =>
188
+ !hasHook(settings, hook.event, [hook.command], hook.timeout) &&
189
+ hasHook(settings, hook.event, [hook.command, ...(hook.superseded ?? [])]),
190
+ );
191
+ if (stale.length === 0) return false;
192
+
193
+ const hooks = isObject(settings.hooks) ? { ...settings.hooks } : {};
194
+ for (const hook of stale) {
195
+ const existing = [...(hooks[hook.event] as unknown[])];
196
+ replaceSuperseded(existing, [hook.command, ...(hook.superseded ?? [])], hook);
197
+ hooks[hook.event] = existing;
198
+ }
199
+
200
+ await writeSettings(file, { ...settings, hooks });
201
+ return true;
202
+ }
203
+
158
204
  export async function installedHooksIn(file: HookFile): Promise<string[]> {
159
205
  const settings = await readSettings(file);
160
- return file.hooks.filter((hook) => hasHook(settings, hook.event, [hook.command])).map(
206
+ return file.hooks.filter((hook) => hasHook(settings, hook.event, [hook.command], hook.timeout)).map(
161
207
  (hook) => hook.event,
162
208
  );
163
209
  }
164
210
 
165
211
  export async function installHookIn(file: HookFile): Promise<"installed" | "already-present"> {
166
212
  const settings = await readSettings(file);
167
- const missing = file.hooks.filter((hook) => !hasHook(settings, hook.event, [hook.command]));
213
+ const missing = file.hooks.filter(
214
+ (hook) => !hasHook(settings, hook.event, [hook.command], hook.timeout),
215
+ );
168
216
  if (missing.length === 0) return "already-present";
169
217
 
170
218
  const hooks = isObject(settings.hooks) ? { ...settings.hooks } : {};
@@ -179,9 +227,14 @@ export async function installHookIn(file: HookFile): Promise<"installed" | "alre
179
227
  // after it — and with them the positions Codex keys its approvals on, so
180
228
  // the user's hooks would lose their approval and ours would inherit one it
181
229
  // 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 }] });
230
+ const replaced = replaceSuperseded(existing, [hook.command, ...(hook.superseded ?? [])], hook);
231
+ if (!replaced) {
232
+ existing.push({
233
+ hooks: [
234
+ { type: "command", command: hook.command, ...(hook.timeout !== undefined ? { timeout: hook.timeout } : {}) },
235
+ ],
236
+ });
237
+ }
185
238
 
186
239
  hooks[hook.event] = existing;
187
240
  }
@@ -213,7 +266,7 @@ export async function removeHookIn(file: HookFile): Promise<"removed" | "absent"
213
266
  export async function isHookInstalled(): Promise<boolean> {
214
267
  const file = claudeHookFile();
215
268
  const settings = await readSettings(file);
216
- return ISY_HOOKS.every((hook) => hasHook(settings, hook.event, [hook.command]));
269
+ return ISY_HOOKS.every((hook) => hasHook(settings, hook.event, [hook.command], hook.timeout));
217
270
  }
218
271
 
219
272
  export function installedHooks(): Promise<string[]> {
@@ -228,6 +281,10 @@ export function removeHook(): Promise<"removed" | "absent"> {
228
281
  return removeHookIn(claudeHookFile());
229
282
  }
230
283
 
284
+ export function repairHooks(): Promise<boolean> {
285
+ return repairHooksIn(claudeHookFile());
286
+ }
287
+
231
288
  export function settingsLocation(): string {
232
289
  return claudeSettingsPath();
233
290
  }
package/src/lines.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { createReadStream } from "node:fs";
2
+
3
+ /**
4
+ * A file's lines, split on "\n" alone, a trailing "\r" dropped. `node:readline`
5
+ * also ends a line at U+2028 and U+2029, which `JSON.stringify` leaves
6
+ * unescaped inside strings: a JSONL record carrying one came apart into two
7
+ * fragments that neither parsed nor had their secrets redacted by key. Breaking
8
+ * out of the loop closes the file.
9
+ */
10
+ export async function* fileLines(path: string): AsyncGenerator<string> {
11
+ const input = createReadStream(path, { encoding: "utf8" });
12
+ let rest = "";
13
+ try {
14
+ for await (const chunk of input as AsyncIterable<string>) {
15
+ let from = 0;
16
+ for (let at = chunk.indexOf("\n"); at !== -1; at = chunk.indexOf("\n", from)) {
17
+ yield withoutCr(rest + chunk.slice(from, at));
18
+ rest = "";
19
+ from = at + 1;
20
+ }
21
+ rest += chunk.slice(from);
22
+ }
23
+ if (rest.length > 0) yield withoutCr(rest);
24
+ } finally {
25
+ input.destroy();
26
+ }
27
+ }
28
+
29
+ function withoutCr(line: string): string {
30
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
31
+ }