@agimon-ai/po-git 0.0.0-alpha.196 → 0.0.0-alpha.197

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.
@@ -1,15 +1,87 @@
1
- import { C as READ_TIMEOUT_MS, E as runGit, S as NETWORK_TIMEOUT_MS, T as createWorktreeGit, a as GIT_WORKTREE_LIFECYCLE_EVENT, c as isWorktreeLifecycleEvent, d as registryFile, f as readJson, g as invalidRequest, h as PoGitExpectedError, i as GIT_SESSION_CHANGED_EVENT, l as credentialsFile, m as HubUnavailableError, n as createWorktreeRegistry, o as createWorktreeMessageInbox, p as writeJsonAtomic, r as validRefName, s as isSessionChangedEvent, t as createWorktreeOperations, u as poGitRoot, w as REBASE_TIMEOUT_MS } from "../worktreeOperations-hT6N8oSr.mjs";
1
+ import { A as NETWORK_TIMEOUT_MS, C as PoGitExpectedError, F as revision, I as runGit, L as GIT_ENGINE_CONTRACT, M as REBASE_TIMEOUT_MS, N as createWorktreeGit, P as remoteBranchHead, S as HubUnavailableError, _ as createWorktreeMessageInbox, a as credentialsFile, b as receiveWorktreeSetup, c as registryFile, f as StartWorktreeWorkflowSchema, g as GIT_WORKTREE_LIFECYCLE_EVENT, h as GIT_SESSION_CHANGED_EVENT, i as validRefName, j as READ_TIMEOUT_MS, l as createWorktreeRegistry, m as writeJsonAtomic, n as createGitOperationDependencies, p as readJson, r as createWorktreeOperations, s as poGitRoot, u as GIT_WORKFLOWS_CONTRACT, v as isSessionChangedEvent, w as invalidRequest, x as validSparseProfile, y as isWorktreeLifecycleEvent } from "../gitDependencies-DYe8D0VS.mjs";
2
+ import { BACKGROUND_CONTEXT, PO_FS_SERVICE, PO_SHELL_SERVICE, requirePoFs, requirePoShell, withAbortSignal } from "@agimon-ai/po-core/platform";
3
+ import { createGitEngineService, createPoFsAdapter } from "@agimon-ai/po-sparo";
4
+ import { PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
2
5
  import fs from "node:fs/promises";
6
+ import { createHash, randomUUID } from "node:crypto";
3
7
  import path from "node:path";
4
8
  import os from "node:os";
5
- import { composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
9
+ import { Check } from "typebox/value";
10
+ import { Type } from "typebox";
11
+ import { PO_WORKFLOW_ADMISSIONS_SERVICE, PO_WORKFLOW_RUNS_SERVICE, PoWorkflowDefinitionRefSchema, readPoWorkflowAdmissionsService, readPoWorkflowRunsService } from "@agimon-ai/po-core/workflow";
6
12
  import { composeRootHooks, composeRootInjects, defineChannel, defineHook, defineResource, defineRoot, defineRoute, defineServerTool } from "@agimon-ai/po-core/extensionFile";
7
13
  import { PO_CODEMODE_SERVICE, readPoCodemode } from "@agimon-ai/po-core/codemode";
8
14
  import { readPoSessionDelivery } from "@agimon-ai/po-session";
9
- import { Type } from "typebox";
10
- import { BACKGROUND_CONTEXT, PO_SHELL_SERVICE, requirePoShell, withAbortSignal } from "@agimon-ai/po-core/platform";
15
+ import { canonicalLocale, formatMessage, readPoLang, readPoPersonLocale } from "@agimon-ai/po-core/locale";
11
16
  import { poApiCallerFrom } from "@agimon-ai/po-core/packageApi";
12
17
  import { parseLaunchSelection } from "@agimon-ai/po-core/hubChannel";
18
+ //#region src/extensions/workspaces/(backend)/root.server.ts
19
+ var root_server_default$1 = defineRoot(({ context, signal }) => {
20
+ context.inject([PO_SERVER_SCOPE_SERVICE, PO_FS_SERVICE], (scoped) => {
21
+ let shell;
22
+ let shellSignal = AbortSignal.abort(/* @__PURE__ */ new Error("Git engine requires the host shell (po/shell)."));
23
+ scoped.inject([PO_SHELL_SERVICE], (child) => {
24
+ const lifetime = new AbortController();
25
+ shell = requirePoShell(child);
26
+ shellSignal = lifetime.signal;
27
+ return () => {
28
+ shell = void 0;
29
+ lifetime.abort(/* @__PURE__ */ new Error("Git engine host shell was disposed."));
30
+ };
31
+ });
32
+ const engine = createGitEngineService({
33
+ fs: createPoFsAdapter(requirePoFs(scoped), (operationSignal) => withAbortSignal(AbortSignal.any([signal, operationSignal]), BACKGROUND_CONTEXT)),
34
+ exec: ({ environment }) => {
35
+ const env = Object.fromEntries(Object.entries(environment).filter((entry) => entry[1] !== void 0));
36
+ return { async run(command, args, options) {
37
+ if (shell === void 0) throw new Error("Git engine requires the host shell (po/shell).");
38
+ const operationSignal = AbortSignal.any([
39
+ signal,
40
+ shellSignal,
41
+ options.signal ?? signal,
42
+ AbortSignal.timeout(12e4)
43
+ ]);
44
+ operationSignal.throwIfAborted();
45
+ let stdout = "";
46
+ let stderr = "";
47
+ let bytes = 0;
48
+ const outputLimit = new AbortController();
49
+ const result = await shell.exec([command, ...args], {
50
+ cwd: options.cwd,
51
+ env,
52
+ inheritEnv: false,
53
+ timeout: 12e4,
54
+ onOutput(text, _context, info) {
55
+ bytes += new TextEncoder().encode(text).byteLength;
56
+ if (bytes > 4194304) {
57
+ outputLimit.abort(/* @__PURE__ */ new Error("Git engine command output exceeded 4 MiB."));
58
+ return;
59
+ }
60
+ if (info.stream === "stdout") stdout += text;
61
+ else stderr += text;
62
+ }
63
+ }, withAbortSignal(AbortSignal.any([operationSignal, outputLimit.signal]), BACKGROUND_CONTEXT));
64
+ outputLimit.signal.throwIfAborted();
65
+ operationSignal.throwIfAborted();
66
+ if (!result.ok) throw result.error;
67
+ return {
68
+ exitCode: result.value.exitCode,
69
+ stdout,
70
+ stderr
71
+ };
72
+ } };
73
+ },
74
+ logger: {
75
+ info: (message) => console.info(message),
76
+ warn: (message) => console.warn(message),
77
+ error: (message) => console.error(message)
78
+ }
79
+ });
80
+ return requirePoServerScope(scoped).provide(GIT_ENGINE_CONTRACT, engine);
81
+ });
82
+ return { value: void 0 };
83
+ });
84
+ //#endregion
13
85
  //#region src/schemas/runWorktreeTool.ts
14
86
  /**
15
87
  * The tool's action vocabulary.
@@ -26,7 +98,10 @@ const WORKTREE_ACTIONS = {
26
98
  merge: "merge",
27
99
  prune: "prune",
28
100
  send: "send",
29
- messages: "messages"
101
+ messages: "messages",
102
+ profiles: "profiles",
103
+ expand: "expand",
104
+ reapply: "reapply"
30
105
  };
31
106
  /**
32
107
  * Which fields each action accepts.
@@ -41,7 +116,8 @@ const WORKTREE_ACTION_FIELDS = {
41
116
  "branch",
42
117
  "baseRef",
43
118
  "task",
44
- "name"
119
+ "name",
120
+ "sparseProfile"
45
121
  ],
46
122
  close_worktree: [
47
123
  "action",
@@ -61,12 +137,20 @@ const WORKTREE_ACTION_FIELDS = {
61
137
  "id",
62
138
  "message"
63
139
  ],
64
- messages: ["action", "id"]
140
+ messages: ["action", "id"],
141
+ profiles: ["action", "baseRef"],
142
+ expand: [
143
+ "action",
144
+ "id",
145
+ "folders"
146
+ ],
147
+ reapply: ["action", "id"]
65
148
  };
66
149
  const SpawnParams = Type.Object({
67
150
  action: Type.Literal(WORKTREE_ACTIONS.spawn_worktree),
68
151
  branch: Type.String({ minLength: 1 }),
69
152
  baseRef: Type.Optional(Type.String({ minLength: 1 })),
153
+ sparseProfile: Type.Optional(Type.String({ minLength: 1 })),
70
154
  task: Type.Optional(Type.String({ minLength: 1 })),
71
155
  name: Type.Optional(Type.String({ minLength: 1 }))
72
156
  }, { additionalProperties: false });
@@ -106,7 +190,20 @@ Type.Union([
106
190
  MergeParams,
107
191
  PruneParams,
108
192
  SendParams,
109
- MessagesParams
193
+ MessagesParams,
194
+ Type.Object({
195
+ action: Type.Literal("profiles"),
196
+ baseRef: Type.Optional(Type.String({ minLength: 1 }))
197
+ }, { additionalProperties: false }),
198
+ Type.Object({
199
+ action: Type.Literal("expand"),
200
+ id: Type.String({ minLength: 1 }),
201
+ folders: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })
202
+ }, { additionalProperties: false }),
203
+ Type.Object({
204
+ action: Type.Literal("reapply"),
205
+ id: Type.String({ minLength: 1 })
206
+ }, { additionalProperties: false })
110
207
  ]);
111
208
  /** The actions that accept `field`, so the declared docs cannot drift from the validator. */
112
209
  function acceptingActions(field) {
@@ -136,6 +233,14 @@ const RunWorktreeToolSchema = Type.Object({
136
233
  minLength: 1,
137
234
  description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions("baseRef")}.`
138
235
  })),
236
+ sparseProfile: Type.Optional(Type.String({
237
+ minLength: 1,
238
+ description: "Sparse checkout profile, independent of the launch profile."
239
+ })),
240
+ folders: Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
241
+ minItems: 1,
242
+ description: "Relative cone folders for expand."
243
+ })),
139
244
  task: Type.Optional(Type.String({
140
245
  minLength: 1,
141
246
  description: `First message for the new session. Actions: ${acceptingActions("task")}.`
@@ -163,6 +268,9 @@ const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its
163
268
 
164
269
  Actions:
165
270
  - spawn_worktree: create a worktree on a new branch and start a session in it. Requires 'branch'. Optional 'baseRef' (defaults to the current branch's remote-tracking ref, then the remote default branch), 'name' for the rail, 'task' as the first message.
271
+ - profiles: list sparse checkout profiles at baseRef.
272
+ - expand: add folders to a sparse worktree. Requires 'id' and 'folders'.
273
+ - reapply: refresh a sparse worktree from HEAD. Requires 'id'.
166
274
  - close_worktree: stop a worktree's session and delete its checkout. Requires 'id'. Refuses a dirty tree unless 'force' is true.
167
275
  - list: every worktree for this repository, with status and relationship to the calling session.
168
276
  - status: one worktree, its relationship to the calling session, and its uncommitted files. Requires 'id'.
@@ -190,12 +298,14 @@ function validateParams(input) {
190
298
  "baseRef",
191
299
  "name",
192
300
  "task",
193
- "message"
301
+ "message",
302
+ "sparseProfile"
194
303
  ]) if (field in record && (typeof record[field] !== "string" || record[field].trim() === "")) throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);
304
+ if (action === "expand" && (!Array.isArray(record.folders) || record.folders.length === 0 || !record.folders.every((folder) => typeof folder === "string" && folder.trim() !== ""))) throw invalidRequest("expand requires nonempty folders.", "Pass relative cone folders.");
195
305
  for (const field of ["force", "dryRun"]) if (field in record && typeof record[field] !== "boolean") throw invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);
196
306
  if (action === WORKTREE_ACTIONS.send && typeof record.message !== "string") throw invalidRequest("action='send' requires 'message'.", "Pass the message to send.");
197
307
  if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== "string") throw invalidRequest("action='spawn_worktree' requires 'branch'.", "Name the branch to create.");
198
- if ((action === WORKTREE_ACTIONS.close_worktree || action === WORKTREE_ACTIONS.status || action === WORKTREE_ACTIONS.merge || action === WORKTREE_ACTIONS.send || action === WORKTREE_ACTIONS.messages) && typeof record.id !== "string") throw invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
308
+ if ((action === WORKTREE_ACTIONS.expand || action === WORKTREE_ACTIONS.reapply || action === WORKTREE_ACTIONS.close_worktree || action === WORKTREE_ACTIONS.status || action === WORKTREE_ACTIONS.merge || action === WORKTREE_ACTIONS.send || action === WORKTREE_ACTIONS.messages) && typeof record.id !== "string") throw invalidRequest(`action='${action}' requires 'id'.`, "Call list to see the current ids.");
199
309
  return record;
200
310
  }
201
311
  function describe(record, sessionId) {
@@ -210,9 +320,31 @@ function text(...lines) {
210
320
  }
211
321
  async function executeRunWorktreeTool(params, operations, context, options = {}) {
212
322
  switch (params.action) {
323
+ case WORKTREE_ACTIONS.profiles: {
324
+ const profiles = await operations.profiles(context, params.baseRef, options);
325
+ return {
326
+ content: text(profiles.sparseProfiles?.join(", ") ?? "Sparse checkout is not configured."),
327
+ details: {
328
+ action: params.action,
329
+ ...profiles
330
+ }
331
+ };
332
+ }
333
+ case WORKTREE_ACTIONS.expand:
334
+ case WORKTREE_ACTIONS.reapply: {
335
+ const record = params.action === "expand" ? await operations.expand(context, params.id, params.folders, options) : await operations.reapply(context, params.id, options);
336
+ return {
337
+ content: text(`Worktree ${record.id} sparse checkout updated.`),
338
+ details: {
339
+ action: params.action,
340
+ records: [record]
341
+ }
342
+ };
343
+ }
213
344
  case WORKTREE_ACTIONS.spawn_worktree: {
214
345
  const record = await operations.spawn(context, {
215
346
  branch: params.branch,
347
+ ...params.sparseProfile === void 0 ? {} : { sparseProfile: params.sparseProfile },
216
348
  ...params.baseRef === void 0 ? {} : { baseRef: params.baseRef },
217
349
  ...params.name === void 0 ? {} : { name: params.name },
218
350
  ...params.task === void 0 ? {} : { task: params.task }
@@ -310,14 +442,19 @@ interface Worktree {
310
442
  id: string;
311
443
  branch: string;
312
444
  baseRef: string;
313
- /** Absolute path of the checkout, under ~/.po/git/worktrees. */
445
+ /** Absolute path of the checkout. Imported worktrees stay at their original path. */
314
446
  path: string;
315
447
  repositoryRoot: string;
316
448
  /** The session running inside the worktree. */
317
449
  sessionId: string;
318
450
  parentSessionId?: string;
319
451
  status: WorktreeStatus;
452
+ /** started confirms runner launch only; unconfirmed handoffs must not be blindly retried. */
453
+ setupStage?: 'none' | 'started' | 'failed' | 'unconfirmed';
320
454
  createdAt: string;
455
+ sparseProfile?: string;
456
+ extraFolders?: string[];
457
+ sparseFingerprint?: string;
321
458
  /** How your session relates to it: 'parent' spawned it, 'child' runs inside it, 'other' is neither. */
322
459
  relationship: 'parent' | 'child' | 'other';
323
460
  }
@@ -350,7 +487,12 @@ declare const worktrees: {
350
487
  * the current branch's remote-tracking ref, then the remote default branch; name labels it in the rail; task is
351
488
  * the new session's first message. Setup can be slow, so give exec a larger timeoutMs.
352
489
  */
353
- spawn(request: { branch: string; baseRef?: string; name?: string; task?: string }): Promise<Worktree>;
490
+ spawn(request: { branch: string; baseRef?: string; name?: string; task?: string; sparseProfile?: string }): Promise<Worktree>;
491
+ /** Run a repository workflow in its own checkout. Retrying the same attemptId never recreates uncertain work. */
492
+ startWorkflow(request: { key: string; attemptId?: string; branch?: string; sparseProfile?: string; inputs?: Record<string, string> }): Promise<{ attemptId: string; worktreeId: string; sessionId: string; branch: string; runId?: string; admission: 'pending' | 'registered' }>;
493
+ profiles(options?: { baseRef?: string }): Promise<{ sparseProfiles?: string[]; defaultSparseProfile?: string }>;
494
+ expand(id: string, folders: string[]): Promise<Worktree>;
495
+ reapply(id: string): Promise<Worktree>;
354
496
  /** Stop the worktree's session and delete its checkout. Refused on a dirty tree unless force is true. */
355
497
  close(id: string, options?: { force?: boolean }): Promise<Worktree>;
356
498
  /** Merge the worktree's branch into this checkout. Refused when this checkout is dirty. */
@@ -370,7 +512,7 @@ const json = (value) => JSON.parse(JSON.stringify(value));
370
512
  function createWorktreeNamespace(options) {
371
513
  return {
372
514
  name: "worktrees",
373
- summary: "Git worktrees, each with its own Po session nested under this one: worktrees.list, status, spawn, close, merge, prune, send and messages.",
515
+ summary: "Create and manage Git worktree sessions, select or expand a sparse checkout, and start isolated repository workflows.",
374
516
  declarations: DECLARATIONS,
375
517
  bind(run) {
376
518
  if (run.sessionId !== options.execution.sessionId) throw new Error("Worktrees namespace belongs to another session.");
@@ -383,13 +525,15 @@ function createWorktreeNamespace(options) {
383
525
  relationship: record.parentSessionId === options.execution.sessionId ? "parent" : record.sessionId === options.execution.sessionId ? "child" : "other"
384
526
  });
385
527
  /** One `run_worktree` action through the tool's own code, so the tool and the namespace cannot drift. */
386
- const act = async (name, action, input) => {
528
+ const act = async (name, action, input = {}, target) => {
387
529
  run.signal.throwIfAborted();
388
530
  if (disposed) throw new Error("Worktrees namespace run is disposed.");
389
531
  options.assertAvailable();
532
+ if (typeof input !== "object" || input === null || Array.isArray(input) || "action" in input) throw invalidRequest(`Invalid options for worktrees.${name}.`, "Pass the documented fields without an action.");
390
533
  const params = validateParams({
391
- action,
392
- ...typeof input === "object" && input !== null ? input : {}
534
+ ...input,
535
+ ...target,
536
+ action
393
537
  });
394
538
  const context = {
395
539
  cwd: options.execution.cwd,
@@ -422,6 +566,15 @@ function createWorktreeNamespace(options) {
422
566
  };
423
567
  const record = (result) => view(result.details.records[0]);
424
568
  const members = Object.create(null);
569
+ members.profiles = async (settings) => {
570
+ const { action: _action, ...profiles } = (await act("profiles", "profiles", settings)).details;
571
+ return json(profiles);
572
+ };
573
+ members.expand = async (id, folders) => json(record(await act("expand", "expand", {
574
+ id,
575
+ folders
576
+ })));
577
+ members.reapply = async (id) => json(record(await act("reapply", "reapply", { id })));
425
578
  members.list = async () => json((await act("list", "list", {})).details.records.map(view));
426
579
  members.status = async (id) => {
427
580
  const { details } = await act("status", "status", { id });
@@ -431,14 +584,36 @@ function createWorktreeNamespace(options) {
431
584
  });
432
585
  };
433
586
  members.spawn = async (request) => json(record(await act("spawn", "spawn_worktree", request)));
434
- members.close = async (id, settings) => json(record(await act("close", "close_worktree", {
435
- ...settings,
436
- id
437
- })));
438
- members.merge = async (id, settings) => json(record(await act("merge", "merge", {
439
- ...settings,
440
- id
441
- })));
587
+ members.startWorkflow = async (request) => {
588
+ run.signal.throwIfAborted();
589
+ if (disposed) throw new Error("Worktrees namespace run is disposed.");
590
+ options.assertAvailable();
591
+ if (!Check(StartWorktreeWorkflowSchema, request)) throw new Error("A repository workflow key and valid launch fields are required.");
592
+ const workflows = options.workflows?.();
593
+ if (!workflows) throw new Error("Isolated workflow admissions are unavailable in this session.");
594
+ const attemptId = request.attemptId ?? `git-${randomUUID()}`;
595
+ const started = await workflows.start({
596
+ attemptId,
597
+ definition: {
598
+ source: "repo",
599
+ key: request.key
600
+ },
601
+ ...request.branch === void 0 ? {} : { branch: request.branch },
602
+ ...request.sparseProfile === void 0 ? {} : { sparseProfile: request.sparseProfile },
603
+ ...request.inputs === void 0 ? {} : { overrides: { inputs: request.inputs } }
604
+ }, run.signal);
605
+ options.assertAvailable();
606
+ return json({
607
+ attemptId,
608
+ worktreeId: started.worktreeId,
609
+ sessionId: started.sessionId,
610
+ branch: started.branch,
611
+ admission: started.admission.state,
612
+ ...started.admission.state === "registered" ? { runId: started.admission.run.runId } : {}
613
+ });
614
+ };
615
+ members.close = async (id, settings) => json(record(await act("close", "close_worktree", settings, { id })));
616
+ members.merge = async (id, settings) => json(record(await act("merge", "merge", settings, { id })));
442
617
  members.prune = async (settings) => {
443
618
  const { plan } = (await act("prune", "prune", settings)).details;
444
619
  return json({
@@ -460,6 +635,368 @@ function createWorktreeNamespace(options) {
460
635
  };
461
636
  }
462
637
  //#endregion
638
+ //#region src/services/worktreeWorkflows/index.ts
639
+ var WorktreeWorkflowError = class extends Error {
640
+ code;
641
+ constructor(code, message, options) {
642
+ super(message, options);
643
+ this.code = code;
644
+ this.name = "WorktreeWorkflowError";
645
+ }
646
+ };
647
+ function canonical(value) {
648
+ if (Array.isArray(value)) return value.map(canonical);
649
+ if (value === null || typeof value !== "object") return value;
650
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
651
+ }
652
+ function defaultBranch(input) {
653
+ const safe = (value) => value.replace(/[^A-Za-z0-9._-]+/gu, "-").replace(/^[.-]+|[.-]+$/gu, "") || "run";
654
+ return `wf/${safe(path.basename(input.definition.key, path.extname(input.definition.key)))}/${safe(input.attemptId)}`;
655
+ }
656
+ function remoteBase(record) {
657
+ const ref = record.baseRef.replace(/^refs\/remotes\//u, "");
658
+ const slash = ref.indexOf("/");
659
+ if (slash < 1 || !record.baseCommit) return void 0;
660
+ const remote = ref.slice(0, slash);
661
+ const branch = ref.slice(slash + 1);
662
+ return validRefName(remote) && validRefName(branch) ? {
663
+ remote,
664
+ branch,
665
+ sha: record.baseCommit
666
+ } : void 0;
667
+ }
668
+ /** One coordinator over the existing admissions/runs services, never a second workflow engine. */
669
+ function createWorktreeWorkflows(options) {
670
+ if (!options.sessionId.trim()) throw new Error("A workflow launcher session is required.");
671
+ const context = {
672
+ cwd: options.cwd,
673
+ sessionId: options.sessionId
674
+ };
675
+ const watching = /* @__PURE__ */ new Map();
676
+ const inFlight = /* @__PURE__ */ new Map();
677
+ options.signal.addEventListener("abort", () => {
678
+ for (const stop of watching.values()) stop();
679
+ watching.clear();
680
+ }, { once: true });
681
+ const operation = (signal) => ({
682
+ env: options.environment,
683
+ signal: AbortSignal.any([options.signal, ...signal ? [signal] : []])
684
+ });
685
+ const store = async () => {
686
+ const root = await options.git.repositoryRoot(options.cwd);
687
+ if (!root) throw new WorktreeWorkflowError("not_started", "A repository checkout is required.");
688
+ return options.registry ? options.registry(root) : createWorktreeRegistry(await registryFile(root, options.homeDirectory, options.environment));
689
+ };
690
+ const mutate = async (fn, signal) => {
691
+ const registry = await store();
692
+ return registry.transaction(async () => {
693
+ const attempts = await registry.workflowAttempts();
694
+ const result = await fn(attempts);
695
+ await registry.replaceWorkflowAttempts(attempts);
696
+ return result;
697
+ }, operation(signal).signal);
698
+ };
699
+ const update = (attempt, signal) => mutate((attempts) => {
700
+ const index = attempts.findIndex((entry) => entry.launcherSessionId === options.sessionId && entry.attemptId === attempt.attemptId);
701
+ if (index < 0 || attempts[index].fingerprint !== attempt.fingerprint) throw new WorktreeWorkflowError("unknown", "The durable workflow intent changed.");
702
+ attempts[index] = structuredClone(attempt);
703
+ }, signal);
704
+ const ownRecords = async () => (await options.operations.list(context)).filter((record) => record.parentSessionId === options.sessionId && record.workflow);
705
+ const retain = async (record, reason) => {
706
+ await options.operations.linkWorkflow(context, record.id, {
707
+ ...record.workflow,
708
+ state: "retained",
709
+ reason
710
+ });
711
+ };
712
+ const settle = async (record, attempt, state) => {
713
+ try {
714
+ const admission = attempt.admission;
715
+ if (admission?.state !== "registered" || JSON.stringify(canonical(state.run)) !== JSON.stringify(canonical(admission.run)) || state.run.ownerSessionId !== record.sessionId) return;
716
+ const current = (await ownRecords()).find((entry) => entry.id === record.id);
717
+ if (!current || current.sessionId !== record.sessionId || current.path !== record.path || current.status !== "running" || current.workflow?.state !== "admitted" || current.workflow?.runId !== state.run.runId || current.workflow.admissionId !== admission.admissionId || current.workflow.attemptId !== attempt.attemptId || current.workflow.fingerprint !== attempt.fingerprint) return;
718
+ let reason;
719
+ let verifiedHead;
720
+ if (state.stage !== "completed" || state.outcome !== "success") reason = `The run ended ${state.outcome ?? state.stage}.`;
721
+ else if (await options.git.repositoryRoot(current.path) !== current.path || await options.git.currentBranch(current.path) !== current.branch || !(await options.git.listWorktreePaths(current.repositoryRoot)).includes(current.path)) reason = "The exact linked checkout could not be verified.";
722
+ else if ((await options.git.dirtyFiles(current.path)).length > 0) reason = "Uncommitted files remain.";
723
+ else {
724
+ const head = await options.git.revision(current.path, "HEAD", operation());
725
+ verifiedHead = head;
726
+ if (!current.baseCommit) reason = "The original commit is unknown.";
727
+ else if (head !== current.baseCommit) {
728
+ const base = remoteBase(current);
729
+ if (!base || await options.git.remoteBranchHead(current.path, base.remote, current.branch, operation()) !== head) reason = "Delivery of this exact branch HEAD could not be verified.";
730
+ }
731
+ }
732
+ if (reason) {
733
+ await retain(current, reason);
734
+ await update({
735
+ ...attempt,
736
+ state: "retained"
737
+ });
738
+ } else {
739
+ await options.operations.close(context, current.id, false, {
740
+ ...current.workflow,
741
+ sessionId: current.sessionId,
742
+ path: current.path,
743
+ head: verifiedHead
744
+ });
745
+ await update({
746
+ ...attempt,
747
+ state: "closed"
748
+ });
749
+ }
750
+ } catch (error) {
751
+ options.onError(error);
752
+ }
753
+ };
754
+ const watch = (record, attempt) => {
755
+ const admission = attempt.admission;
756
+ if (admission?.state !== "registered" || watching.has(record.id) || options.signal.aborted) return;
757
+ const runs = options.runs();
758
+ if (!runs) return;
759
+ let stopped = false;
760
+ let unsubscribe;
761
+ const stop = () => {
762
+ stopped = true;
763
+ unsubscribe?.();
764
+ watching.delete(record.id);
765
+ };
766
+ watching.set(record.id, stop);
767
+ unsubscribe = runs.subscribe(admission.run.runId, (state) => {
768
+ if (stopped || state.stage === "running") return;
769
+ if (JSON.stringify(canonical(state.run)) !== JSON.stringify(canonical(admission.run))) return;
770
+ stop();
771
+ settle(record, attempt, state);
772
+ });
773
+ if (stopped) unsubscribe();
774
+ };
775
+ const link = async (record, attempt, admission) => {
776
+ if (admission.attemptId !== attempt.attemptId || admission.state === "registered" && admission.run.ownerSessionId !== record.sessionId) throw new WorktreeWorkflowError("unknown", "The admission does not belong to this checkout session.");
777
+ if (record.workflow?.admissionId && record.workflow.admissionId !== admission.admissionId || record.workflow?.runId && (admission.state !== "registered" || record.workflow.runId !== admission.run.runId) || attempt.admission && attempt.admission.admissionId !== admission.admissionId) throw new WorktreeWorkflowError("unknown", "The recorded workflow admission identity changed. The checkout was kept.");
778
+ if (record.workflow?.state === "retained" || [
779
+ "retained",
780
+ "closed",
781
+ "rejected"
782
+ ].includes(attempt.state)) {
783
+ if (admission.state === "rejected") throw new WorktreeWorkflowError("not_started", "This rejected attempt remains retained.");
784
+ return {
785
+ worktreeId: record.id,
786
+ sessionId: record.sessionId,
787
+ branch: record.branch,
788
+ admission
789
+ };
790
+ }
791
+ const linked = {
792
+ attemptId: attempt.attemptId,
793
+ fingerprint: attempt.fingerprint,
794
+ state: admission.state === "rejected" ? "retained" : "admitted",
795
+ admissionId: admission.admissionId,
796
+ ...admission.state === "registered" ? { runId: admission.run.runId } : {},
797
+ ...admission.state === "rejected" ? { reason: `Admission rejected: ${admission.errors.join("; ")}` } : {}
798
+ };
799
+ await options.operations.linkWorkflow(context, record.id, linked);
800
+ const updated = {
801
+ ...attempt,
802
+ admission,
803
+ state: admission.state === "rejected" ? "rejected" : "admitted",
804
+ worktreeId: record.id,
805
+ sessionId: record.sessionId
806
+ };
807
+ await update(updated);
808
+ if (admission.state === "rejected") throw new WorktreeWorkflowError("not_started", "The workflow admission was rejected. The checkout was kept.");
809
+ watch({
810
+ ...record,
811
+ workflow: linked
812
+ }, updated);
813
+ return {
814
+ worktreeId: record.id,
815
+ sessionId: record.sessionId,
816
+ branch: record.branch,
817
+ admission
818
+ };
819
+ };
820
+ const start = async (input, branch, fingerprint, signal) => {
821
+ const admissions = options.admissions();
822
+ if (!admissions) throw new WorktreeWorkflowError("not_started", "Workflow admissions are unavailable.");
823
+ const records = await ownRecords();
824
+ const legacy = records.find((record) => record.workflow.attemptId === input.attemptId);
825
+ const { attempt, created } = await mutate((attempts) => {
826
+ let attempt = attempts.find((entry) => entry.launcherSessionId === options.sessionId && entry.attemptId === input.attemptId);
827
+ if (!attempt && legacy) {
828
+ attempt = {
829
+ attemptId: input.attemptId,
830
+ fingerprint: legacy.workflow.fingerprint,
831
+ launcherSessionId: options.sessionId,
832
+ branch: legacy.branch,
833
+ definition: input.definition,
834
+ createdAt: legacy.createdAt,
835
+ state: "spawned",
836
+ worktreeId: legacy.id,
837
+ sessionId: legacy.sessionId
838
+ };
839
+ attempts.push(attempt);
840
+ }
841
+ if (attempt) {
842
+ if (attempt.fingerprint !== fingerprint) throw new WorktreeWorkflowError("attempt_conflict", "This workflow attempt was started with different arguments.");
843
+ return {
844
+ attempt: structuredClone(attempt),
845
+ created: false
846
+ };
847
+ }
848
+ attempt = {
849
+ attemptId: input.attemptId,
850
+ fingerprint,
851
+ launcherSessionId: options.sessionId,
852
+ branch,
853
+ definition: input.definition,
854
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
855
+ state: "reserved"
856
+ };
857
+ attempts.push(attempt);
858
+ return {
859
+ attempt: structuredClone(attempt),
860
+ created: true
861
+ };
862
+ }, signal);
863
+ let record = records.find((entry) => entry.id === attempt.worktreeId) ?? legacy;
864
+ if (!created) {
865
+ if (!record || record.status === "orphaned") {
866
+ if (attempt.state === "rejected" && !record) throw new WorktreeWorkflowError("not_started", "This attempt was rejected before checkout creation. Use a new attempt identity after fixing it.");
867
+ if (attempt.state === "closed" && attempt.admission && attempt.worktreeId && attempt.sessionId) return {
868
+ worktreeId: attempt.worktreeId,
869
+ sessionId: attempt.sessionId,
870
+ branch: attempt.branch,
871
+ admission: attempt.admission
872
+ };
873
+ throw new WorktreeWorkflowError("unknown", "This attempt may have created work. Its checkout is absent or orphaned and will not be recreated.");
874
+ }
875
+ const admission = await admissions.read(input.attemptId);
876
+ if (!admission) throw new WorktreeWorkflowError("unknown", "This attempt has no authoritative admission outcome. Its checkout was kept.");
877
+ return link(record, attempt, admission);
878
+ }
879
+ let report;
880
+ try {
881
+ report = await admissions.validate({
882
+ kind: "launch",
883
+ definition: input.definition,
884
+ ...input.overrides ? { overrides: input.overrides } : {}
885
+ });
886
+ } catch (error) {
887
+ await update({
888
+ ...attempt,
889
+ state: "rejected"
890
+ }, signal);
891
+ throw new WorktreeWorkflowError("not_started", "Workflow validation failed before checkout creation.", { cause: error });
892
+ }
893
+ if (report.errors.length || report.allocation && JSON.stringify(canonical(report.allocation)) !== JSON.stringify(canonical(input.overrides?.allocation))) {
894
+ await update({
895
+ ...attempt,
896
+ state: "rejected"
897
+ }, signal);
898
+ throw new WorktreeWorkflowError("not_started", "Workflow validation failed or its prepared allocation changed.");
899
+ }
900
+ operation(signal).signal.throwIfAborted();
901
+ try {
902
+ record = await options.operations.spawn(context, {
903
+ branch,
904
+ ...input.sparseProfile ? { sparseProfile: input.sparseProfile } : {}
905
+ }, {
906
+ workflow: {
907
+ attemptId: input.attemptId,
908
+ fingerprint
909
+ },
910
+ ...input.preset ? { preset: input.preset } : {},
911
+ signal: operation(signal).signal
912
+ });
913
+ await update({
914
+ ...attempt,
915
+ worktreeId: record.id,
916
+ sessionId: record.sessionId,
917
+ state: "spawned"
918
+ });
919
+ const base = remoteBase(record);
920
+ if (!base) throw new WorktreeWorkflowError("not_started", "The workflow base is not a verifiable remote branch. The checkout was kept.");
921
+ const pending = {
922
+ ...attempt,
923
+ worktreeId: record.id,
924
+ sessionId: record.sessionId,
925
+ state: "admitting"
926
+ };
927
+ await update(pending);
928
+ const admission = await admissions.launch(input.attemptId, input.definition, {
929
+ ...input.overrides,
930
+ env: {
931
+ ...input.overrides?.env,
932
+ SPARO_BASE_REMOTE: base.remote,
933
+ SPARO_BASE_BRANCH: base.branch,
934
+ SPARO_BASE_SHA: base.sha,
935
+ SPARO_BRANCH: record.branch,
936
+ PO_GIT_BASE_REMOTE: base.remote,
937
+ PO_GIT_BASE_BRANCH: base.branch,
938
+ PO_GIT_BASE_SHA: base.sha,
939
+ PO_GIT_BRANCH: record.branch
940
+ },
941
+ targetSessionId: record.sessionId
942
+ });
943
+ return await link(record, pending, admission);
944
+ } catch (error) {
945
+ if (error instanceof WorktreeWorkflowError) throw error;
946
+ throw new WorktreeWorkflowError("unknown", "The workflow launch outcome is uncertain. Inspect the saved attempt before retrying.", { cause: error });
947
+ }
948
+ };
949
+ return {
950
+ start(input, signal) {
951
+ options.signal.throwIfAborted();
952
+ signal?.throwIfAborted();
953
+ if (!input || typeof input.attemptId !== "string" || !input.attemptId.trim() || !Check(PoWorkflowDefinitionRefSchema, input.definition) || input.definition.source !== "repo" || input.sparseProfile !== void 0 && !validSparseProfile(input.sparseProfile)) return Promise.reject(new WorktreeWorkflowError("not_started", "A valid repository workflow and attempt identity are required."));
954
+ const snapshot = structuredClone(input);
955
+ const branch = snapshot.branch ?? defaultBranch(snapshot);
956
+ if (!validRefName(branch)) return Promise.reject(new WorktreeWorkflowError("not_started", "The workflow branch is invalid."));
957
+ const fingerprint = createHash("sha256").update(JSON.stringify(canonical({
958
+ definition: snapshot.definition,
959
+ branch,
960
+ profile: snapshot.sparseProfile,
961
+ preset: snapshot.preset,
962
+ overrides: snapshot.overrides
963
+ }))).digest("hex");
964
+ const existing = inFlight.get(snapshot.attemptId);
965
+ if (existing) return existing.fingerprint === fingerprint ? existing.promise : Promise.reject(new WorktreeWorkflowError("attempt_conflict", "This workflow attempt is already starting with different arguments."));
966
+ const promise = start(snapshot, branch, fingerprint, signal).finally(() => {
967
+ inFlight.delete(snapshot.attemptId);
968
+ });
969
+ inFlight.set(snapshot.attemptId, {
970
+ fingerprint,
971
+ promise
972
+ });
973
+ return promise;
974
+ },
975
+ async reconcile(signal) {
976
+ operation(signal).signal.throwIfAborted();
977
+ const admissions = options.admissions();
978
+ if (!admissions) return;
979
+ const records = await ownRecords();
980
+ const registry = await store();
981
+ const attempts = await registry.transaction(() => registry.workflowAttempts(), operation(signal).signal);
982
+ for (const attempt of attempts.filter((entry) => entry.launcherSessionId === options.sessionId && ![
983
+ "closed",
984
+ "rejected",
985
+ "retained"
986
+ ].includes(entry.state))) {
987
+ const record = records.find((entry) => entry.id === attempt.worktreeId || entry.workflow.attemptId === attempt.attemptId);
988
+ if (!record || record.status === "orphaned") continue;
989
+ try {
990
+ const admission = await admissions.read(attempt.attemptId);
991
+ if (admission) await link(record, attempt, admission);
992
+ } catch (error) {
993
+ options.onError(error);
994
+ }
995
+ }
996
+ }
997
+ };
998
+ }
999
+ //#endregion
463
1000
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
464
1001
  function progressResult(action, label) {
465
1002
  return {
@@ -479,18 +1016,66 @@ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
479
1016
  "discover",
480
1017
  "load_skill"
481
1018
  ]);
482
- function createGitSession({ context, host: serverHost, agent, signal }) {
1019
+ async function createGitSession({ context, host: serverHost, agent, signal }) {
483
1020
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
484
1021
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
485
1022
  const sessionId = serverHost.context.sessionId;
486
1023
  const directEvents = serverHost.context.directEvents;
487
1024
  const messageInbox = createWorktreeMessageInbox(directEvents, sessionId);
1025
+ const setupReceiver = context.inject(["po/runner-launch"], (child) => {
1026
+ const runner = child.get("po/runner-launch");
1027
+ const cwd = serverHost.context.cwd;
1028
+ if (!runner || !cwd) return void 0;
1029
+ return receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal);
1030
+ });
488
1031
  const operations = createWorktreeOperations({
489
1032
  git: createWorktreeGit(),
1033
+ ...createGitOperationDependencies({
1034
+ context,
1035
+ host: serverHost,
1036
+ signal
1037
+ }),
490
1038
  sessionService: serverHost.context.sessionService,
491
1039
  messageInbox,
492
1040
  sessionDelivery: () => readPoSessionDelivery(context)
493
1041
  });
1042
+ const homeDirectory = serverHost.context.homeDirectory ?? serverHost.context.environment?.HOME;
1043
+ let workflows;
1044
+ const workflowProvider = context.inject([PO_SERVER_SCOPE_SERVICE], async (scoped) => {
1045
+ if (!homeDirectory || !serverHost.context.cwd) return void 0;
1046
+ const lifetime = new AbortController();
1047
+ const service = createWorktreeWorkflows({
1048
+ sessionId,
1049
+ cwd: serverHost.context.cwd,
1050
+ homeDirectory,
1051
+ environment: serverHost.context.environment ?? {},
1052
+ signal: AbortSignal.any([signal, lifetime.signal]),
1053
+ operations,
1054
+ git: {
1055
+ ...createWorktreeGit(),
1056
+ revision,
1057
+ remoteBranchHead
1058
+ },
1059
+ admissions: () => readPoWorkflowAdmissionsService(scoped),
1060
+ runs: () => readPoWorkflowRunsService(scoped),
1061
+ onError: (error) => serverHost.context.onNotice(`Workflow checkout retained (${error instanceof Error ? error.name : "unknown error"}).`)
1062
+ });
1063
+ const release = await requirePoServerScope(scoped).provide(GIT_WORKFLOWS_CONTRACT, service);
1064
+ workflows = service;
1065
+ return async () => {
1066
+ if (workflows === service) workflows = void 0;
1067
+ lifetime.abort();
1068
+ await release();
1069
+ };
1070
+ });
1071
+ if (context.get(PO_SERVER_SCOPE_SERVICE) !== void 0) await workflowProvider.await();
1072
+ const workflowServices = context.inject([PO_WORKFLOW_ADMISSIONS_SERVICE, PO_WORKFLOW_RUNS_SERVICE], async () => {
1073
+ try {
1074
+ await workflows?.reconcile();
1075
+ } catch (error) {
1076
+ serverHost.context.onNotice(`Workflow reconciliation deferred (${error instanceof Error ? error.name : "unknown error"}).`);
1077
+ }
1078
+ });
494
1079
  const resources = [{
495
1080
  name: "codemode-how-to-git",
496
1081
  description: "Hand a branch of work to a separate session in its own checkout, keeping the current checkout untouched. Use for a long refactor, a risky migration, or parallel features that touch the same files; not for parallel work on one branch.",
@@ -527,6 +1112,7 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
527
1112
  if (agent) {
528
1113
  const namespace = createWorktreeNamespace({
529
1114
  operations,
1115
+ workflows: () => workflows,
530
1116
  execution: agent.context,
531
1117
  assertAvailable: () => {
532
1118
  if (signal?.aborted) throw new Error("Git session is unavailable.");
@@ -549,7 +1135,12 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
549
1135
  tool,
550
1136
  hooks
551
1137
  },
552
- onDispose: () => messageInbox.close()
1138
+ onDispose: async () => {
1139
+ await workflowServices.dispose();
1140
+ await workflowProvider.dispose();
1141
+ await setupReceiver.dispose();
1142
+ messageInbox.close();
1143
+ }
553
1144
  };
554
1145
  }
555
1146
  const root = defineRoot(createGitSession);
@@ -588,12 +1179,12 @@ async function read(cwd, args) {
588
1179
  const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
589
1180
  return result.code === 0 ? result.stdout : void 0;
590
1181
  }
591
- async function readLine$1(cwd, args) {
1182
+ async function readLine(cwd, args) {
592
1183
  const out = (await read(cwd, args))?.trim();
593
1184
  return out === void 0 || out === "" ? void 0 : out;
594
1185
  }
595
1186
  async function commitExists(cwd, ref) {
596
- return await readLine$1(cwd, [
1187
+ return await readLine(cwd, [
597
1188
  "rev-parse",
598
1189
  "--verify",
599
1190
  "--quiet",
@@ -602,7 +1193,7 @@ async function commitExists(cwd, ref) {
602
1193
  }
603
1194
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
604
1195
  async function upstreamOf(cwd, ref) {
605
- return readLine$1(cwd, [
1196
+ return readLine(cwd, [
606
1197
  "rev-parse",
607
1198
  "--abbrev-ref",
608
1199
  "--symbolic-full-name",
@@ -611,13 +1202,13 @@ async function upstreamOf(cwd, ref) {
611
1202
  }
612
1203
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
613
1204
  async function resolveBaseRef(cwd, branch, recordedBaseRef) {
614
- if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine$1(cwd, [
1205
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
615
1206
  "rev-parse",
616
1207
  "--verify",
617
1208
  "--quiet",
618
1209
  `refs/heads/${recordedBaseRef}`
619
1210
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
620
- const originHead = await readLine$1(cwd, [
1211
+ const originHead = await readLine(cwd, [
621
1212
  "symbolic-ref",
622
1213
  "--quiet",
623
1214
  "--short",
@@ -631,7 +1222,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
631
1222
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
632
1223
  const head = await commitExists(cwd, "HEAD");
633
1224
  if (ref !== void 0 && head) {
634
- const mergeBase = await readLine$1(cwd, [
1225
+ const mergeBase = await readLine(cwd, [
635
1226
  "merge-base",
636
1227
  ref,
637
1228
  "HEAD"
@@ -743,9 +1334,9 @@ function parseUnifiedDiff(diff) {
743
1334
  function createBranchDiff() {
744
1335
  return {
745
1336
  async review(cwd, options = {}) {
746
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1337
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
747
1338
  if (root === void 0) return void 0;
748
- const branch = await readLine$1(root, [
1339
+ const branch = await readLine(root, [
749
1340
  "symbolic-ref",
750
1341
  "--quiet",
751
1342
  "--short",
@@ -806,12 +1397,12 @@ function createBranchDiff() {
806
1397
  }
807
1398
  entries.sort((left, right) => left.path.localeCompare(right.path));
808
1399
  const conflicts = [...unmerged];
809
- const rebaseMerge = await readLine$1(root, [
1400
+ const rebaseMerge = await readLine(root, [
810
1401
  "rev-parse",
811
1402
  "--git-path",
812
1403
  "rebase-merge"
813
1404
  ]);
814
- const rebaseApply = await readLine$1(root, [
1405
+ const rebaseApply = await readLine(root, [
815
1406
  "rev-parse",
816
1407
  "--git-path",
817
1408
  "rebase-apply"
@@ -820,7 +1411,7 @@ function createBranchDiff() {
820
1411
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
821
1412
  let upstream;
822
1413
  if (upstreamRef !== void 0) {
823
- const [behind, ahead] = (await readLine$1(root, [
1414
+ const [behind, ahead] = (await readLine(root, [
824
1415
  "rev-list",
825
1416
  "--left-right",
826
1417
  "--count",
@@ -967,7 +1558,6 @@ const LOOSE_BITS = 63;
967
1558
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
968
1559
  const MAX_USERNAME = 256;
969
1560
  const MAX_TOKEN = 4096;
970
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
971
1561
  /** Environment that would make git log or skip what this module relies on. */
972
1562
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
973
1563
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -1231,70 +1821,384 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1231
1821
  };
1232
1822
  }
1233
1823
  //#endregion
1234
- //#region src/services/newSessionRequest/index.ts
1235
- const MAX_NAME_LENGTH = 120;
1236
- /** Trimmed text, undefined when absent or blank, false when not text at all. */
1237
- function optionalText(value) {
1238
- if (value === void 0) return void 0;
1239
- if (typeof value !== "string") return false;
1240
- const trimmed = value.trim();
1241
- return trimmed === "" ? void 0 : trimmed;
1242
- }
1243
- /**
1244
- * Validates a new-session dialog request for a worktree session. Every ref is
1245
- * checked here, before it can reach git as a positional argument.
1246
- */
1247
- function newSessionRequest(body) {
1248
- if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
1249
- const record = body;
1250
- const branch = optionalText(record.branch);
1251
- if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
1252
- const name = optionalText(record.name);
1253
- if (name === false || name !== void 0 && name.length > MAX_NAME_LENGTH) return { error: `The session name must be text of up to ${String(MAX_NAME_LENGTH)} characters.` };
1254
- const chosen = record.selection === void 0 ? {} : parseLaunchSelection(record.selection);
1255
- if ("error" in chosen) return chosen;
1256
- const profile = chosen.selection?.profile;
1257
- const named = {
1258
- ...name === void 0 ? {} : { name },
1259
- ...profile === void 0 ? {} : { selection: { profile } }
1260
- };
1261
- if (record.mode === "existing-branch") {
1262
- const remote = optionalText(record.remote);
1263
- if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
1264
- return {
1265
- mode: "existing-branch",
1266
- branch,
1267
- ...remote === void 0 ? {} : { remote },
1268
- ...named
1269
- };
1270
- }
1271
- if (record.mode === "new-branch") {
1272
- const baseRef = optionalText(record.baseRef);
1273
- if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
1274
- return {
1275
- mode: "new-branch",
1276
- branch,
1277
- ...baseRef === void 0 ? {} : { baseRef },
1278
- ...named
1279
- };
1824
+ //#region src/services/gitFailure/index.ts
1825
+ const english = (_key, fallback, vars) => formatMessage(fallback, vars);
1826
+ const RULES = [
1827
+ {
1828
+ code: "host_key_changed",
1829
+ phrases: ["remote host identification has changed"],
1830
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1831
+ recovery: (t) => t("git.failure.host_key_changed.recovery", "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal."),
1832
+ retryable: false
1833
+ },
1834
+ {
1835
+ code: "host_key_unknown",
1836
+ phrases: [
1837
+ "host key verification failed",
1838
+ "no ed25519 host key is known",
1839
+ "no rsa host key is known"
1840
+ ],
1841
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1842
+ recovery: (t) => t("git.failure.host_key_unknown.recovery", "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again."),
1843
+ retryable: false
1844
+ },
1845
+ {
1846
+ code: "auth_failed",
1847
+ phrases: [
1848
+ "authentication failed",
1849
+ "could not read username",
1850
+ "could not read password",
1851
+ "permission denied (publickey",
1852
+ "returned error: 401",
1853
+ "returned error: 403",
1854
+ "terminal prompts disabled",
1855
+ "load key",
1856
+ "unprotected private key",
1857
+ "invalid format"
1858
+ ],
1859
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1860
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1861
+ retryable: false
1862
+ },
1863
+ {
1864
+ code: "repository_not_found",
1865
+ phrases: ["repository not found", "does not appear to be a git repository"],
1866
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1867
+ recovery: (t) => t("git.failure.repository_not_found.recovery", "Check the remote URL and that the credentials have access. Open settings, then repository, then git remote."),
1868
+ retryable: false
1869
+ },
1870
+ {
1871
+ code: "remote_unreachable",
1872
+ phrases: [
1873
+ "could not resolve host",
1874
+ "connection refused",
1875
+ "connection timed out",
1876
+ "operation timed out",
1877
+ "unable to access",
1878
+ "network is unreachable"
1879
+ ],
1880
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1881
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1882
+ retryable: true
1883
+ },
1884
+ {
1885
+ code: "push_lease_rejected",
1886
+ phrases: ["(stale info)"],
1887
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1888
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1889
+ retryable: false
1890
+ },
1891
+ {
1892
+ code: "push_needs_force",
1893
+ phrases: ["(non-fast-forward)", "(fetch first)"],
1894
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1895
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1896
+ retryable: false
1897
+ },
1898
+ {
1899
+ code: "worktree_dirty",
1900
+ phrases: [
1901
+ "unstaged changes",
1902
+ "uncommitted changes",
1903
+ "would be overwritten",
1904
+ "your index contains uncommitted changes"
1905
+ ],
1906
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1907
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1908
+ retryable: false
1280
1909
  }
1281
- return { error: "The mode must be existing-branch or new-branch." };
1910
+ ];
1911
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1912
+ if (result.timedOut) return new PoGitExpectedError("git_timeout", t("git.failure.timeout", "git {operation} took too long and was stopped.", { operation }), true, t("git.failure.timeoutRecovery", "Check the network, then try again."));
1913
+ const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1914
+ const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1915
+ if (rule === void 0) return new PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1916
+ operation,
1917
+ code: String(result.code)
1918
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1919
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1920
+ return new PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1282
1921
  }
1283
1922
  //#endregion
1284
- //#region src/extensions/(backend)/api/git/_lib/route.server.ts
1923
+ //#region src/services/gitSync/index.ts
1285
1924
  /**
1286
- * The worktree surface the cockpit panel calls.
1287
- *
1288
- * Hub-scoped because worktrees are a property of a repository, not of one
1289
- * session: the panel lists and creates them whether or not the session that
1290
- * made them is focused, and a session-scoped API would disappear with it.
1925
+ * Manual pull, push and rebase for a session's checkout.
1291
1926
  *
1292
- * The panel names a repository by the hub's opaque id and never by path.
1293
- * `resolveRepository` turns that into an admitted root, so a browser cannot
1294
- * point this at a directory the cockpit was never given.
1295
- */
1296
- function badRequest(message) {
1297
- return Response.json({ error: message }, { status: 400 });
1927
+ * DESIGN PATTERNS:
1928
+ * - The workspace's auth goes into the environment of the one fetch or push
1929
+ * that needs it, built fresh per call. Rebase itself runs locally and never
1930
+ * sees a credential.
1931
+ * - Fetch and rebase are separate commands, so a hung network can never leave a
1932
+ * rebase half applied.
1933
+ * - A conflicted rebase is not an error. It is left paused for the reader to
1934
+ * hand to the agent or abort, and git's own state reports it from then on.
1935
+ * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1936
+ * Untracked files only block when git says they would be overwritten.
1937
+ * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1938
+ * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1939
+ * which git refuses if the remote holds commits this branch never integrated.
1940
+ */
1941
+ const DONE = { outcome: "done" };
1942
+ function expected(code, message, recovery) {
1943
+ return new PoGitExpectedError(code, message, false, recovery);
1944
+ }
1945
+ function createGitSync(options) {
1946
+ const baseEnv = options.baseEnv ?? {};
1947
+ async function readLine(cwd, args) {
1948
+ const result = await runGit(cwd, args, {
1949
+ timeout: READ_TIMEOUT_MS,
1950
+ env: baseEnv
1951
+ });
1952
+ const out = result.stdout.trim();
1953
+ return result.code === 0 && out !== "" ? out : void 0;
1954
+ }
1955
+ async function toplevel(cwd) {
1956
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1957
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1958
+ return root;
1959
+ }
1960
+ async function rebasing(root) {
1961
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1962
+ const gitPath = await readLine(root, [
1963
+ "rev-parse",
1964
+ "--git-path",
1965
+ name
1966
+ ]);
1967
+ if (gitPath !== void 0 && await fs.access(path.resolve(root, gitPath)).then(() => true, () => false)) return true;
1968
+ }
1969
+ return false;
1970
+ }
1971
+ async function conflicts(root) {
1972
+ return (await runGit(root, [
1973
+ "diff",
1974
+ "--name-only",
1975
+ "--diff-filter=U",
1976
+ "-z"
1977
+ ], {
1978
+ timeout: READ_TIMEOUT_MS,
1979
+ env: baseEnv
1980
+ })).stdout.split("\0").filter((file) => file !== "");
1981
+ }
1982
+ async function currentBranch(root) {
1983
+ const branch = await readLine(root, [
1984
+ "symbolic-ref",
1985
+ "--quiet",
1986
+ "--short",
1987
+ "HEAD"
1988
+ ]);
1989
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1990
+ return branch;
1991
+ }
1992
+ async function guard(root, needsCleanTree) {
1993
+ if (await rebasing(root)) throw expected("rebase_in_progress", "A rebase is paused in this checkout.", "Ask the agent to resolve it, or abort the rebase.");
1994
+ const branch = await currentBranch(root);
1995
+ if (needsCleanTree) {
1996
+ if (await readLine(root, [
1997
+ "status",
1998
+ "--porcelain",
1999
+ "--untracked-files=no"
2000
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2001
+ }
2002
+ return branch;
2003
+ }
2004
+ const baselines = /* @__PURE__ */ new Map();
2005
+ /** One credentialed network command against `remote`, classified on failure. */
2006
+ const network = async (root, context, remote, operation, args, urlArgs = []) => {
2007
+ const url = await readLine(root, [
2008
+ "remote",
2009
+ "get-url",
2010
+ ...urlArgs,
2011
+ remote
2012
+ ]);
2013
+ if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
2014
+ const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
2015
+ const result = await runGit(root, args, {
2016
+ timeout: NETWORK_TIMEOUT_MS,
2017
+ env: prepared.env,
2018
+ ...context.signal ? { signal: context.signal } : {}
2019
+ });
2020
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
2021
+ };
2022
+ /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
2023
+ const rebaseOnto = async (root, onto, context) => {
2024
+ context.signal?.throwIfAborted();
2025
+ const before = baselines.get(root) ?? await revision(root, "HEAD", {
2026
+ env: baseEnv,
2027
+ ...context.signal ? { signal: context.signal } : {}
2028
+ });
2029
+ baselines.set(root, before);
2030
+ const result = await runGit(root, ["rebase", onto], {
2031
+ timeout: REBASE_TIMEOUT_MS,
2032
+ ...context.signal ? { signal: context.signal } : {},
2033
+ env: {
2034
+ ...baseEnv,
2035
+ GIT_EDITOR: "true",
2036
+ GIT_TERMINAL_PROMPT: "0"
2037
+ }
2038
+ });
2039
+ if (result.code === 0) {
2040
+ if (before !== await revision(root, "HEAD", {
2041
+ env: baseEnv,
2042
+ ...context.signal ? { signal: context.signal } : {}
2043
+ })) await options.reapplySparse?.(root, context.signal);
2044
+ baselines.delete(root);
2045
+ return DONE;
2046
+ }
2047
+ if (await rebasing(root)) return {
2048
+ outcome: "paused",
2049
+ conflicts: await conflicts(root)
2050
+ };
2051
+ baselines.delete(root);
2052
+ throw classifyGitFailure("rebase", result, void 0, context.t);
2053
+ };
2054
+ /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
2055
+ const remoteOfRef = async (root, ref) => {
2056
+ const full = await readLine(root, [
2057
+ "rev-parse",
2058
+ "--symbolic-full-name",
2059
+ ref
2060
+ ]);
2061
+ if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
2062
+ const rest = full.slice(13);
2063
+ const cut = rest.indexOf("/");
2064
+ return cut > 0 ? rest.slice(0, cut) : void 0;
2065
+ };
2066
+ return {
2067
+ async pull(context) {
2068
+ const root = await toplevel(context.cwd);
2069
+ const branch = await guard(root, true);
2070
+ const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
2071
+ const upstream = await readLine(root, [
2072
+ "rev-parse",
2073
+ "--abbrev-ref",
2074
+ "--symbolic-full-name",
2075
+ `${branch}@{upstream}`
2076
+ ]);
2077
+ if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
2078
+ if (remote !== ".") await network(root, context, remote, "fetch", [
2079
+ "fetch",
2080
+ "--prune",
2081
+ remote
2082
+ ]);
2083
+ return rebaseOnto(root, upstream, context);
2084
+ },
2085
+ async push(context, force) {
2086
+ const root = await toplevel(context.cwd);
2087
+ const branch = await guard(root, false);
2088
+ const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
2089
+ const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
2090
+ let remote = configuredRemote;
2091
+ let target = merge;
2092
+ const args = ["push", "--porcelain"];
2093
+ if (remote === void 0 || target === void 0 || remote === ".") {
2094
+ const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
2095
+ remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
2096
+ if (remote === void 0) throw expected("no_remote", "There is no remote to push to.", remotes.length === 0 ? "Add a remote in a terminal first." : "Push once from a terminal to choose the remote.");
2097
+ target = `refs/heads/${branch}`;
2098
+ args.push("--set-upstream");
2099
+ }
2100
+ if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
2101
+ args.push(remote, `HEAD:${target}`);
2102
+ await network(root, context, remote, "push", args, ["--push"]);
2103
+ return DONE;
2104
+ },
2105
+ async rebase(context) {
2106
+ const root = await toplevel(context.cwd);
2107
+ const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
2108
+ if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
2109
+ const remote = await remoteOfRef(root, base);
2110
+ if (remote !== void 0) await network(root, context, remote, "fetch", [
2111
+ "fetch",
2112
+ "--prune",
2113
+ remote
2114
+ ]);
2115
+ return rebaseOnto(root, base, context);
2116
+ },
2117
+ async abortRebase(context) {
2118
+ const root = await toplevel(context.cwd);
2119
+ if (!await rebasing(root)) {
2120
+ baselines.delete(root);
2121
+ return DONE;
2122
+ }
2123
+ const result = await runGit(root, ["rebase", "--abort"], {
2124
+ timeout: REBASE_TIMEOUT_MS,
2125
+ env: baseEnv,
2126
+ ...context.signal ? { signal: context.signal } : {}
2127
+ });
2128
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2129
+ baselines.delete(root);
2130
+ return DONE;
2131
+ }
2132
+ };
2133
+ }
2134
+ //#endregion
2135
+ //#region src/services/newSessionRequest/index.ts
2136
+ const MAX_NAME_LENGTH = 120;
2137
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2138
+ function optionalText(value) {
2139
+ if (value === void 0) return void 0;
2140
+ if (typeof value !== "string") return false;
2141
+ const trimmed = value.trim();
2142
+ return trimmed === "" ? void 0 : trimmed;
2143
+ }
2144
+ /**
2145
+ * Validates a new-session dialog request for a worktree session. Every ref is
2146
+ * checked here, before it can reach git as a positional argument.
2147
+ */
2148
+ function newSessionRequest(body) {
2149
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2150
+ const record = body;
2151
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2152
+ const branch = optionalText(record.branch);
2153
+ if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
2154
+ const name = optionalText(record.name);
2155
+ if (name === false || name !== void 0 && name.length > MAX_NAME_LENGTH) return { error: `The session name must be text of up to ${String(MAX_NAME_LENGTH)} characters.` };
2156
+ if (Object.hasOwn(record, "sparseProfile") && !validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2157
+ const chosen = record.selection === void 0 ? {} : parseLaunchSelection(record.selection);
2158
+ if ("error" in chosen) return chosen;
2159
+ const profile = chosen.selection?.profile;
2160
+ const named = {
2161
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2162
+ ...name === void 0 ? {} : { name },
2163
+ ...profile === void 0 ? {} : { selection: { profile } }
2164
+ };
2165
+ if (record.mode === "existing-branch") {
2166
+ const remote = optionalText(record.remote);
2167
+ if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
2168
+ return {
2169
+ mode: "existing-branch",
2170
+ branch,
2171
+ ...remote === void 0 ? {} : { remote },
2172
+ ...named
2173
+ };
2174
+ }
2175
+ if (record.mode === "new-branch") {
2176
+ const baseRef = optionalText(record.baseRef);
2177
+ if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
2178
+ return {
2179
+ mode: "new-branch",
2180
+ branch,
2181
+ ...baseRef === void 0 ? {} : { baseRef },
2182
+ ...named
2183
+ };
2184
+ }
2185
+ return { error: "The mode must be existing-branch or new-branch." };
2186
+ }
2187
+ //#endregion
2188
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2189
+ /**
2190
+ * The worktree surface the cockpit panel calls.
2191
+ *
2192
+ * Hub-scoped because worktrees are a property of a repository, not of one
2193
+ * session: the panel lists and creates them whether or not the session that
2194
+ * made them is focused, and a session-scoped API would disappear with it.
2195
+ *
2196
+ * The panel names a repository by the hub's opaque id and never by path.
2197
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2198
+ * point this at a directory the cockpit was never given.
2199
+ */
2200
+ function badRequest(message) {
2201
+ return Response.json({ error: message }, { status: 400 });
1298
2202
  }
1299
2203
  function failed(error) {
1300
2204
  if (error instanceof PoGitExpectedError) return Response.json({
@@ -1303,7 +2207,7 @@ function failed(error) {
1303
2207
  }, { status: error.retryable ? 503 : 409 });
1304
2208
  return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1305
2209
  }
1306
- function createGitApi(openDirectory) {
2210
+ function createGitApi(openDirectory, dependencies = {}, translate) {
1307
2211
  return {
1308
2212
  basePath: "git",
1309
2213
  start(context) {
@@ -1317,11 +2221,81 @@ function createGitApi(openDirectory) {
1317
2221
  };
1318
2222
  const git = createWorktreeGit();
1319
2223
  const operations = createWorktreeOperations({
2224
+ ...dependencies,
1320
2225
  git,
1321
2226
  sessionService: context.sessionService,
1322
2227
  ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
1323
2228
  ...context.environment === void 0 ? {} : { environment: context.environment }
1324
2229
  });
2230
+ const sync = createGitSync({
2231
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2232
+ baseEnv: context.environment ?? {},
2233
+ async reapplySparse(cwd, signal) {
2234
+ const record = (await createWorktreeRegistry(await registryFile(cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.path === cwd && entry.sessionId === context.sessionId);
2235
+ if (record?.sparseProfile) await operations.reapply({
2236
+ cwd,
2237
+ sessionId: context.sessionId
2238
+ }, record.id, { signal });
2239
+ }
2240
+ });
2241
+ const sessionCommand = async (request, url) => {
2242
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2243
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2244
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2245
+ const caller = {
2246
+ cwd: context.cwd,
2247
+ sessionId: context.sessionId
2248
+ };
2249
+ const body = await request.json().catch(() => void 0);
2250
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2251
+ const command = body;
2252
+ if (url.pathname === "/sync") {
2253
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2254
+ const recordedBaseRef = (await createWorktreeRegistry(await registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2255
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2256
+ const syncContext = {
2257
+ ...caller,
2258
+ auth,
2259
+ recordedBaseRef,
2260
+ signal: request.signal,
2261
+ ...translate ? { t: translate } : {}
2262
+ };
2263
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2264
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2265
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2266
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2267
+ return badRequest("Unknown sync command.");
2268
+ }
2269
+ if (Object.keys(command).some((key) => ![
2270
+ "action",
2271
+ "branch",
2272
+ "baseRef",
2273
+ "sparseProfile",
2274
+ "reservationId",
2275
+ "id",
2276
+ "force",
2277
+ "folders"
2278
+ ].includes(key))) return badRequest("Unknown command field.");
2279
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2280
+ if (command.action === "create") {
2281
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2282
+ const result = await operations.spawn(caller, {
2283
+ branch: command.branch,
2284
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2285
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2286
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2287
+ }, { signal: request.signal });
2288
+ return Response.json({ worktree: result });
2289
+ }
2290
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2291
+ if (![
2292
+ "profiles",
2293
+ "expand",
2294
+ "reapply"
2295
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2296
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2297
+ return Response.json(result.details);
2298
+ };
1325
2299
  /**
1326
2300
  * The new-session dialog's routes: the workspace's branches, and a top-level
1327
2301
  * worktree session on one. Workspace-mounted only, and always rooted at the
@@ -1343,7 +2317,8 @@ function createGitApi(openDirectory) {
1343
2317
  remote: []
1344
2318
  } : {
1345
2319
  repository: true,
1346
- ...await git.listBranches(repositoryRoot)
2320
+ ...await git.listBranches(repositoryRoot),
2321
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
1347
2322
  };
1348
2323
  return Response.json(branches);
1349
2324
  }
@@ -1378,12 +2353,13 @@ function createGitApi(openDirectory) {
1378
2353
  if ("error" in parsed) return badRequest(parsed.error);
1379
2354
  const record = await operations.spawn({ cwd: workspaceRoot }, {
1380
2355
  branch: parsed.branch,
2356
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
1381
2357
  checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1382
2358
  ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1383
2359
  ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1384
2360
  ...parsed.name === void 0 ? {} : { name: parsed.name },
1385
2361
  ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
1386
- });
2362
+ }, { signal: request.signal });
1387
2363
  publishLifecycle(record.sessionId, record.repositoryRoot);
1388
2364
  const created = {
1389
2365
  sessionId: record.sessionId,
@@ -1465,7 +2441,7 @@ function createGitApi(openDirectory) {
1465
2441
  async fetch(request) {
1466
2442
  const url = new URL(request.url);
1467
2443
  try {
1468
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2444
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1469
2445
  if (answered !== void 0) return answered;
1470
2446
  } catch (error) {
1471
2447
  context.onNotice(`git request failed: ${error.name}`);
@@ -1485,6 +2461,7 @@ function createGitApi(openDirectory) {
1485
2461
  if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1486
2462
  const record = await operations.spawn(callerContext, {
1487
2463
  branch: body.branch,
2464
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
1488
2465
  ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1489
2466
  ...body.name === void 0 ? {} : { name: body.name }
1490
2467
  });
@@ -1510,7 +2487,8 @@ function createGitApi(openDirectory) {
1510
2487
  }
1511
2488
  //#endregion
1512
2489
  //#region src/extensions/(backend)/api/git/route.server.ts
1513
- var route_server_default = defineRoute(({ context, host, signal }) => {
2490
+ var route_server_default = defineRoute((plugin) => {
2491
+ const { context, host, signal } = plugin;
1514
2492
  let openDirectory;
1515
2493
  context.inject([PO_SHELL_SERVICE], (child) => {
1516
2494
  const shell = requirePoShell(child);
@@ -1534,285 +2512,9 @@ var route_server_default = defineRoute(({ context, host, signal }) => {
1534
2512
  return createGitApi(async (path) => {
1535
2513
  if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
1536
2514
  await openDirectory(path);
1537
- });
2515
+ }, createGitOperationDependencies(plugin), (key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(host.context.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars));
1538
2516
  });
1539
2517
  //#endregion
1540
- //#region src/services/gitFailure/index.ts
1541
- const RULES = [
1542
- {
1543
- code: "host_key_changed",
1544
- phrases: ["remote host identification has changed"],
1545
- message: "The remote's SSH host key changed since this machine last saw it.",
1546
- recovery: "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal.",
1547
- retryable: false
1548
- },
1549
- {
1550
- code: "host_key_unknown",
1551
- phrases: [
1552
- "host key verification failed",
1553
- "no ed25519 host key is known",
1554
- "no rsa host key is known"
1555
- ],
1556
- message: "This machine does not trust the remote's SSH host key yet.",
1557
- recovery: "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again.",
1558
- retryable: false
1559
- },
1560
- {
1561
- code: "auth_failed",
1562
- phrases: [
1563
- "authentication failed",
1564
- "could not read username",
1565
- "could not read password",
1566
- "permission denied (publickey",
1567
- "returned error: 401",
1568
- "returned error: 403",
1569
- "terminal prompts disabled",
1570
- "load key",
1571
- "unprotected private key",
1572
- "invalid format"
1573
- ],
1574
- message: "The remote refused the credentials.",
1575
- recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1576
- retryable: false
1577
- },
1578
- {
1579
- code: "repository_not_found",
1580
- phrases: ["repository not found", "does not appear to be a git repository"],
1581
- message: "The remote repository was not found, or these credentials cannot see it.",
1582
- recovery: `Check the remote URL and that the credentials have access. ${SETTINGS_HINT}`,
1583
- retryable: false
1584
- },
1585
- {
1586
- code: "remote_unreachable",
1587
- phrases: [
1588
- "could not resolve host",
1589
- "connection refused",
1590
- "connection timed out",
1591
- "operation timed out",
1592
- "unable to access",
1593
- "network is unreachable"
1594
- ],
1595
- message: "The remote could not be reached.",
1596
- recovery: "Check the network and the remote URL, then try again.",
1597
- retryable: true
1598
- },
1599
- {
1600
- code: "push_lease_rejected",
1601
- phrases: ["(stale info)"],
1602
- message: "The remote branch moved since your last fetch, so the force push was refused.",
1603
- recovery: "Pull to see the new commits, then decide whether to push again.",
1604
- retryable: false
1605
- },
1606
- {
1607
- code: "push_needs_force",
1608
- phrases: ["(non-fast-forward)", "(fetch first)"],
1609
- message: "The remote branch has commits yours replaced, usually after a rebase.",
1610
- recovery: "Confirm a force push with lease, or pull first to keep the remote commits.",
1611
- retryable: false
1612
- },
1613
- {
1614
- code: "worktree_dirty",
1615
- phrases: [
1616
- "unstaged changes",
1617
- "uncommitted changes",
1618
- "would be overwritten",
1619
- "your index contains uncommitted changes"
1620
- ],
1621
- message: "There are uncommitted changes in the way.",
1622
- recovery: "Commit or stash your changes first.",
1623
- retryable: false
1624
- }
1625
- ];
1626
- function classifyGitFailure(operation, result, mismatch) {
1627
- if (result.timedOut) return new PoGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1628
- const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1629
- const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1630
- if (rule === void 0) return new PoGitExpectedError("git_failed", `git ${operation} failed (exit ${String(result.code)}).`, false, "Run the same command in a terminal in this checkout to see what git says.");
1631
- const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1632
- return new PoGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1633
- }
1634
- //#endregion
1635
- //#region src/services/gitSync/index.ts
1636
- /**
1637
- * Manual pull, push and rebase for a session's checkout.
1638
- *
1639
- * DESIGN PATTERNS:
1640
- * - The workspace's auth goes into the environment of the one fetch or push
1641
- * that needs it, built fresh per call. Rebase itself runs locally and never
1642
- * sees a credential.
1643
- * - Fetch and rebase are separate commands, so a hung network can never leave a
1644
- * rebase half applied.
1645
- * - A conflicted rebase is not an error. It is left paused for the reader to
1646
- * hand to the agent or abort, and git's own state reports it from then on.
1647
- * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1648
- * Untracked files only block when git says they would be overwritten.
1649
- * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1650
- * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1651
- * which git refuses if the remote holds commits this branch never integrated.
1652
- */
1653
- const DONE = { outcome: "done" };
1654
- function expected(code, message, recovery) {
1655
- return new PoGitExpectedError(code, message, false, recovery);
1656
- }
1657
- async function readLine(cwd, args) {
1658
- const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
1659
- const out = result.stdout.trim();
1660
- return result.code === 0 && out !== "" ? out : void 0;
1661
- }
1662
- async function toplevel(cwd) {
1663
- const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1664
- if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1665
- return root;
1666
- }
1667
- async function rebasing(root) {
1668
- for (const name of ["rebase-merge", "rebase-apply"]) {
1669
- const gitPath = await readLine(root, [
1670
- "rev-parse",
1671
- "--git-path",
1672
- name
1673
- ]);
1674
- if (gitPath !== void 0 && await fs.access(path.resolve(root, gitPath)).then(() => true, () => false)) return true;
1675
- }
1676
- return false;
1677
- }
1678
- async function conflicts(root) {
1679
- return (await runGit(root, [
1680
- "diff",
1681
- "--name-only",
1682
- "--diff-filter=U",
1683
- "-z"
1684
- ], { timeout: READ_TIMEOUT_MS })).stdout.split("\0").filter((file) => file !== "");
1685
- }
1686
- async function currentBranch(root) {
1687
- const branch = await readLine(root, [
1688
- "symbolic-ref",
1689
- "--quiet",
1690
- "--short",
1691
- "HEAD"
1692
- ]);
1693
- if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1694
- return branch;
1695
- }
1696
- async function guard(root, needsCleanTree) {
1697
- if (await rebasing(root)) throw expected("rebase_in_progress", "A rebase is paused in this checkout.", "Ask the agent to resolve it, or abort the rebase.");
1698
- const branch = await currentBranch(root);
1699
- if (needsCleanTree) {
1700
- if (await readLine(root, [
1701
- "status",
1702
- "--porcelain",
1703
- "--untracked-files=no"
1704
- ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
1705
- }
1706
- return branch;
1707
- }
1708
- function createGitSync(options) {
1709
- const baseEnv = options.baseEnv ?? process.env;
1710
- /** One credentialed network command against `remote`, classified on failure. */
1711
- const network = async (root, context, remote, operation, args, urlArgs = []) => {
1712
- const url = await readLine(root, [
1713
- "remote",
1714
- "get-url",
1715
- ...urlArgs,
1716
- remote
1717
- ]);
1718
- if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
1719
- const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1720
- const result = await runGit(root, args, {
1721
- timeout: NETWORK_TIMEOUT_MS,
1722
- env: prepared.env
1723
- });
1724
- if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
1725
- };
1726
- /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1727
- const rebaseOnto = async (root, onto) => {
1728
- const result = await runGit(root, ["rebase", onto], {
1729
- timeout: REBASE_TIMEOUT_MS,
1730
- env: {
1731
- ...baseEnv,
1732
- GIT_EDITOR: "true",
1733
- GIT_TERMINAL_PROMPT: "0"
1734
- }
1735
- });
1736
- if (result.code === 0) return DONE;
1737
- if (await rebasing(root)) return {
1738
- outcome: "paused",
1739
- conflicts: await conflicts(root)
1740
- };
1741
- throw classifyGitFailure("rebase", result);
1742
- };
1743
- /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1744
- const remoteOfRef = async (root, ref) => {
1745
- const full = await readLine(root, [
1746
- "rev-parse",
1747
- "--symbolic-full-name",
1748
- ref
1749
- ]);
1750
- if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
1751
- const rest = full.slice(13);
1752
- const cut = rest.indexOf("/");
1753
- return cut > 0 ? rest.slice(0, cut) : void 0;
1754
- };
1755
- return {
1756
- async pull(context) {
1757
- const root = await toplevel(context.cwd);
1758
- const branch = await guard(root, true);
1759
- const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
1760
- const upstream = await readLine(root, [
1761
- "rev-parse",
1762
- "--abbrev-ref",
1763
- "--symbolic-full-name",
1764
- `${branch}@{upstream}`
1765
- ]);
1766
- if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
1767
- if (remote !== ".") await network(root, context, remote, "fetch", [
1768
- "fetch",
1769
- "--prune",
1770
- remote
1771
- ]);
1772
- return rebaseOnto(root, upstream);
1773
- },
1774
- async push(context, force) {
1775
- const root = await toplevel(context.cwd);
1776
- const branch = await guard(root, false);
1777
- const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
1778
- const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
1779
- let remote = configuredRemote;
1780
- let target = merge;
1781
- const args = ["push", "--porcelain"];
1782
- if (remote === void 0 || target === void 0 || remote === ".") {
1783
- const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
1784
- remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
1785
- if (remote === void 0) throw expected("no_remote", "There is no remote to push to.", remotes.length === 0 ? "Add a remote in a terminal first." : "Push once from a terminal to choose the remote.");
1786
- target = `refs/heads/${branch}`;
1787
- args.push("--set-upstream");
1788
- }
1789
- if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
1790
- args.push(remote, `HEAD:${target}`);
1791
- await network(root, context, remote, "push", args, ["--push"]);
1792
- return DONE;
1793
- },
1794
- async rebase(context) {
1795
- const root = await toplevel(context.cwd);
1796
- const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
1797
- if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
1798
- const remote = await remoteOfRef(root, base);
1799
- if (remote !== void 0) await network(root, context, remote, "fetch", [
1800
- "fetch",
1801
- "--prune",
1802
- remote
1803
- ]);
1804
- return rebaseOnto(root, base);
1805
- },
1806
- async abortRebase(context) {
1807
- const root = await toplevel(context.cwd);
1808
- if (!await rebasing(root)) return DONE;
1809
- const result = await runGit(root, ["rebase", "--abort"], { timeout: REBASE_TIMEOUT_MS });
1810
- if (result.code !== 0) throw classifyGitFailure("rebase --abort", result);
1811
- return DONE;
1812
- }
1813
- };
1814
- }
1815
- //#endregion
1816
2518
  //#region src/types/gitReview.ts
1817
2519
  /**
1818
2520
  * The cockpit's view of what this session changed against its base: the counts
@@ -1964,17 +2666,30 @@ function createGitChangesChannel(options = {}) {
1964
2666
  delayed.set(sessionId, timer);
1965
2667
  };
1966
2668
  const run = async (scope, command) => {
2669
+ if (options.scopedCommands) {
2670
+ const response = await host.requestSessionApi(scope, {
2671
+ basePath: "git",
2672
+ path: "/sync",
2673
+ method: "POST",
2674
+ body: JSON.stringify(command)
2675
+ });
2676
+ const result = await response.json();
2677
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2678
+ return result;
2679
+ }
1967
2680
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1968
2681
  const base = await recordedBaseRef(scope);
1969
2682
  const context = {
1970
2683
  cwd: scope.cwd,
2684
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
1971
2685
  auth: await auth.read(workspaceRoot),
1972
2686
  ...base === void 0 ? {} : { recordedBaseRef: base }
1973
2687
  };
1974
- if (command.action === "pull") return sync.pull(context);
1975
- if (command.action === "push") return sync.push(context, command.force === true);
1976
- if (command.action === "rebase") return sync.rebase(context);
1977
- return sync.abortRebase(context);
2688
+ const sessionSync = sync;
2689
+ if (command.action === "pull") return sessionSync.pull(context);
2690
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2691
+ if (command.action === "rebase") return sessionSync.rebase(context);
2692
+ return sessionSync.abortRebase(context);
1978
2693
  };
1979
2694
  const source = {
1980
2695
  payloadFor(scope) {
@@ -2041,7 +2756,12 @@ function createGitChangesChannel(options = {}) {
2041
2756
  }
2042
2757
  //#endregion
2043
2758
  //#region src/extensions/(backend)/channel/git-changes.server.ts
2044
- var git_changes_server_default = defineChannel(createGitChangesChannel);
2759
+ var git_changes_server_default = defineChannel(({ context, host }) => createGitChangesChannel({
2760
+ homeDir: host.context.homeDirectory,
2761
+ environment: host.context.environment,
2762
+ scopedCommands: true,
2763
+ t: (scope, key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(scope.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars)
2764
+ }), { context: true });
2045
2765
  //#endregion
2046
2766
  //#region src/types/webWorktrees.ts
2047
2767
  /**
@@ -2114,7 +2834,9 @@ function parseCommand(payload) {
2114
2834
  if (value.action === "create") {
2115
2835
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
2116
2836
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2837
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
2117
2838
  return {
2839
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
2118
2840
  action: "create",
2119
2841
  branch: value.branch.trim(),
2120
2842
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -2168,6 +2890,22 @@ function createWorktreesChannel(options = {}) {
2168
2890
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
2169
2891
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
2170
2892
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2893
+ if (options.scopedCommands) {
2894
+ if (!(await host.requestSessionApi(parent, {
2895
+ basePath: "git",
2896
+ path: "/session-worktrees",
2897
+ method: "POST",
2898
+ body: JSON.stringify({
2899
+ action: "create",
2900
+ branch,
2901
+ reservationId
2902
+ }),
2903
+ ...signal ? { signal } : {}
2904
+ })).ok) throw new Error("The conversation worktree could not be created.");
2905
+ const reservations = sessionService.reservations;
2906
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2907
+ return reservations.complete(reservationId, parentSessionId);
2908
+ }
2171
2909
  const record = await worktrees.spawn({
2172
2910
  cwd: parent.cwd,
2173
2911
  sessionId: parent.sessionId
@@ -2231,10 +2969,24 @@ function createWorktreesChannel(options = {}) {
2231
2969
  if (generations.get(scope.sessionId) !== generation) return;
2232
2970
  mark(scope, pending, error, errorTarget);
2233
2971
  };
2972
+ if (options.scopedCommands) {
2973
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2974
+ const response = await host.requestSessionApi(scope, {
2975
+ basePath: "git",
2976
+ path: "/session-worktrees",
2977
+ method: "POST",
2978
+ body: JSON.stringify(command)
2979
+ });
2980
+ const result = await response.json();
2981
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2982
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2983
+ return;
2984
+ }
2234
2985
  if (command.action === "create") {
2235
2986
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
2236
2987
  const record = await worktrees.spawn(context, {
2237
2988
  branch: command.branch,
2989
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2238
2990
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2239
2991
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2240
2992
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -2310,7 +3062,11 @@ function createWorktreesChannel(options = {}) {
2310
3062
  }
2311
3063
  //#endregion
2312
3064
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2313
- var git_worktrees_server_default = defineChannel(createWorktreesChannel);
3065
+ var git_worktrees_server_default = defineChannel((plugin) => createWorktreesChannel({
3066
+ homeDir: plugin.host.context.homeDirectory,
3067
+ environment: plugin.host.context.environment,
3068
+ scopedCommands: true
3069
+ }), { context: true });
2314
3070
  //#endregion
2315
3071
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2316
3072
  var agent_settled_server_default = defineHook((context) => context.root.hooks[1]);
@@ -2337,8 +3093,11 @@ const via = (identity, value) => value === void 0 ? void 0 : {
2337
3093
  };
2338
3094
  const serverPlugin = defineServerPlugin({
2339
3095
  name: "@agimon-ai/po-git",
2340
- providerOverrides: composeServerProviderOverrides(root_server_default),
2341
- injects: composeRootInjects({ session: [root_server_default] }),
3096
+ providerOverrides: composeServerProviderOverrides(root_server_default$1, root_server_default),
3097
+ injects: composeRootInjects({
3098
+ workspace: [root_server_default$1],
3099
+ session: [root_server_default$1, root_server_default]
3100
+ }),
2342
3101
  host: (context) => ({
2343
3102
  get api() {
2344
3103
  return [at(route_server_default, context)];
@@ -2347,22 +3106,32 @@ const serverPlugin = defineServerPlugin({
2347
3106
  return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2348
3107
  }
2349
3108
  }),
2350
- workspace: (context) => ({
2351
- get api() {
2352
- return [at(route_server_default, context)];
2353
- },
2354
- get channels() {
2355
- return defined([context.hosted("host") ? void 0 : () => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), context.hosted("host") ? void 0 : () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))]);
2356
- }
2357
- }),
3109
+ workspace: async (context) => {
3110
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3111
+ return {
3112
+ ...composeRootHooks(scopeWorkspace),
3113
+ get api() {
3114
+ return [at(route_server_default, context)];
3115
+ },
3116
+ get channels() {
3117
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), context.hosted("host") ? void 0 : () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))]);
3118
+ },
3119
+ services: [...scopeWorkspace.services ?? []]
3120
+ };
3121
+ },
2358
3122
  session: async (context) => {
2359
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
2360
- const contextSession = {
3123
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3124
+ const contextWorkspace = {
2361
3125
  ...context,
3126
+ root: scopeWorkspace.value
3127
+ };
3128
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3129
+ const contextSession = {
3130
+ ...contextWorkspace,
2362
3131
  root: scopeSession.value
2363
3132
  };
2364
3133
  return {
2365
- ...composeRootHooks(scopeSession),
3134
+ ...composeRootHooks(scopeWorkspace, scopeSession),
2366
3135
  get api() {
2367
3136
  return [at(route_server_default, context)];
2368
3137
  },
@@ -2378,9 +3147,9 @@ const serverPlugin = defineServerPlugin({
2378
3147
  get tools() {
2379
3148
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2380
3149
  },
2381
- services: [...scopeSession.services ?? []],
3150
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2382
3151
  get activities() {
2383
- return [...scopeSession.activities ?? []];
3152
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2384
3153
  }
2385
3154
  };
2386
3155
  }