toolroll 0.9.115 → 0.9.117

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 (145) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
@@ -0,0 +1,630 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { request as httpRequest } from "node:http";
3
+ import { request as httpsRequest } from "node:https";
4
+ import { join } from "node:path";
5
+ import { centralProfile, serviceOrigin } from "./connect-cli.js";
6
+ import { MAX_HANDOFF_PATCH_BYTES, validateHandoffPatch } from "./local-handoff.js";
7
+ import { refusal, teardownGit } from "./teardown-git.js";
8
+ const HELP = `toolroll handoff pull <task> [--repo <local-dir>] [--profile <name>]
9
+ Open a central task's code in an isolated local git worktree (never touches your dirty checkout).
10
+ toolroll handoff push [<task>] [--note "<summary>"] [--profile <name>]
11
+ Upload your local handoff diff back to the central task as an unverified revision candidate.
12
+ toolroll handoff rebase [<task>] [--repo <worktree>] [--push] [--note "<summary>"] [--profile <name>]
13
+ Rebase your isolated handoff worktree onto the latest central task head after a teammate's promotion (3-way merge, preserving a backup patch).
14
+ toolroll handoff status [<task>] [--repo <worktree>] [--profile <name>]
15
+ Show local handoff diff status, whether your base commit is stale, and central candidate/check/PR state.
16
+ toolroll handoff clean [<task>] [--repo <dir>] [--force]
17
+ Remove an isolated local handoff worktree without touching your main checkout (refuses dirty edits unless --force).`;
18
+ function httpJson(method, origin, path, token, pins = {}, body) {
19
+ const safeOrigin = serviceOrigin(origin);
20
+ const url = new URL(path, safeOrigin);
21
+ const reqFn = url.protocol === "https:" ? httpsRequest : httpRequest;
22
+ const serialized = body === undefined ? undefined : JSON.stringify(body);
23
+ const headers = {
24
+ authorization: `Bearer ${token}`,
25
+ accept: "application/json",
26
+ "x-toolroll-client": "terminal-remote",
27
+ ...(pins.workspaceId !== undefined ? { "x-toolroll-workspace": pins.workspaceId } : {}),
28
+ ...(pins.recoveryGeneration !== undefined ? { "x-toolroll-recovery": pins.recoveryGeneration } : {}),
29
+ ...(serialized === undefined ? {} : { "content-type": "application/json", "content-length": String(Buffer.byteLength(serialized)) }),
30
+ };
31
+ return new Promise((resolve, reject) => {
32
+ const req = reqFn(url, { method, headers, timeout: 30_000 }, res => {
33
+ const status = res.statusCode ?? 0;
34
+ if (status >= 300 && status < 400) {
35
+ res.resume();
36
+ resolve({ status, data: null });
37
+ return;
38
+ }
39
+ const chunks = [];
40
+ let size = 0;
41
+ res.on("data", (chunk) => {
42
+ size += chunk.length;
43
+ if (size > MAX_HANDOFF_PATCH_BYTES + 128 * 1024) {
44
+ req.destroy();
45
+ resolve({ status, data: null });
46
+ return;
47
+ }
48
+ chunks.push(chunk);
49
+ });
50
+ res.on("end", () => {
51
+ try {
52
+ resolve({ status, data: JSON.parse(Buffer.concat(chunks).toString("utf8")) });
53
+ }
54
+ catch {
55
+ resolve({ status, data: null });
56
+ }
57
+ });
58
+ });
59
+ req.on("error", reject);
60
+ req.on("timeout", () => { req.destroy(); reject(new Error("Request timed out.")); });
61
+ if (serialized !== undefined)
62
+ req.write(serialized);
63
+ req.end();
64
+ });
65
+ }
66
+ const handoffGit = teardownGit();
67
+ class GitRefused extends Error {
68
+ }
69
+ async function gitRaw(cwd, args) {
70
+ const result = await handoffGit(cwd, args);
71
+ if (result.code === 0)
72
+ return result.stdout;
73
+ const refused = refusal(result);
74
+ if (refused !== null)
75
+ throw new GitRefused(`Toolroll won't run git in this repository: ${refused}.`);
76
+ const said = result.stderr.trim().split("\n")[0] ?? "";
77
+ throw new Error(said === "" ? `git ${args[0] ?? ""} failed` : said);
78
+ }
79
+ async function gitRun(cwd, args) {
80
+ return (await gitRaw(cwd, args)).trim();
81
+ }
82
+ async function gitDiff(cwd, base) {
83
+ const patch = await gitRaw(cwd, ["diff", "--no-ext-diff", "--no-textconv", base]);
84
+ if (Buffer.byteLength(patch, "utf8") > MAX_HANDOFF_PATCH_BYTES + 1024 * 1024)
85
+ throw new Error("the local diff is too large to hand off");
86
+ return patch;
87
+ }
88
+ async function gitDirOf(cwd) {
89
+ const raw = await gitRun(cwd, ["rev-parse", "--git-dir"]);
90
+ return raw.startsWith("/") ? raw : join(cwd, raw);
91
+ }
92
+ async function gitCommonDirOf(cwd) {
93
+ const raw = await gitRun(cwd, ["rev-parse", "--git-common-dir"]);
94
+ return raw.startsWith("/") ? raw : join(cwd, raw);
95
+ }
96
+ async function commitExistsLocally(repo, sha) {
97
+ if (!sha || !/^[0-9a-f]{40}$/.test(sha))
98
+ return null;
99
+ const result = await handoffGit(repo, ["cat-file", "-e", `${sha}^{commit}`]);
100
+ return result.code === 0 ? sha : null;
101
+ }
102
+ async function syncWorktreeToCentralBase(worktree, info) {
103
+ const direct = await commitExistsLocally(worktree, info.baseCommit);
104
+ if (direct !== null) {
105
+ try {
106
+ await gitRun(worktree, ["reset", "--hard", direct]);
107
+ await gitRun(worktree, ["clean", "-fd"]);
108
+ }
109
+ catch (error) {
110
+ return { ok: false, error: `Could not reset the worktree to ${direct.slice(0, 12)}: ${error instanceof Error ? error.message : String(error)}` };
111
+ }
112
+ return { ok: true, localHead: direct, centralBase: direct };
113
+ }
114
+ const chain = info.patchChain && info.patchChain.length > 0
115
+ ? info.patchChain
116
+ : info.parentCommit && info.baseCommit && info.patch && info.patch.trim() !== ""
117
+ ? [{ parentCommit: info.parentCommit, headCommit: info.baseCommit, patch: info.patch }]
118
+ : [];
119
+ let startIndex = -1;
120
+ for (let i = chain.length - 1; i >= 0; i -= 1) {
121
+ if (await commitExistsLocally(worktree, chain[i].parentCommit) !== null) {
122
+ startIndex = i;
123
+ break;
124
+ }
125
+ }
126
+ if (startIndex !== -1) {
127
+ const steps = chain.slice(startIndex);
128
+ for (const step of steps) {
129
+ const checked = validateHandoffPatch(step.patch);
130
+ if (!checked.ok) {
131
+ return { ok: false, error: `Central patch failed safety validation: ${checked.error}` };
132
+ }
133
+ }
134
+ const anchor = steps[0].parentCommit;
135
+ let patchFile;
136
+ try {
137
+ await gitRun(worktree, ["reset", "--hard", anchor]);
138
+ await gitRun(worktree, ["clean", "-fd"]);
139
+ patchFile = join(await gitDirOf(worktree), "central-base.patch");
140
+ }
141
+ catch (error) {
142
+ return { ok: false, error: `Could not reset the worktree to ${anchor.slice(0, 12)}: ${error instanceof Error ? error.message : String(error)}` };
143
+ }
144
+ try {
145
+ for (const step of steps) {
146
+ writeFileSync(patchFile, step.patch, { mode: 0o600 });
147
+ await gitRun(worktree, ["apply", "--index", "--", patchFile]);
148
+ }
149
+ await gitRun(worktree, [
150
+ "-c", "user.name=Toolroll Handoff",
151
+ "-c", "user.email=toolroll@local",
152
+ "commit", "--no-verify", "--no-gpg-sign",
153
+ "-m", `Toolroll central base ${(info.baseCommit ?? anchor).slice(0, 12)}`,
154
+ ]);
155
+ const syntheticHead = await gitRun(worktree, ["rev-parse", "HEAD"]);
156
+ return { ok: true, localHead: syntheticHead, centralBase: info.baseCommit ?? syntheticHead };
157
+ }
158
+ catch (error) {
159
+ return {
160
+ ok: false,
161
+ error: `Could not reconstruct central commit ${(info.baseCommit ?? "").slice(0, 8)} from ${anchor.slice(0, 8)}: ${error instanceof Error ? error.message : String(error)}`,
162
+ };
163
+ }
164
+ finally {
165
+ rmSync(patchFile, { force: true });
166
+ }
167
+ }
168
+ return {
169
+ ok: false,
170
+ error: `Central base commit ${(info.baseCommit ?? "unknown").slice(0, 12)} is not in your local Git repository. Run \`git fetch\` first, then retry.`,
171
+ };
172
+ }
173
+ export async function maybeRunHandoffCommand(argv, write, options = {}) {
174
+ if (argv[0] !== "handoff")
175
+ return null;
176
+ try {
177
+ return await runHandoff(argv, write, options);
178
+ }
179
+ catch (error) {
180
+ write(`Stopped: ${error instanceof Error ? error.message : String(error)}`);
181
+ return 1;
182
+ }
183
+ }
184
+ async function runHandoff(argv, write, options) {
185
+ const sub = argv[1];
186
+ if (sub === undefined || sub === "--help" || sub === "-h" || argv.includes("--help")) {
187
+ write(HELP);
188
+ return 0;
189
+ }
190
+ const rest = argv.slice(2);
191
+ let profileName;
192
+ let repoFlag;
193
+ let note = "";
194
+ let pushAfterRebase = false;
195
+ let forceClean = false;
196
+ const positionals = [];
197
+ for (let i = 0; i < rest.length; i += 1) {
198
+ const arg = rest[i];
199
+ if (arg === "--push") {
200
+ pushAfterRebase = true;
201
+ continue;
202
+ }
203
+ if (arg === "--force") {
204
+ forceClean = true;
205
+ continue;
206
+ }
207
+ if (arg === "--profile" || arg === "--repo" || arg === "--note") {
208
+ const next = rest[++i];
209
+ if (!next) {
210
+ write(`${arg} needs a value.`);
211
+ return 2;
212
+ }
213
+ if (arg === "--profile")
214
+ profileName = next;
215
+ else if (arg === "--repo")
216
+ repoFlag = next;
217
+ else
218
+ note = next;
219
+ continue;
220
+ }
221
+ if (arg.startsWith("-")) {
222
+ write(`Unknown option: ${arg}`);
223
+ return 2;
224
+ }
225
+ positionals.push(arg);
226
+ }
227
+ const cwd = options.cwd ?? process.cwd();
228
+ if (sub === "clean") {
229
+ const targetDir = repoFlag ?? cwd;
230
+ let repoRoot;
231
+ try {
232
+ repoRoot = realpathSync(await gitRun(targetDir, ["rev-parse", "--show-toplevel"]));
233
+ }
234
+ catch (error) {
235
+ if (error instanceof GitRefused)
236
+ throw error;
237
+ write("Run this inside your local repository or handoff worktree (or pass --repo <dir>).");
238
+ return 2;
239
+ }
240
+ const common = await gitCommonDirOf(repoRoot);
241
+ const poolDir = join(common, "toolroll-handoff");
242
+ const hereMetaPath = join(await gitDirOf(repoRoot), "toolroll-handoff.json");
243
+ let worktree;
244
+ let taskId = positionals[0];
245
+ if (existsSync(hereMetaPath)) {
246
+ worktree = repoRoot;
247
+ if (!taskId) {
248
+ try {
249
+ taskId = JSON.parse(readFileSync(hereMetaPath, "utf8")).taskId;
250
+ }
251
+ catch { }
252
+ }
253
+ }
254
+ else {
255
+ if (!taskId) {
256
+ write("Name the task id to clean (or run inside its handoff worktree): toolroll handoff clean <task>");
257
+ return 2;
258
+ }
259
+ worktree = join(poolDir, taskId.replace(/[^A-Za-z0-9_.-]/g, "-"));
260
+ }
261
+ if (!existsSync(worktree)) {
262
+ write(`No local handoff worktree found at ${worktree}.`);
263
+ return 0;
264
+ }
265
+ const wtReal = realpathSync(worktree);
266
+ if (!wtReal.startsWith(realpathSync(poolDir))) {
267
+ write("Refused: target directory is not an isolated Toolroll handoff worktree.");
268
+ return 1;
269
+ }
270
+ const wtMetaPath = join(await gitDirOf(wtReal), "toolroll-handoff.json");
271
+ let meta = null;
272
+ if (existsSync(wtMetaPath)) {
273
+ try {
274
+ meta = JSON.parse(readFileSync(wtMetaPath, "utf8"));
275
+ }
276
+ catch {
277
+ meta = null;
278
+ }
279
+ }
280
+ const diffBase = (meta?.localHead && await commitExistsLocally(wtReal, meta.localHead))
281
+ ?? (meta?.baseCommit && await commitExistsLocally(wtReal, meta.baseCommit))
282
+ ?? await gitRun(wtReal, ["rev-parse", "HEAD"]);
283
+ const dirtyDiff = await gitDiff(wtReal, diffBase);
284
+ const untracked = await gitRun(wtReal, ["status", "--porcelain"]);
285
+ if (!forceClean && (dirtyDiff.trim() !== "" || untracked.trim() !== "")) {
286
+ write("Refused: handoff worktree has local changes. Push them first (`toolroll handoff push`) or re-run with `--force`.");
287
+ return 1;
288
+ }
289
+ const resolvedTask = taskId ?? meta?.taskId ?? "";
290
+ const safeTask = resolvedTask.replace(/[^A-Za-z0-9_.-]/g, "-");
291
+ const mainWorktree = realpathSync(join(common, ".."));
292
+ await gitRun(mainWorktree, ["worktree", "remove", "--force", "--", wtReal]);
293
+ if (safeTask !== "") {
294
+ try {
295
+ await gitRun(mainWorktree, ["branch", "-D", "--", `toolroll/handoff/${safeTask}`]);
296
+ }
297
+ catch { }
298
+ }
299
+ write(`Removed isolated handoff worktree for ${resolvedTask || wtReal} (your main checkout was untouched).`);
300
+ return 0;
301
+ }
302
+ let profile;
303
+ try {
304
+ profile = centralProfile(options, profileName);
305
+ }
306
+ catch (error) {
307
+ write(error instanceof Error ? error.message : "Could not read remote profile.");
308
+ return 2;
309
+ }
310
+ if (profile === null || !profile.apiToken) {
311
+ write("Connect to a central server with an API token first: toolroll connect <https://origin> --as <account> --token-stdin");
312
+ return 2;
313
+ }
314
+ if (sub === "pull") {
315
+ const taskId = positionals[0];
316
+ if (!taskId) {
317
+ write("Name a task id: toolroll handoff pull <task>");
318
+ return 2;
319
+ }
320
+ let localRepo;
321
+ try {
322
+ localRepo = realpathSync(await gitRun(repoFlag ?? cwd, ["rev-parse", "--show-toplevel"]));
323
+ }
324
+ catch (error) {
325
+ if (error instanceof GitRefused)
326
+ throw error;
327
+ write("Run this inside a local Git checkout of the project, or pass --repo <local-dir>.");
328
+ return 2;
329
+ }
330
+ const reply = await httpJson("GET", profile.origin, `/api/handoff/task/${encodeURIComponent(taskId)}`, profile.token, { workspaceId: profile.workspaceId, recoveryGeneration: profile.recoveryGeneration });
331
+ if (reply.status !== 200 || reply.data === null || !reply.data.ok) {
332
+ write(reply.data?.message ?? `Central server answered status ${reply.status}.`);
333
+ return 1;
334
+ }
335
+ const info = reply.data;
336
+ if (profile.workspaceId !== undefined && info.workspaceId !== profile.workspaceId) {
337
+ write("Refused: central server workspace identity does not match your saved profile.");
338
+ return 1;
339
+ }
340
+ const common = await gitCommonDirOf(localRepo);
341
+ const poolDir = join(common, "toolroll-handoff");
342
+ mkdirSync(poolDir, { recursive: true, mode: 0o700 });
343
+ const safeTask = taskId.replace(/[^A-Za-z0-9_.-]/g, "-");
344
+ const worktree = join(poolDir, safeTask);
345
+ if (existsSync(worktree)) {
346
+ write(`Handoff worktree already exists:\n cd ${worktree}`);
347
+ return 0;
348
+ }
349
+ const startRef = await commitExistsLocally(localRepo, info.baseCommit)
350
+ ?? await commitExistsLocally(localRepo, info.parentCommit)
351
+ ?? "HEAD";
352
+ const branch = `toolroll/handoff/${safeTask}`;
353
+ try {
354
+ await gitRun(localRepo, ["worktree", "add", "-B", branch, "--", worktree, startRef]);
355
+ }
356
+ catch (error) {
357
+ write(`Could not create isolated handoff worktree: ${error instanceof Error ? error.message : String(error)}`);
358
+ return 1;
359
+ }
360
+ let localHead = await gitRun(worktree, ["rev-parse", "HEAD"]);
361
+ if (info.baseCommit && await commitExistsLocally(worktree, info.baseCommit) === null && info.patch && info.patch.trim() !== "") {
362
+ const synced = await syncWorktreeToCentralBase(worktree, info);
363
+ if (synced.ok) {
364
+ localHead = synced.localHead;
365
+ }
366
+ else {
367
+ write(`Created isolated worktree at ${worktree}, but central patch could not auto-apply cleanly: ${synced.error}`);
368
+ }
369
+ }
370
+ else if (!info.baseCommit && info.patch && info.patch.trim() !== "") {
371
+ const patchFile = join(await gitDirOf(worktree), "central-initial.patch");
372
+ writeFileSync(patchFile, info.patch, { mode: 0o600 });
373
+ try {
374
+ await gitRun(worktree, ["apply", "--3way", "--", patchFile]);
375
+ }
376
+ catch {
377
+ write(`Created isolated worktree at ${worktree}, but central patch could not auto-apply cleanly (base ${startRef}).`);
378
+ }
379
+ finally {
380
+ rmSync(patchFile, { force: true });
381
+ }
382
+ }
383
+ const meta = {
384
+ workspaceId: info.workspaceId ?? "",
385
+ recoveryGeneration: info.recoveryGeneration ?? "",
386
+ taskId: info.taskId ?? taskId,
387
+ baseCommit: info.baseCommit ?? localHead,
388
+ localHead,
389
+ origin: profile.origin,
390
+ profile: profile.name,
391
+ };
392
+ writeFileSync(join(await gitDirOf(worktree), "toolroll-handoff.json"), JSON.stringify(meta, null, 2), { mode: 0o600 });
393
+ write(`Opened task ${meta.taskId} (${info.title ?? "task"}) in an isolated local worktree (your main checkout was untouched):`);
394
+ write(` cd ${worktree}`);
395
+ write(`When ready, push your changes back with:`);
396
+ write(` toolroll handoff push --note "Updated locally"`);
397
+ return 0;
398
+ }
399
+ if (sub === "push") {
400
+ let worktreeRoot;
401
+ try {
402
+ worktreeRoot = realpathSync(await gitRun(repoFlag ?? cwd, ["rev-parse", "--show-toplevel"]));
403
+ }
404
+ catch (error) {
405
+ if (error instanceof GitRefused)
406
+ throw error;
407
+ write("Run this inside your local handoff worktree (or pass --repo <worktree>).");
408
+ return 2;
409
+ }
410
+ const metaPath = join(await gitDirOf(worktreeRoot), "toolroll-handoff.json");
411
+ let meta = null;
412
+ if (existsSync(metaPath)) {
413
+ try {
414
+ meta = JSON.parse(readFileSync(metaPath, "utf8"));
415
+ }
416
+ catch {
417
+ meta = null;
418
+ }
419
+ }
420
+ const taskId = positionals[0] ?? meta?.taskId;
421
+ if (!taskId) {
422
+ write("Not inside a handoff worktree. Name the task id: toolroll handoff push <task>");
423
+ return 2;
424
+ }
425
+ if (meta !== null && meta.workspaceId !== "" && profile.workspaceId !== undefined && meta.workspaceId !== profile.workspaceId) {
426
+ write("Refused: this handoff worktree belongs to a different central workspace than your active profile.");
427
+ return 1;
428
+ }
429
+ const baseCommit = meta?.baseCommit ?? await gitRun(worktreeRoot, ["rev-parse", "HEAD"]);
430
+ const diffBase = (meta?.localHead && await commitExistsLocally(worktreeRoot, meta.localHead)) ?? baseCommit;
431
+ const patch = await gitDiff(worktreeRoot, diffBase);
432
+ const checked = validateHandoffPatch(patch);
433
+ if (!checked.ok) {
434
+ write(`Cannot upload local diff: ${checked.error}`);
435
+ return 1;
436
+ }
437
+ const reply = await httpJson("POST", profile.origin, `/api/handoff/task/${encodeURIComponent(taskId)}/candidate`, profile.token, {
438
+ workspaceId: meta?.workspaceId || profile.workspaceId,
439
+ recoveryGeneration: meta?.recoveryGeneration || profile.recoveryGeneration,
440
+ }, { patch, baseCommit, note });
441
+ if (reply.status !== 201 || reply.data === null || !reply.data.ok) {
442
+ write(reply.data?.message ?? `Central server refused candidate upload (status ${reply.status}).`);
443
+ return 1;
444
+ }
445
+ write(`Uploaded local candidate ${reply.data.candidateId} to task ${reply.data.taskId} (${checked.files.length} files, unverified — ready for central checks/review).`);
446
+ return 0;
447
+ }
448
+ if (sub === "rebase") {
449
+ let worktreeRoot;
450
+ try {
451
+ worktreeRoot = realpathSync(await gitRun(repoFlag ?? cwd, ["rev-parse", "--show-toplevel"]));
452
+ }
453
+ catch (error) {
454
+ if (error instanceof GitRefused)
455
+ throw error;
456
+ write("Run this inside your local handoff worktree (or pass --repo <worktree>).");
457
+ return 2;
458
+ }
459
+ const gdir = await gitDirOf(worktreeRoot);
460
+ const metaPath = join(gdir, "toolroll-handoff.json");
461
+ let meta = null;
462
+ if (existsSync(metaPath)) {
463
+ try {
464
+ meta = JSON.parse(readFileSync(metaPath, "utf8"));
465
+ }
466
+ catch {
467
+ meta = null;
468
+ }
469
+ }
470
+ const taskId = positionals[0] ?? meta?.taskId;
471
+ if (!taskId) {
472
+ write("Not inside a handoff worktree. Name the task id: toolroll handoff rebase <task>");
473
+ return 2;
474
+ }
475
+ if (meta !== null && meta.workspaceId !== "" && profile.workspaceId !== undefined && meta.workspaceId !== profile.workspaceId) {
476
+ write("Refused: this handoff worktree belongs to a different central workspace than your active profile.");
477
+ return 1;
478
+ }
479
+ const oldBase = meta?.baseCommit ?? await gitRun(worktreeRoot, ["rev-parse", "HEAD"]);
480
+ const oldDiffBase = (meta?.localHead && await commitExistsLocally(worktreeRoot, meta.localHead)) ?? oldBase;
481
+ const localPatch = await gitDiff(worktreeRoot, oldDiffBase);
482
+ const hasLocalChanges = localPatch.trim() !== "";
483
+ if (hasLocalChanges) {
484
+ const checkedLocal = validateHandoffPatch(localPatch);
485
+ if (!checkedLocal.ok) {
486
+ write(`Cannot rebase local diff: ${checkedLocal.error}`);
487
+ return 1;
488
+ }
489
+ }
490
+ const reply = await httpJson("GET", profile.origin, `/api/handoff/task/${encodeURIComponent(taskId)}`, profile.token, { workspaceId: meta?.workspaceId || profile.workspaceId, recoveryGeneration: meta?.recoveryGeneration || profile.recoveryGeneration });
491
+ if (reply.status !== 200 || reply.data === null || !reply.data.ok) {
492
+ write(reply.data?.message ?? `Central server answered status ${reply.status}.`);
493
+ return 1;
494
+ }
495
+ const info = reply.data;
496
+ if (profile.workspaceId !== undefined && info.workspaceId !== profile.workspaceId) {
497
+ write("Refused: central server workspace identity does not match your saved profile.");
498
+ return 1;
499
+ }
500
+ const newBase = info.baseCommit ?? oldBase;
501
+ if (newBase === oldBase) {
502
+ write(`Already up to date with central base ${newBase.slice(0, 12)}.`);
503
+ if (pushAfterRebase && hasLocalChanges) {
504
+ return maybeRunHandoffCommand(["handoff", "push", taskId, ...(note ? ["--note", note] : []), ...(profileName ? ["--profile", profileName] : [])], write, { ...options, cwd: worktreeRoot });
505
+ }
506
+ return 0;
507
+ }
508
+ const backupPath = join(gdir, "rebase-backup.patch");
509
+ if (hasLocalChanges)
510
+ writeFileSync(backupPath, localPatch, { mode: 0o600 });
511
+ const synced = await syncWorktreeToCentralBase(worktreeRoot, info);
512
+ if (!synced.ok) {
513
+ write(`Rebase paused (your worktree was not modified; backup saved at ${backupPath}): ${synced.error}`);
514
+ return 1;
515
+ }
516
+ const updatedMeta = {
517
+ workspaceId: info.workspaceId ?? meta?.workspaceId ?? "",
518
+ recoveryGeneration: info.recoveryGeneration ?? meta?.recoveryGeneration ?? "",
519
+ taskId: info.taskId ?? taskId,
520
+ baseCommit: synced.centralBase,
521
+ localHead: synced.localHead,
522
+ origin: profile.origin,
523
+ profile: profile.name,
524
+ };
525
+ writeFileSync(metaPath, JSON.stringify(updatedMeta, null, 2), { mode: 0o600 });
526
+ if (hasLocalChanges) {
527
+ try {
528
+ await gitRun(worktreeRoot, ["apply", "--3way", "--", backupPath]);
529
+ }
530
+ catch {
531
+ write(`Rebased onto central head ${synced.centralBase.slice(0, 12)}, but your local changes hit merge conflicts.`);
532
+ write(`Your original patch is safely backed up at: ${backupPath}`);
533
+ write(`Resolve the conflict markers in ${worktreeRoot}, then run:`);
534
+ write(` toolroll handoff push ${taskId}`);
535
+ return 1;
536
+ }
537
+ rmSync(backupPath, { force: true });
538
+ }
539
+ write(`Rebased handoff worktree for ${taskId} cleanly from ${oldBase.slice(0, 12)} to ${synced.centralBase.slice(0, 12)}.`);
540
+ if (pushAfterRebase) {
541
+ if (!hasLocalChanges) {
542
+ write("No local diff to push after rebase.");
543
+ return 0;
544
+ }
545
+ return maybeRunHandoffCommand(["handoff", "push", taskId, ...(note ? ["--note", note] : []), ...(profileName ? ["--profile", profileName] : [])], write, { ...options, cwd: worktreeRoot });
546
+ }
547
+ write(`Ready to upload a fresh candidate: toolroll handoff push ${taskId}`);
548
+ return 0;
549
+ }
550
+ if (sub === "status") {
551
+ let worktreeRoot;
552
+ try {
553
+ worktreeRoot = realpathSync(await gitRun(repoFlag ?? cwd, ["rev-parse", "--show-toplevel"]));
554
+ }
555
+ catch (error) {
556
+ if (error instanceof GitRefused)
557
+ throw error;
558
+ write("Run this inside your local handoff worktree (or pass --repo <worktree>).");
559
+ return 2;
560
+ }
561
+ const metaPath = join(await gitDirOf(worktreeRoot), "toolroll-handoff.json");
562
+ let meta = null;
563
+ if (existsSync(metaPath)) {
564
+ try {
565
+ meta = JSON.parse(readFileSync(metaPath, "utf8"));
566
+ }
567
+ catch {
568
+ meta = null;
569
+ }
570
+ }
571
+ const taskId = positionals[0] ?? meta?.taskId;
572
+ if (!taskId) {
573
+ write("Not inside a handoff worktree. Name the task id: toolroll handoff status <task>");
574
+ return 2;
575
+ }
576
+ const baseCommit = meta?.baseCommit ?? await gitRun(worktreeRoot, ["rev-parse", "HEAD"]);
577
+ const diffBase = (meta?.localHead && await commitExistsLocally(worktreeRoot, meta.localHead)) ?? baseCommit;
578
+ const localPatch = await gitDiff(worktreeRoot, diffBase);
579
+ const checked = localPatch.trim() === "" ? null : validateHandoffPatch(localPatch);
580
+ const reply = await httpJson("GET", profile.origin, `/api/handoff/task/${encodeURIComponent(taskId)}/candidates`, profile.token, {
581
+ workspaceId: meta?.workspaceId || profile.workspaceId,
582
+ recoveryGeneration: meta?.recoveryGeneration || profile.recoveryGeneration,
583
+ });
584
+ if (reply.status !== 200 || reply.data === null || !reply.data.ok) {
585
+ write(reply.data?.message ?? `Central server answered status ${reply.status}.`);
586
+ return 1;
587
+ }
588
+ const centralBase = reply.data.currentBaseCommit ?? null;
589
+ const stale = centralBase !== null && baseCommit !== centralBase;
590
+ write(`Task: ${taskId} (${profile.origin})`);
591
+ write(`Local base: ${baseCommit.slice(0, 12)}${stale ? ` [STALE — central is ${centralBase.slice(0, 12)}]` : " [up to date]"}`);
592
+ if (checked === null) {
593
+ write("Local edits: none");
594
+ }
595
+ else if (checked.ok) {
596
+ write(`Local edits: ${checked.files.length} file${checked.files.length === 1 ? "" : "s"} (${checked.files.join(", ")})`);
597
+ }
598
+ else {
599
+ write(`Local edits: invalid patch (${checked.error})`);
600
+ }
601
+ const cands = reply.data.candidates ?? [];
602
+ if (cands.length === 0) {
603
+ write("Central candidates: none");
604
+ }
605
+ else {
606
+ write(`Central candidates (${cands.length}):`);
607
+ for (const c of cands) {
608
+ const state = c.promotedAt
609
+ ? c.publication?.prNumber
610
+ ? `promoted Run #${c.runId ?? "?"} · PR #${c.publication.prNumber}`
611
+ : c.publication
612
+ ? `promoted Run #${c.runId ?? "?"} · PR queued`
613
+ : `promoted Run #${c.runId ?? "?"} · checks ${c.liveCheckState ?? "not-run"}${c.canOpenPr ? " · ready for PR" : ""}`
614
+ : c.stale
615
+ ? "stale"
616
+ : "unverified";
617
+ write(` - ${c.id} by ${c.author} [${state}]`);
618
+ }
619
+ }
620
+ if (stale) {
621
+ write(`Next step: toolroll handoff rebase ${taskId}`);
622
+ }
623
+ else if (checked?.ok) {
624
+ write(`Next step: toolroll handoff push ${taskId}`);
625
+ }
626
+ return 0;
627
+ }
628
+ write(`Unknown handoff action: ${sub}\n${HELP}`);
629
+ return 2;
630
+ }