@phren/cli 0.3.67 → 0.3.69

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 (83) hide show
  1. package/dist/bridge/agent-hook-callback.js +11 -2
  2. package/dist/bridge/agent-hooks.d.ts +11 -1
  3. package/dist/bridge/agent-hooks.js +259 -40
  4. package/dist/bridge/changes.d.ts +2 -2
  5. package/dist/bridge/changes.js +11 -9
  6. package/dist/bridge/checkpoints.d.ts +24 -0
  7. package/dist/bridge/checkpoints.js +423 -0
  8. package/dist/bridge/claude-input-state.d.ts +14 -0
  9. package/dist/bridge/claude-input-state.js +58 -0
  10. package/dist/bridge/claude-queue.js +5 -2
  11. package/dist/bridge/claude-suggestion.d.ts +3 -0
  12. package/dist/bridge/claude-suggestion.js +10 -0
  13. package/dist/bridge/codex-threads.d.ts +7 -1
  14. package/dist/bridge/codex-threads.js +185 -56
  15. package/dist/bridge/conversation-search.d.ts +20 -0
  16. package/dist/bridge/conversation-search.js +928 -0
  17. package/dist/bridge/git-watch.d.ts +46 -0
  18. package/dist/bridge/git-watch.js +351 -0
  19. package/dist/bridge/git-worktree-remove.d.ts +44 -0
  20. package/dist/bridge/git-worktree-remove.js +140 -0
  21. package/dist/bridge/git-worktrees.d.ts +14 -0
  22. package/dist/bridge/git-worktrees.js +7 -3
  23. package/dist/bridge/git-write-policy.js +1 -1
  24. package/dist/bridge/gitboy-webhooks.d.ts +3 -1
  25. package/dist/bridge/gitboy-webhooks.js +26 -2
  26. package/dist/bridge/herdr.d.ts +6 -1
  27. package/dist/bridge/herdr.js +56 -10
  28. package/dist/bridge/hook-fast.js +13 -1
  29. package/dist/bridge/input-classification.d.ts +33 -0
  30. package/dist/bridge/input-classification.js +84 -0
  31. package/dist/bridge/pane-status.d.ts +3 -3
  32. package/dist/bridge/pane-status.js +16 -8
  33. package/dist/bridge/prompt-deliveries.d.ts +30 -4
  34. package/dist/bridge/prompt-deliveries.js +365 -13
  35. package/dist/bridge/prompt-identity.d.ts +8 -0
  36. package/dist/bridge/prompt-identity.js +15 -0
  37. package/dist/bridge/request-origin.js +2 -1
  38. package/dist/bridge/schedule-events.d.ts +17 -0
  39. package/dist/bridge/schedule-events.js +53 -0
  40. package/dist/bridge/schedule-format.d.ts +22 -2
  41. package/dist/bridge/schedule-format.js +40 -5
  42. package/dist/bridge/schedule-update.js +2 -1
  43. package/dist/bridge/schedule-watch.js +15 -5
  44. package/dist/bridge/schedules.d.ts +9 -0
  45. package/dist/bridge/schedules.js +120 -7
  46. package/dist/bridge/server-pane-routes.d.ts +7 -8
  47. package/dist/bridge/server-pane-routes.js +186 -82
  48. package/dist/bridge/server-routes.d.ts +26 -2
  49. package/dist/bridge/server-routes.js +180 -56
  50. package/dist/bridge/server-stream.js +66 -15
  51. package/dist/bridge/server.js +25 -7
  52. package/dist/bridge/session-activity.d.ts +49 -4
  53. package/dist/bridge/session-activity.js +47 -0
  54. package/dist/bridge/session-evidence.d.ts +18 -0
  55. package/dist/bridge/session-evidence.js +72 -0
  56. package/dist/bridge/session-seen.d.ts +23 -0
  57. package/dist/bridge/session-seen.js +69 -0
  58. package/dist/bridge/tab-activity.d.ts +26 -1
  59. package/dist/bridge/tab-activity.js +64 -9
  60. package/dist/bridge/terminal-resolve.d.ts +20 -0
  61. package/dist/bridge/terminal-resolve.js +145 -0
  62. package/dist/bridge/terminal-tmux.d.ts +8 -3
  63. package/dist/bridge/terminal-tmux.js +59 -7
  64. package/dist/bridge/transcript-claude.d.ts +12 -2
  65. package/dist/bridge/transcript-claude.js +91 -13
  66. package/dist/bridge/transcript-index.d.ts +4 -2
  67. package/dist/bridge/transcript-index.js +6 -5
  68. package/dist/bridge/transcript-preview.d.ts +16 -1
  69. package/dist/bridge/transcript-preview.js +171 -27
  70. package/dist/bridge/transcripts.d.ts +41 -1
  71. package/dist/bridge/transcripts.js +181 -23
  72. package/dist/bridge/turn-queue-pane.d.ts +6 -0
  73. package/dist/bridge/turn-queue-pane.js +30 -0
  74. package/dist/bridge/turn-queue.d.ts +86 -0
  75. package/dist/bridge/turn-queue.js +280 -0
  76. package/dist/bridge/turn-records.d.ts +18 -0
  77. package/dist/bridge/turn-records.js +77 -5
  78. package/dist/bridge-hook.mjs +7074 -3173
  79. package/dist/cli/config-shared.js +2 -1
  80. package/dist/cli/schedules.js +6 -1
  81. package/dist/content/secrets.js +1 -1
  82. package/dist/modules/registry.js +12 -11
  83. package/package.json +1 -1
@@ -309,7 +309,7 @@ export class ToolChanges {
309
309
  controllers = new Set();
310
310
  claims = [];
311
311
  failures = new Map();
312
- /** Conversation and repository root pairs already shown that Git could not capture changes. */
312
+ /** Repository roots already shown that Git could not capture changes. */
313
313
  reported = new Set();
314
314
  repositories = new Map();
315
315
  scratches = new Map();
@@ -318,9 +318,9 @@ export class ToolChanges {
318
318
  * time shows no changes rather than an error: a busy machine is not
319
319
  * something to act on per call, and repository Changes still has the
320
320
  * status. A broken capture (Git missing, a corrupt repository) shows on the
321
- * first call it hits in a conversation, not on every later one. A per-call
321
+ * first call it hits, until capture succeeds in that repository again. A per-call
322
322
  * limit (too many files) shows on its own call. */
323
- failed(conversation, key, error, roots = []) {
323
+ failed(key, error, roots = []) {
324
324
  if (timedOut(error))
325
325
  return undefined;
326
326
  const failure = error instanceof BridgeError ? error : new BridgeError(503, "Git change capture failed. Refresh repository Changes for the current status.", { code: "git-capture-failed" });
@@ -328,8 +328,7 @@ export class ToolChanges {
328
328
  // A breakage is news once per repository: a healthy checkout's capture
329
329
  // must not let a corrupt sibling repo report its error again.
330
330
  const root = failureRoot(error);
331
- const marks = root ? [`${conversation}\0${root}`]
332
- : roots.length ? [...new Set(roots)].map(entry => `${conversation}\0${entry}`) : [`${conversation}\0`];
331
+ const marks = root ? [root] : roots.length ? [...new Set(roots)] : ["unknown"];
333
332
  if (marks.every(mark => this.reported.has(mark)))
334
333
  return undefined;
335
334
  for (const mark of marks) {
@@ -433,7 +432,7 @@ export class ToolChanges {
433
432
  // Asked again next time rather than remembered.
434
433
  if (this.repositories.get(checkout)?.lookup === lookup)
435
434
  this.repositories.delete(checkout);
436
- throw error;
435
+ throw failedIn(error, checkout);
437
436
  });
438
437
  lookup.result = repository;
439
438
  repository.catch(() => { });
@@ -524,7 +523,10 @@ export class ToolChanges {
524
523
  snapshot.expiry.unref();
525
524
  }
526
525
  catch (error) {
527
- this.failed(conversation, key, error, snapshot.roots);
526
+ // An abandoned callback may finish after the tool ran. Its late failure
527
+ // belongs to no card; genuine failures of a live capture still report once.
528
+ if (!snapshot.dropped)
529
+ this.failed(key, error, snapshot.roots);
528
530
  if (this.snapshots.get(key) === snapshot)
529
531
  this.snapshots.delete(key);
530
532
  await this.discard(snapshot);
@@ -573,7 +575,7 @@ export class ToolChanges {
573
575
  catch (error) {
574
576
  if (this.snapshots.get(key) === snapshot) {
575
577
  this.snapshots.delete(key);
576
- this.failed(conversation, key, error, snapshot.roots);
578
+ this.failed(key, error, snapshot.roots);
577
579
  }
578
580
  const failure = this.failures.get(key);
579
581
  if (failure)
@@ -585,7 +587,7 @@ export class ToolChanges {
585
587
  await this.record(conversation, toolUseId, files);
586
588
  // Capture works again for these repositories: a later breakage there is news worth one more row.
587
589
  for (const root of snapshot.roots)
588
- this.reported.delete(`${conversation}\0${root}`);
590
+ this.reported.delete(root);
589
591
  }
590
592
  }
591
593
  async compute(snapshot) {
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ import { type Json, type Target } from "./protocol.js";
3
+ export declare function checkpointActivityArrived(target: Target): void;
4
+ declare const rowSchema: z.ZodObject<{
5
+ id: z.ZodString;
6
+ turn: z.ZodNumber;
7
+ boundary: z.ZodEnum<{
8
+ prompt: "prompt";
9
+ recovery: "recovery";
10
+ stop: "stop";
11
+ }>;
12
+ at: z.ZodString;
13
+ prompt: z.ZodString;
14
+ filesChanged: z.ZodNumber;
15
+ promptEntryId: z.ZodOptional<z.ZodString>;
16
+ }, z.core.$strip>;
17
+ export type CheckpointRow = z.infer<typeof rowSchema>;
18
+ /** Record immutable boundary facts before returning; Git runs off the callback path.
19
+ * The snapshot contains the files when the queued capture runs, not historical
20
+ * bytes from the callback instant. A route joins this queue before reading them. */
21
+ export declare function checkpointBoundary(cwd: string, target: Target, event: string, turn: number, prompt?: string, promptEntryId?: string, at?: string): void;
22
+ /** Only the pane's own checkout and conversation; child/worktree selectors are deliberately excluded. */
23
+ export declare function checkpointRoute(cwd: string, target: Target, action: string, data: Record<string, unknown>, readPane: () => Promise<Json>): Promise<unknown>;
24
+ export {};
@@ -0,0 +1,423 @@
1
+ /** Files-only turn checkpoints. Private, parentless commits never move the user's refs/index. */
2
+ import { execFile } from "node:child_process";
3
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
4
+ import { lstatSync, mkdirSync, rmdirSync, unlinkSync, symlinkSync, writeFileSync, chmodSync } from "node:fs";
5
+ import { lstat, mkdtemp, open, readlink, realpath, rm } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { promisify } from "node:util";
8
+ import { z } from "zod";
9
+ import { checkoutGitEnv } from "./projects.js";
10
+ import { BridgeError } from "./protocol.js";
11
+ import { readTurn, turnPhase } from "./turn-records.js";
12
+ import { ownRecord, liveBackground } from "./session-activity.js";
13
+ import { readFinalTurn } from "./schedule-watch.js";
14
+ import { childAgentTree, runningChildAgents } from "./transcripts.js";
15
+ // A callback can arrive while restore awaits an old disk record. Invalidate synchronously,
16
+ // before callback placement/status/record I/O; daemon callbacks already name their true session.
17
+ const activityGenerations = new Map();
18
+ let activityClock = 0;
19
+ const activityKeys = (target) => [`pane:${target.server}:${target.pane}`, `session:${target.source}:${target.session}`];
20
+ export function checkpointActivityArrived(target) {
21
+ const generation = ++activityClock;
22
+ // Pane identity also covers a new conversation taking over; session identity covers daemon placement.
23
+ for (const key of activityKeys(target))
24
+ activityGenerations.set(key, generation);
25
+ }
26
+ const activityGeneration = (target) => Math.max(...activityKeys(target).map(key => activityGenerations.get(key) ?? 0));
27
+ const exec = promisify(execFile);
28
+ // The two hash directories and ref UUID can push a ref's .lock over Windows'
29
+ // MAX_PATH even in a short checkout. Apply per process, never to user config.
30
+ const GIT_PATH_OPTIONS = ["-c", "core.longpaths=true"];
31
+ const LIMIT = 50;
32
+ // Background capture has its own safety cap, independent of callback latency.
33
+ const CAPTURE_BUDGET_MS = 60_000;
34
+ const secret = randomBytes(32);
35
+ const hash = (text) => createHash("sha256").update(text).digest("hex");
36
+ const rowSchema = z.object({ id: z.string().uuid(), turn: z.number().int().nonnegative(),
37
+ boundary: z.enum(["prompt", "stop", "recovery"]), at: z.string().datetime(), prompt: z.string().max(240), filesChanged: z.number().int().nonnegative(),
38
+ promptEntryId: z.string().min(1).max(256).optional() });
39
+ function conflict(code, message) { throw new BridgeError(409, message, { code }); }
40
+ function safePath(file) {
41
+ if (!file || file.length > 4096 || path.isAbsolute(file) || path.win32.isAbsolute(file) || file.includes("\\") || file.includes("\0") || file.split("/").some(part => !part || part === "." || part === ".." || part.toLowerCase() === ".git")) {
42
+ conflict("checkpoint-unsafe-path", "The checkpoint contains an unsafe path.");
43
+ }
44
+ }
45
+ async function context(cwd, target, budget = 15_000) {
46
+ const deadline = performance.now() + budget;
47
+ const runEnv = async (root, extra, ...args) => {
48
+ const left = Math.floor(deadline - performance.now());
49
+ if (left <= 0)
50
+ throw new Error("Checkpoint time budget exceeded");
51
+ return (await exec("git", [...GIT_PATH_OPTIONS, "-C", root, "--no-pager", ...args], { env: { ...checkoutGitEnv(), ...extra }, timeout: left, killSignal: "SIGKILL", maxBuffer: 8_388_608 })).stdout;
52
+ };
53
+ const runAt = (root, ...args) => runEnv(root, {}, ...args);
54
+ let root, dir, common;
55
+ try {
56
+ root = await realpath((await runAt(cwd, "rev-parse", "--show-toplevel")).trimEnd());
57
+ dir = await realpath((await runAt(root, "rev-parse", "--absolute-git-dir")).trimEnd());
58
+ common = await realpath(path.resolve(root, (await runAt(root, "rev-parse", "--git-common-dir")).trimEnd()));
59
+ }
60
+ catch (error) {
61
+ if (String(error.stderr).includes("not a git repository"))
62
+ conflict("checkpoint-not-isolated", "Checkpoints require a linked Git worktree.");
63
+ throw error;
64
+ }
65
+ if (!(await lstat(path.join(root, ".git"))).isFile() || path.dirname(dir) !== path.join(common, "worktrees")) {
66
+ conflict("checkpoint-not-isolated", "Checkpoints require a linked Git worktree.");
67
+ }
68
+ const check = () => { if (performance.now() >= deadline)
69
+ throw new Error("Checkpoint time budget exceeded"); };
70
+ return { check, root, dir, prefix: `refs/phren/checkpoints/${hash(root)}/${hash(`${target.source}:${target.session}`)}/`, run: (...args) => runAt(root, ...args),
71
+ input: (index, args, input) => new Promise((resolve, reject) => {
72
+ const left = Math.floor(deadline - performance.now());
73
+ if (left <= 0) {
74
+ reject(new Error("Checkpoint time budget exceeded"));
75
+ return;
76
+ }
77
+ const child = execFile("git", [...GIT_PATH_OPTIONS, "-C", root, ...args], { env: { ...checkoutGitEnv(), ...(index ? { GIT_INDEX_FILE: index } : {}) }, timeout: left, killSignal: "SIGKILL", maxBuffer: 8_388_608 }, (error, stdout) => error ? reject(error) : resolve(stdout));
78
+ child.stdin.on("error", () => { });
79
+ child.stdin.end(input);
80
+ }),
81
+ bytes: async (oid) => { check(); return (await exec("git", [...GIT_PATH_OPTIONS, "-C", root, "cat-file", "blob", oid], { env: checkoutGitEnv(), encoding: "buffer", timeout: Math.max(1, Math.floor(deadline - performance.now())), maxBuffer: 8_388_608 })).stdout; },
82
+ private: (index, ...args) => runEnv(root, { GIT_INDEX_FILE: index }, "-c", "core.fsmonitor=false", ...args) };
83
+ }
84
+ async function locked(ctx, action) {
85
+ const file = path.join(ctx.dir, "phren-checkpoint.lock");
86
+ const lock = await open(file, "wx", 0o600).catch(() => conflict("checkpoint-busy", "Another checkpoint operation is running."));
87
+ try {
88
+ return await action();
89
+ }
90
+ finally {
91
+ await lock.close();
92
+ await rm(file, { force: true });
93
+ }
94
+ }
95
+ async function rows(ctx) {
96
+ const raw = await ctx.run("for-each-ref", "--format=%(contents:subject)", ctx.prefix);
97
+ return raw.split("\n").filter(Boolean).map(line => rowSchema.parse(JSON.parse(line))).sort((a, b) => a.at.localeCompare(b.at) || a.turn - b.turn);
98
+ }
99
+ async function tree(ctx) {
100
+ const temp = await mkdtemp(path.join(ctx.dir, "phren-checkpoint-"));
101
+ try {
102
+ const index = path.join(temp, "index");
103
+ // Read only index membership, never its cached blobs/flags, and hash raw bytes without clean filters or CRLF conversion.
104
+ const names = [...new Set((await ctx.run("ls-files", "--cached", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean))];
105
+ const regular = [], records = [];
106
+ for (const file of names) {
107
+ ctx.check();
108
+ safePath(file);
109
+ if (nonDirectoryParent(ctx.root, file))
110
+ continue; // A tracked directory was replaced by a file/symlink.
111
+ validateParents(ctx.root, file, []);
112
+ const info = await lstat(path.join(ctx.root, file)).catch(error => { if (error.code === "ENOENT")
113
+ return undefined; throw error; });
114
+ if (!info)
115
+ continue;
116
+ if (info.isSymbolicLink()) {
117
+ const oid = (await ctx.input(undefined, ["hash-object", "-w", "--stdin"], await readlink(path.join(ctx.root, file)))).trim();
118
+ records.push(`120000 ${oid}\t${file}\0`);
119
+ }
120
+ else if (info.isFile())
121
+ regular.push({ file, mode: info.mode & 0o111 ? "100755" : "100644" });
122
+ else
123
+ conflict("checkpoint-unsupported-tree", "Checkpoints do not support submodules or nested Git repositories.");
124
+ }
125
+ if (regular.length) {
126
+ // Git's stdin-paths accepts C-quoted UTF-8 byte strings, including tabs/newlines in filenames.
127
+ const quoted = regular.map(({ file }) => '"' + [...Buffer.from(file)].map(byte => "\\" + byte.toString(8).padStart(3, "0")).join("") + '"').join("\n") + "\n";
128
+ const oids = (await ctx.input(undefined, ["hash-object", "-w", "--no-filters", "--stdin-paths"], quoted)).trim().split("\n");
129
+ regular.forEach(({ file, mode }, i) => records.push(`${mode} ${oids[i]}\t${file}\0`));
130
+ }
131
+ await ctx.private(index, "read-tree", "--empty");
132
+ await ctx.input(index, ["update-index", "-z", "--index-info"], records.join(""));
133
+ const result = (await ctx.private(index, "write-tree")).trim();
134
+ return result;
135
+ }
136
+ finally {
137
+ await rm(temp, { recursive: true, force: true });
138
+ }
139
+ }
140
+ async function changes(ctx, from, to) {
141
+ const tokens = (await ctx.run("diff-tree", "--no-commit-id", "--no-renames", "--name-status", "-r", "-z", from, to)).split("\0");
142
+ const files = [];
143
+ for (let i = 0; i + 1 < tokens.length; i += 2) {
144
+ const file = tokens[i + 1];
145
+ safePath(file);
146
+ files.push({ path: file, status: tokens[i] === "A" ? "A" : tokens[i] === "D" ? "D" : "M" });
147
+ }
148
+ return files;
149
+ }
150
+ async function save(ctx, current, meta, force = false) {
151
+ const previous = await rows(ctx), last = previous.at(-1);
152
+ if (!force && last && (await ctx.run("rev-parse", `${ctx.prefix}${last.id}^{tree}`)).trim() === current)
153
+ return last;
154
+ const base = last ? `${ctx.prefix}${last.id}` : "HEAD";
155
+ const row = { ...meta, id: randomUUID(), filesChanged: (await changes(ctx, base, current)).length };
156
+ // Parentless: pruning a ref also makes that snapshot collectable, even when later snapshots survive.
157
+ const commit = (await ctx.run("-c", "user.name=Phren checkpoint", "-c", "user.email=checkpoint@phren.local", "commit-tree", current, "-m", JSON.stringify(row))).trim();
158
+ const prune = previous.slice(0, Math.max(0, previous.length + 1 - LIMIT));
159
+ await ctx.input(undefined, ["update-ref", "--stdin"], `start\ncreate ${ctx.prefix}${row.id} ${commit}\n${prune.map(old => `delete ${ctx.prefix}${old.id}\n`).join("")}prepare\ncommit\n`);
160
+ return row;
161
+ }
162
+ // All operations on a worktree share a queue, including different conversations:
163
+ // the private Git lock and the working files are shared by those conversations.
164
+ const pending = new Map();
165
+ async function checkoutKey(cwd) {
166
+ let directory;
167
+ try {
168
+ directory = await realpath(cwd);
169
+ }
170
+ catch {
171
+ return path.resolve(cwd);
172
+ }
173
+ for (let current = directory;; current = path.dirname(current)) {
174
+ try {
175
+ await lstat(path.join(current, ".git"));
176
+ return current;
177
+ }
178
+ catch (error) {
179
+ if (error.code !== "ENOENT")
180
+ return directory;
181
+ }
182
+ if (path.dirname(current) === current)
183
+ return directory;
184
+ }
185
+ }
186
+ function enqueue(key, work) {
187
+ const result = (pending.get(key) ?? Promise.resolve()).then(work);
188
+ const settled = result.then(() => { }, () => { });
189
+ pending.set(key, settled);
190
+ void settled.then(() => { if (pending.get(key) === settled)
191
+ pending.delete(key); });
192
+ return result;
193
+ }
194
+ // Resolve paths in admission order, without making a callback do filesystem
195
+ // I/O. Only admission is shared globally: independent worktrees capture in
196
+ // parallel. Wrapping the queued promise keeps admission off the capture path.
197
+ let admission = Promise.resolve();
198
+ function schedule(cwd, work) {
199
+ const admitted = admission.then(async () => {
200
+ const root = await checkoutKey(cwd);
201
+ return { result: enqueue(root, () => work(root)) };
202
+ });
203
+ admission = admitted.then(() => { }, () => { });
204
+ return admitted.then(({ result }) => result);
205
+ }
206
+ const skipped = new Map();
207
+ const prompts = new Map();
208
+ const conversationKey = (root, target) => JSON.stringify([root, target.source, target.session]);
209
+ /** Record immutable boundary facts before returning; Git runs off the callback path.
210
+ * The snapshot contains the files when the queued capture runs, not historical
211
+ * bytes from the callback instant. A route joins this queue before reading them. */
212
+ export function checkpointBoundary(cwd, target, event, turn, prompt = "", promptEntryId, at = new Date().toISOString()) {
213
+ if (event !== "UserPromptSubmit" && event !== "Stop")
214
+ return;
215
+ const owner = { ...target };
216
+ const boundary = { turn, boundary: event === "Stop" ? "stop" : "prompt", at,
217
+ prompt: prompt.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 240),
218
+ ...(event === "UserPromptSubmit" && promptEntryId ? { promptEntryId } : {}) };
219
+ void schedule(cwd, async (root) => {
220
+ const key = conversationKey(root, owner);
221
+ try {
222
+ const ctx = await context(root, owner, CAPTURE_BUDGET_MS);
223
+ if (boundary.boundary === "prompt") {
224
+ prompts.delete(key);
225
+ prompts.set(key, { turn: boundary.turn, text: boundary.prompt });
226
+ if (prompts.size > 256)
227
+ prompts.delete(prompts.keys().next().value);
228
+ }
229
+ await locked(ctx, async () => {
230
+ const last = (await rows(ctx)).at(-1);
231
+ const remembered = prompts.get(key);
232
+ const excerpt = boundary.boundary === "prompt" ? boundary.prompt
233
+ : remembered?.turn === boundary.turn ? remembered.text : last?.turn === boundary.turn ? last.prompt : "";
234
+ await save(ctx, await tree(ctx), { ...boundary, prompt: excerpt }, Boolean(boundary.promptEntryId));
235
+ });
236
+ }
237
+ catch (error) {
238
+ if (error instanceof BridgeError && error.details?.code === "checkpoint-not-isolated")
239
+ return;
240
+ const reason = error instanceof BridgeError ? String(error.details?.code ?? "checkpoint-failed")
241
+ : /time budget/.test(String(error)) || error.killed ? "checkpoint-timeout" : "checkpoint-failed";
242
+ const failures = skipped.get(key) ?? [];
243
+ failures.push({ ...boundary, reason });
244
+ skipped.delete(key);
245
+ skipped.set(key, failures.slice(-LIMIT));
246
+ if (skipped.size > 256)
247
+ skipped.delete(skipped.keys().next().value);
248
+ console.warn(`[phren-hook] Checkpoint capture skipped (${reason}); boundary recorded in skippedCaptures.`);
249
+ }
250
+ });
251
+ }
252
+ async function idle(target, readPane) {
253
+ const pane = await readPane();
254
+ const record = ownRecord(await readTurn(target.server, target.pane), pane, target.source, target.session);
255
+ const phase = record && turnPhase(record);
256
+ const [background, children] = await Promise.all([
257
+ liveBackground(record, readFinalTurn),
258
+ childAgentTree(target.source, target.session).then(runningChildAgents),
259
+ ]);
260
+ if (!["idle", "done"].includes(String(pane.agent_status)) || phase?.phase === "working" || background || children.length) {
261
+ conflict("checkpoint-working", "The agent is working. Wait for it to stop before restoring files.");
262
+ }
263
+ }
264
+ function token(ctx, id, current) {
265
+ return createHash("sha256").update(secret).update(`${ctx.prefix}\0${id}\0${current}`).digest("hex");
266
+ }
267
+ async function selected(ctx, value) {
268
+ const id = z.string().uuid().parse(value);
269
+ const row = (await rows(ctx)).find(row => row.id === id);
270
+ if (!row)
271
+ throw new BridgeError(404, "That checkpoint is no longer available.", { code: "checkpoint-not-found" });
272
+ return row;
273
+ }
274
+ /** Only the pane's own checkout and conversation; child/worktree selectors are deliberately excluded. */
275
+ export async function checkpointRoute(cwd, target, action, data, readPane) {
276
+ try {
277
+ return await schedule(cwd, root => handleCheckpointRoute(root, target, action, data, readPane));
278
+ }
279
+ catch (error) {
280
+ if (error instanceof BridgeError || error instanceof z.ZodError)
281
+ throw error;
282
+ const failure = error;
283
+ if (failure.killed || failure.signal || /time budget/.test(String(error)))
284
+ throw new BridgeError(504, "Checkpoint preparation exceeded its time budget.", { code: "checkpoint-timeout" });
285
+ if (failure.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
286
+ throw new BridgeError(413, "Checkpoint output exceeded its size limit.", { code: "checkpoint-output-limit" });
287
+ throw new BridgeError(503, "Checkpoint preparation failed. Retry when the repository is idle.", { code: "checkpoint-failed" });
288
+ }
289
+ }
290
+ async function handleCheckpointRoute(cwd, target, action, data, readPane) {
291
+ const generation = activityGeneration(target);
292
+ let ctx;
293
+ try {
294
+ ctx = await context(cwd, target);
295
+ }
296
+ catch (error) {
297
+ if (action === "list" && error instanceof BridgeError && error.details?.code === "checkpoint-not-isolated")
298
+ return { state: "not-isolated", checkpoints: [], limit: LIMIT };
299
+ throw error;
300
+ }
301
+ return locked(ctx, async () => {
302
+ if (action === "list")
303
+ return { state: "ready", repository: ctx.root, checkpoints: (await rows(ctx)).reverse(), skippedCaptures: [...(skipped.get(conversationKey(ctx.root, target)) ?? [])], limit: LIMIT };
304
+ if (!["preview", "restore"].includes(action))
305
+ throw new BridgeError(404, "Unknown checkpoint route.");
306
+ const row = await selected(ctx, data.checkpointId);
307
+ const current = await tree(ctx), destination = (await ctx.run("rev-parse", `${ctx.prefix}${row.id}^{tree}`)).trim();
308
+ const files = await changes(ctx, current, destination);
309
+ if (action === "preview")
310
+ return { state: "ready", checkpointId: row.id, repository: ctx.root, files, token: token(ctx, row.id, current) };
311
+ await idle(target, readPane);
312
+ if (typeof data.token !== "string" || data.token !== token(ctx, row.id, current))
313
+ conflict("checkpoint-stale", "Files changed since the preview. Preview the restore again.");
314
+ const recovery = await save(ctx, current, { boundary: "recovery", turn: row.turn, prompt: "Before restore", at: new Date().toISOString() }, true);
315
+ // Materialize all destination blobs before changing anything; no filters, hooks or user index.
316
+ const entries = (await ctx.run("ls-tree", "-r", "-z", destination)).split("\0").filter(Boolean);
317
+ const blobs = new Map();
318
+ let blobBytes = 0;
319
+ for (const entry of entries) {
320
+ const tab = entry.indexOf("\t"), file = entry.slice(tab + 1);
321
+ safePath(file);
322
+ if (!files.some(change => change.path === file && change.status !== "D"))
323
+ continue;
324
+ const [mode, , oid] = entry.slice(0, tab).split(" ");
325
+ // cat-file's base64-free Buffer path preserves binary file contents.
326
+ const bytes = await ctx.bytes(oid);
327
+ blobBytes += bytes.length;
328
+ if (blobBytes > 64 * 1024 * 1024)
329
+ throw new BridgeError(413, "Restore exceeds the 64 MiB preparation limit.", { code: "checkpoint-output-limit" });
330
+ blobs.set(file, { mode, bytes });
331
+ }
332
+ const ignored = (await ctx.run("ls-files", "--others", "--ignored", "--exclude-standard", "-z")).split("\0").filter(Boolean);
333
+ for (const change of files) {
334
+ safePath(change.path);
335
+ // Check ignores even for paths tracked at the destination, using --no-index.
336
+ validateParents(ctx.root, change.path, files);
337
+ const excluded = nonDirectoryParent(ctx.root, change.path) ? "" : await ctx.run("check-ignore", "--no-index", "--", change.path).catch(error => {
338
+ if (error.code === 1)
339
+ return "";
340
+ throw error;
341
+ });
342
+ if (excluded || ignored.some(file => file === change.path || file.startsWith(change.path + "/") || change.path.startsWith(file + "/"))) {
343
+ conflict("checkpoint-obstructed", "An ignored file obstructs this restore.");
344
+ }
345
+ }
346
+ // Catch edits during recovery/blob reads and activity arriving during preparation.
347
+ if (await tree(ctx) !== current)
348
+ conflict("checkpoint-stale", "Files changed since the preview. Preview the restore again.");
349
+ await idle(target, readPane);
350
+ // No await after this comparison: resumed work or an input request wins even if the final read saw an old Stop.
351
+ if (activityGeneration(target) !== generation)
352
+ conflict("checkpoint-working", "Agent activity arrived. Wait for the agent to stop before restoring files.");
353
+ try {
354
+ applyFiles(ctx.root, files, blobs);
355
+ }
356
+ catch {
357
+ throw new BridgeError(503, "Restore could not finish. Use the recovery checkpoint to recover files.", { code: "checkpoint-restore-failed", recoveryId: recovery.id });
358
+ }
359
+ return { ok: true, checkpointId: row.id, recoveryId: recovery.id, files };
360
+ });
361
+ }
362
+ function nonDirectoryParent(root, file) {
363
+ const parts = file.split("/");
364
+ for (let i = 1; i < parts.length; i++) {
365
+ const info = stat(path.join(root, ...parts.slice(0, i)));
366
+ if (info && !info.isDirectory())
367
+ return true;
368
+ }
369
+ return false;
370
+ }
371
+ function validateParents(root, file, changes) {
372
+ const parts = file.split("/");
373
+ for (let i = 1; i < parts.length; i++) {
374
+ const parent = parts.slice(0, i).join("/");
375
+ const info = stat(path.join(root, parent));
376
+ if (info && !info.isDirectory()) {
377
+ if (changes.some(change => change.path === parent && change.status === "D"))
378
+ return;
379
+ conflict("checkpoint-obstructed", "A file or symlink obstructs this restore.");
380
+ }
381
+ }
382
+ }
383
+ function stat(file) { try {
384
+ return lstatSync(file);
385
+ }
386
+ catch (error) {
387
+ if (error.code === "ENOENT" || error.code === "ENOTDIR")
388
+ return undefined;
389
+ throw error;
390
+ } }
391
+ function applyFiles(root, files, blobs) {
392
+ // No await between final guard and these writes: local lifecycle callbacks cannot interleave.
393
+ for (const change of [...files].sort((a, b) => b.path.length - a.path.length)) {
394
+ // An added descendant of a file/symlink being deleted does not yet exist inside the repository.
395
+ if (nonDirectoryParent(root, change.path))
396
+ continue;
397
+ const abs = path.join(root, change.path), info = stat(abs);
398
+ if (info && !info.isDirectory())
399
+ unlinkSync(abs);
400
+ if (info?.isDirectory())
401
+ rmdirSync(abs); // Never recursively delete ignored/unrepresented contents.
402
+ let parent = path.dirname(abs);
403
+ while (parent !== root) {
404
+ try {
405
+ rmdirSync(parent);
406
+ }
407
+ catch {
408
+ break;
409
+ }
410
+ parent = path.dirname(parent);
411
+ }
412
+ }
413
+ for (const [file, { mode, bytes }] of blobs) {
414
+ const abs = path.join(root, file);
415
+ mkdirSync(path.dirname(abs), { recursive: true });
416
+ if (mode === "120000")
417
+ symlinkSync(bytes.toString("utf8"), abs);
418
+ else {
419
+ writeFileSync(abs, bytes);
420
+ chmodSync(abs, mode === "100755" ? 0o755 : 0o644);
421
+ }
422
+ }
423
+ }
@@ -0,0 +1,14 @@
1
+ import { type InputClassification } from "./input-classification.js";
2
+ import type { Entry } from "./transcripts.js";
3
+ /** Read raw provenance before public normalization removes private inputs. The
4
+ * caller supplies only a path resolved for the verified conversation. Bounds
5
+ * apply to lines and bytes; an unrelated latest user row is never a match. */
6
+ export declare function claudeInputState(file: string, submitted?: string, executionId?: string): Promise<{
7
+ input?: InputClassification;
8
+ owner?: {
9
+ at: string;
10
+ text: string;
11
+ };
12
+ backgroundStop?: boolean;
13
+ recovery: Entry[];
14
+ }>;
@@ -0,0 +1,58 @@
1
+ import { classifyClaudeInput } from "./input-classification.js";
2
+ import { object, objects } from "./protocol.js";
3
+ import { visibleClaudeEvent } from "./transcript-claude.js";
4
+ import { withTranscriptIndex } from "./transcript-index.js";
5
+ /** Read raw provenance before public normalization removes private inputs. The
6
+ * caller supplies only a path resolved for the verified conversation. Bounds
7
+ * apply to lines and bytes; an unrelated latest user row is never a match. */
8
+ export async function claudeInputState(file, submitted, executionId) {
9
+ return withTranscriptIndex(file, async (handle, index) => {
10
+ let bytes = 0, input;
11
+ let backgroundStop;
12
+ const recovery = [];
13
+ for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - 2048), undefined, 1_048_576)) {
14
+ bytes += row.bytes?.length ?? 1_048_577;
15
+ if (bytes > 1_048_576)
16
+ break;
17
+ let raw;
18
+ try {
19
+ raw = object(JSON.parse(row.bytes.toString()));
20
+ }
21
+ catch {
22
+ continue;
23
+ }
24
+ if (["assistant", "system"].includes(String(raw.type))) {
25
+ const visible = visibleClaudeEvent(raw);
26
+ if (visible)
27
+ recovery.push({ line: row.line, raw: visible });
28
+ }
29
+ const message = object(raw.message), attachment = object(raw.attachment);
30
+ const content = message.content, blocks = objects(content);
31
+ const text = typeof content === "string" ? content : blocks.filter(b => b.type === "text").map(b => String(b.text ?? "")).join("\n");
32
+ // Only explicit execution provenance can mark a Stop as background.
33
+ // Notification order and the presence/absence of reply text say nothing
34
+ // about which execution stopped. A plain Stop remains a real boundary.
35
+ if (executionId && backgroundStop === undefined && raw.type === "assistant" && (raw.executionId ?? raw.execution_id) === executionId) {
36
+ backgroundStop = classifyClaudeInput({ text: "assistant", origin: raw.origin, isSidechain: raw.isSidechain }).category !== "owner";
37
+ }
38
+ const queued = raw.type === "attachment" && attachment.type === "queued_command";
39
+ if (raw.type !== "user" && !queued)
40
+ continue;
41
+ const prompt = queued && typeof attachment.prompt === "string" ? attachment.prompt : text;
42
+ const classification = classifyClaudeInput({ text: prompt, origin: raw.origin,
43
+ commandMode: queued ? attachment.commandMode : raw.commandMode, notificationDelivery: queued,
44
+ isMeta: raw.isMeta, isSidechain: raw.isSidechain, isCompactSummary: raw.isCompactSummary,
45
+ toolResult: blocks.some(b => b.type === "tool_result"), hasImage: blocks.some(b => b.type === "image") });
46
+ if (!input && submitted !== undefined && prompt === submitted)
47
+ input = classification;
48
+ if (raw.type === "user" && classification.category === "owner") {
49
+ // An image-only or malformed latest owner boundary must not recover
50
+ // an older textual prompt. Empty text deliberately leaves previews silent.
51
+ const owner = typeof raw.timestamp === "string" && Number.isFinite(Date.parse(raw.timestamp))
52
+ ? { at: raw.timestamp, text: prompt.slice(0, 65_536) } : undefined;
53
+ return { input, owner, backgroundStop, recovery: recovery.reverse() };
54
+ }
55
+ }
56
+ return { input, backgroundStop, recovery: [] };
57
+ });
58
+ }
@@ -52,7 +52,10 @@ export function claudeQueued(transcript) {
52
52
  }
53
53
  if (row.type !== "queue-operation" || row.isSidechain)
54
54
  continue;
55
- const content = typeof row.content === "string" ? row.content : undefined;
55
+ // Unwrap before matching so a pasted enqueue and its plain removal name the
56
+ // same occurrence. Occurrences stay separate entries: two identical sends
57
+ // are two messages, and one removal takes only one of them.
58
+ const content = typeof row.content === "string" ? unwrapPastedContent(row.content) : undefined;
56
59
  if (row.operation === "enqueue" && content !== undefined)
57
60
  queue.push(content);
58
61
  else if (row.operation === "dequeue")
@@ -63,7 +66,7 @@ export function claudeQueued(transcript) {
63
66
  queue.splice(index, 1);
64
67
  }
65
68
  }
66
- return queue.map(unwrapPastedContent).filter(text => !text.trimStart().startsWith("<"));
69
+ return queue.filter(text => !text.trimStart().startsWith("<"));
67
70
  }
68
71
  /** Send Claude's queued messages to the running turn now, or withdraw them
69
72
  * all unsent. `status` is the pane's agent status. Answers the messages it
@@ -20,3 +20,6 @@ export declare function claudeSubagentView(screen: string): boolean;
20
20
  * text, a subagent's view, or no single-line live box on screen (typed text
21
21
  * that wraps leaves no rule under the prompt line). */
22
22
  export declare function claudeInputEmpty(screen: string): boolean;
23
+ /** Exact visible typed text in an unambiguous single-line composer. Wrapped,
24
+ * collapsed-paste and dim suggestion inputs cannot prove the delivery's text. */
25
+ export declare function claudeInputMatches(screen: string, text: string): boolean;
@@ -59,6 +59,16 @@ export function claudeInputEmpty(screen) {
59
59
  const dim = dimText(line);
60
60
  return !!dim && !SUBAGENT_VIEW.test(dim);
61
61
  }
62
+ /** Exact visible typed text in an unambiguous single-line composer. Wrapped,
63
+ * collapsed-paste and dim suggestion inputs cannot prove the delivery's text. */
64
+ export function claudeInputMatches(screen, text) {
65
+ const line = liveInputLine(screen);
66
+ if (line === undefined || dimText(line) || /[\r\n]/.test(text))
67
+ return false;
68
+ // Remove only Claude's prompt and its separator space. Extra whitespace,
69
+ // including ambiguous screen padding, cannot prove an exact match.
70
+ return stripTerminal(line).replace(/^\s*❯[ \u00a0]/, "") === text;
71
+ }
62
72
  /** The dim text in the live input box (between its two rules), "" when the
63
73
  * box holds typed text, undefined when there is no live box on screen. */
64
74
  function liveInputDimText(screen) {