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

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-Delu4xip.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,370 @@ 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
+ const frozen = input.overrides?.allocation;
894
+ const refusal = report.errors.length ? `The workflow is not valid: ${report.errors.map((issue) => issue.message).join("; ")}` : report.allocation === void 0 ? void 0 : frozen === void 0 ? "This role-bound workflow needs an allocation prepared before the checkout, and none was supplied." : JSON.stringify(canonical(report.allocation)) !== JSON.stringify(canonical(frozen)) ? "The workflow allocation changed since it was prepared." : void 0;
895
+ if (refusal) {
896
+ await update({
897
+ ...attempt,
898
+ state: "rejected"
899
+ }, signal);
900
+ throw new WorktreeWorkflowError("not_started", refusal);
901
+ }
902
+ operation(signal).signal.throwIfAborted();
903
+ try {
904
+ record = await options.operations.spawn(context, {
905
+ branch,
906
+ ...input.sparseProfile ? { sparseProfile: input.sparseProfile } : {}
907
+ }, {
908
+ workflow: {
909
+ attemptId: input.attemptId,
910
+ fingerprint
911
+ },
912
+ ...input.preset ? { preset: input.preset } : {},
913
+ signal: operation(signal).signal
914
+ });
915
+ await update({
916
+ ...attempt,
917
+ worktreeId: record.id,
918
+ sessionId: record.sessionId,
919
+ state: "spawned"
920
+ });
921
+ const base = remoteBase(record);
922
+ if (!base) throw new WorktreeWorkflowError("not_started", "The workflow base is not a verifiable remote branch. The checkout was kept.");
923
+ const pending = {
924
+ ...attempt,
925
+ worktreeId: record.id,
926
+ sessionId: record.sessionId,
927
+ state: "admitting"
928
+ };
929
+ await update(pending);
930
+ const admission = await admissions.launch(input.attemptId, input.definition, {
931
+ ...input.overrides,
932
+ env: {
933
+ ...input.overrides?.env,
934
+ SPARO_BASE_REMOTE: base.remote,
935
+ SPARO_BASE_BRANCH: base.branch,
936
+ SPARO_BASE_SHA: base.sha,
937
+ SPARO_BRANCH: record.branch,
938
+ PO_GIT_BASE_REMOTE: base.remote,
939
+ PO_GIT_BASE_BRANCH: base.branch,
940
+ PO_GIT_BASE_SHA: base.sha,
941
+ PO_GIT_BRANCH: record.branch
942
+ },
943
+ targetSessionId: record.sessionId
944
+ });
945
+ return await link(record, pending, admission);
946
+ } catch (error) {
947
+ if (error instanceof WorktreeWorkflowError) throw error;
948
+ throw new WorktreeWorkflowError("unknown", "The workflow launch outcome is uncertain. Inspect the saved attempt before retrying.", { cause: error });
949
+ }
950
+ };
951
+ return {
952
+ start(input, signal) {
953
+ options.signal.throwIfAborted();
954
+ signal?.throwIfAborted();
955
+ 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."));
956
+ const snapshot = structuredClone(input);
957
+ const branch = snapshot.branch ?? defaultBranch(snapshot);
958
+ if (!validRefName(branch)) return Promise.reject(new WorktreeWorkflowError("not_started", "The workflow branch is invalid."));
959
+ const fingerprint = createHash("sha256").update(JSON.stringify(canonical({
960
+ definition: snapshot.definition,
961
+ branch,
962
+ profile: snapshot.sparseProfile,
963
+ preset: snapshot.preset,
964
+ overrides: snapshot.overrides
965
+ }))).digest("hex");
966
+ const existing = inFlight.get(snapshot.attemptId);
967
+ if (existing) return existing.fingerprint === fingerprint ? existing.promise : Promise.reject(new WorktreeWorkflowError("attempt_conflict", "This workflow attempt is already starting with different arguments."));
968
+ const promise = start(snapshot, branch, fingerprint, signal).finally(() => {
969
+ inFlight.delete(snapshot.attemptId);
970
+ });
971
+ inFlight.set(snapshot.attemptId, {
972
+ fingerprint,
973
+ promise
974
+ });
975
+ return promise;
976
+ },
977
+ async reconcile(signal) {
978
+ operation(signal).signal.throwIfAborted();
979
+ const admissions = options.admissions();
980
+ if (!admissions) return;
981
+ const records = await ownRecords();
982
+ const registry = await store();
983
+ const attempts = await registry.transaction(() => registry.workflowAttempts(), operation(signal).signal);
984
+ for (const attempt of attempts.filter((entry) => entry.launcherSessionId === options.sessionId && ![
985
+ "closed",
986
+ "rejected",
987
+ "retained"
988
+ ].includes(entry.state))) {
989
+ const record = records.find((entry) => entry.id === attempt.worktreeId || entry.workflow.attemptId === attempt.attemptId);
990
+ if (!record || record.status === "orphaned") continue;
991
+ try {
992
+ const admission = await admissions.read(attempt.attemptId);
993
+ if (admission) await link(record, attempt, admission);
994
+ } catch (error) {
995
+ options.onError(error);
996
+ }
997
+ }
998
+ }
999
+ };
1000
+ }
1001
+ //#endregion
463
1002
  //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
464
1003
  function progressResult(action, label) {
465
1004
  return {
@@ -479,18 +1018,66 @@ const READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
479
1018
  "discover",
480
1019
  "load_skill"
481
1020
  ]);
482
- function createGitSession({ context, host: serverHost, agent, signal }) {
1021
+ async function createGitSession({ context, host: serverHost, agent, signal }) {
483
1022
  if (serverHost.context.directEvents === void 0) throw new Error("Git server plugin requires the session direct event bus.");
484
1023
  if (serverHost.context.sessionId === void 0) throw new Error("Git server plugin requires a session identity.");
485
1024
  const sessionId = serverHost.context.sessionId;
486
1025
  const directEvents = serverHost.context.directEvents;
487
1026
  const messageInbox = createWorktreeMessageInbox(directEvents, sessionId);
1027
+ const setupReceiver = context.inject(["po/runner-launch"], (child) => {
1028
+ const runner = child.get("po/runner-launch");
1029
+ const cwd = serverHost.context.cwd;
1030
+ if (!runner || !cwd) return void 0;
1031
+ return receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal);
1032
+ });
488
1033
  const operations = createWorktreeOperations({
489
1034
  git: createWorktreeGit(),
1035
+ ...createGitOperationDependencies({
1036
+ context,
1037
+ host: serverHost,
1038
+ signal
1039
+ }),
490
1040
  sessionService: serverHost.context.sessionService,
491
1041
  messageInbox,
492
1042
  sessionDelivery: () => readPoSessionDelivery(context)
493
1043
  });
1044
+ const homeDirectory = serverHost.context.homeDirectory ?? serverHost.context.environment?.HOME;
1045
+ let workflows;
1046
+ const workflowProvider = context.inject([PO_SERVER_SCOPE_SERVICE], async (scoped) => {
1047
+ if (!homeDirectory || !serverHost.context.cwd) return void 0;
1048
+ const lifetime = new AbortController();
1049
+ const service = createWorktreeWorkflows({
1050
+ sessionId,
1051
+ cwd: serverHost.context.cwd,
1052
+ homeDirectory,
1053
+ environment: serverHost.context.environment ?? {},
1054
+ signal: AbortSignal.any([signal, lifetime.signal]),
1055
+ operations,
1056
+ git: {
1057
+ ...createWorktreeGit(),
1058
+ revision,
1059
+ remoteBranchHead
1060
+ },
1061
+ admissions: () => readPoWorkflowAdmissionsService(scoped),
1062
+ runs: () => readPoWorkflowRunsService(scoped),
1063
+ onError: (error) => serverHost.context.onNotice(`Workflow checkout retained (${error instanceof Error ? error.name : "unknown error"}).`)
1064
+ });
1065
+ const release = await requirePoServerScope(scoped).provide(GIT_WORKFLOWS_CONTRACT, service);
1066
+ workflows = service;
1067
+ return async () => {
1068
+ if (workflows === service) workflows = void 0;
1069
+ lifetime.abort();
1070
+ await release();
1071
+ };
1072
+ });
1073
+ if (context.get(PO_SERVER_SCOPE_SERVICE) !== void 0) await workflowProvider.await();
1074
+ const workflowServices = context.inject([PO_WORKFLOW_ADMISSIONS_SERVICE, PO_WORKFLOW_RUNS_SERVICE], async () => {
1075
+ try {
1076
+ await workflows?.reconcile();
1077
+ } catch (error) {
1078
+ serverHost.context.onNotice(`Workflow reconciliation deferred (${error instanceof Error ? error.name : "unknown error"}).`);
1079
+ }
1080
+ });
494
1081
  const resources = [{
495
1082
  name: "codemode-how-to-git",
496
1083
  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 +1114,7 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
527
1114
  if (agent) {
528
1115
  const namespace = createWorktreeNamespace({
529
1116
  operations,
1117
+ workflows: () => workflows,
530
1118
  execution: agent.context,
531
1119
  assertAvailable: () => {
532
1120
  if (signal?.aborted) throw new Error("Git session is unavailable.");
@@ -549,7 +1137,12 @@ function createGitSession({ context, host: serverHost, agent, signal }) {
549
1137
  tool,
550
1138
  hooks
551
1139
  },
552
- onDispose: () => messageInbox.close()
1140
+ onDispose: async () => {
1141
+ await workflowServices.dispose();
1142
+ await workflowProvider.dispose();
1143
+ await setupReceiver.dispose();
1144
+ messageInbox.close();
1145
+ }
553
1146
  };
554
1147
  }
555
1148
  const root = defineRoot(createGitSession);
@@ -588,12 +1181,12 @@ async function read(cwd, args) {
588
1181
  const result = await runGit(cwd, args, { timeout: READ_TIMEOUT_MS });
589
1182
  return result.code === 0 ? result.stdout : void 0;
590
1183
  }
591
- async function readLine$1(cwd, args) {
1184
+ async function readLine(cwd, args) {
592
1185
  const out = (await read(cwd, args))?.trim();
593
1186
  return out === void 0 || out === "" ? void 0 : out;
594
1187
  }
595
1188
  async function commitExists(cwd, ref) {
596
- return await readLine$1(cwd, [
1189
+ return await readLine(cwd, [
597
1190
  "rev-parse",
598
1191
  "--verify",
599
1192
  "--quiet",
@@ -602,7 +1195,7 @@ async function commitExists(cwd, ref) {
602
1195
  }
603
1196
  /** A local branch's upstream, so the review measures against what fetch keeps current. */
604
1197
  async function upstreamOf(cwd, ref) {
605
- return readLine$1(cwd, [
1198
+ return readLine(cwd, [
606
1199
  "rev-parse",
607
1200
  "--abbrev-ref",
608
1201
  "--symbolic-full-name",
@@ -611,13 +1204,13 @@ async function upstreamOf(cwd, ref) {
611
1204
  }
612
1205
  /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
613
1206
  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, [
1207
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine(cwd, [
615
1208
  "rev-parse",
616
1209
  "--verify",
617
1210
  "--quiet",
618
1211
  `refs/heads/${recordedBaseRef}`
619
1212
  ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
620
- const originHead = await readLine$1(cwd, [
1213
+ const originHead = await readLine(cwd, [
621
1214
  "symbolic-ref",
622
1215
  "--quiet",
623
1216
  "--short",
@@ -631,7 +1224,7 @@ async function resolveBase(cwd, branch, recordedBaseRef) {
631
1224
  const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
632
1225
  const head = await commitExists(cwd, "HEAD");
633
1226
  if (ref !== void 0 && head) {
634
- const mergeBase = await readLine$1(cwd, [
1227
+ const mergeBase = await readLine(cwd, [
635
1228
  "merge-base",
636
1229
  ref,
637
1230
  "HEAD"
@@ -743,9 +1336,9 @@ function parseUnifiedDiff(diff) {
743
1336
  function createBranchDiff() {
744
1337
  return {
745
1338
  async review(cwd, options = {}) {
746
- const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
1339
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
747
1340
  if (root === void 0) return void 0;
748
- const branch = await readLine$1(root, [
1341
+ const branch = await readLine(root, [
749
1342
  "symbolic-ref",
750
1343
  "--quiet",
751
1344
  "--short",
@@ -806,12 +1399,12 @@ function createBranchDiff() {
806
1399
  }
807
1400
  entries.sort((left, right) => left.path.localeCompare(right.path));
808
1401
  const conflicts = [...unmerged];
809
- const rebaseMerge = await readLine$1(root, [
1402
+ const rebaseMerge = await readLine(root, [
810
1403
  "rev-parse",
811
1404
  "--git-path",
812
1405
  "rebase-merge"
813
1406
  ]);
814
- const rebaseApply = await readLine$1(root, [
1407
+ const rebaseApply = await readLine(root, [
815
1408
  "rev-parse",
816
1409
  "--git-path",
817
1410
  "rebase-apply"
@@ -820,7 +1413,7 @@ function createBranchDiff() {
820
1413
  const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
821
1414
  let upstream;
822
1415
  if (upstreamRef !== void 0) {
823
- const [behind, ahead] = (await readLine$1(root, [
1416
+ const [behind, ahead] = (await readLine(root, [
824
1417
  "rev-list",
825
1418
  "--left-right",
826
1419
  "--count",
@@ -967,7 +1560,6 @@ const LOOSE_BITS = 63;
967
1560
  const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
968
1561
  const MAX_USERNAME = 256;
969
1562
  const MAX_TOKEN = 4096;
970
- const SETTINGS_HINT = "Open settings, then repository, then git remote.";
971
1563
  /** Environment that would make git log or skip what this module relies on. */
972
1564
  const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
973
1565
  const STRIPPED_PREFIXES = ["GIT_TRACE"];
@@ -1231,70 +1823,384 @@ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
1231
1823
  };
1232
1824
  }
1233
1825
  //#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
- };
1826
+ //#region src/services/gitFailure/index.ts
1827
+ const english = (_key, fallback, vars) => formatMessage(fallback, vars);
1828
+ const RULES = [
1829
+ {
1830
+ code: "host_key_changed",
1831
+ phrases: ["remote host identification has changed"],
1832
+ message: (t) => t("git.failure.host_key_changed.message", "The remote's SSH host key changed since this machine last saw it."),
1833
+ 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."),
1834
+ retryable: false
1835
+ },
1836
+ {
1837
+ code: "host_key_unknown",
1838
+ phrases: [
1839
+ "host key verification failed",
1840
+ "no ed25519 host key is known",
1841
+ "no rsa host key is known"
1842
+ ],
1843
+ message: (t) => t("git.failure.host_key_unknown.message", "This machine does not trust the remote's SSH host key yet."),
1844
+ 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."),
1845
+ retryable: false
1846
+ },
1847
+ {
1848
+ code: "auth_failed",
1849
+ phrases: [
1850
+ "authentication failed",
1851
+ "could not read username",
1852
+ "could not read password",
1853
+ "permission denied (publickey",
1854
+ "returned error: 401",
1855
+ "returned error: 403",
1856
+ "terminal prompts disabled",
1857
+ "load key",
1858
+ "unprotected private key",
1859
+ "invalid format"
1860
+ ],
1861
+ message: (t) => t("git.failure.auth_failed.message", "The remote refused the credentials."),
1862
+ recovery: (t) => t("git.failure.auth_failed.recovery", "Check this workspace's git remote auth. Open settings, then repository, then git remote."),
1863
+ retryable: false
1864
+ },
1865
+ {
1866
+ code: "repository_not_found",
1867
+ phrases: ["repository not found", "does not appear to be a git repository"],
1868
+ message: (t) => t("git.failure.repository_not_found.message", "The remote repository was not found, or these credentials cannot see it."),
1869
+ 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."),
1870
+ retryable: false
1871
+ },
1872
+ {
1873
+ code: "remote_unreachable",
1874
+ phrases: [
1875
+ "could not resolve host",
1876
+ "connection refused",
1877
+ "connection timed out",
1878
+ "operation timed out",
1879
+ "unable to access",
1880
+ "network is unreachable"
1881
+ ],
1882
+ message: (t) => t("git.failure.remote_unreachable.message", "The remote could not be reached."),
1883
+ recovery: (t) => t("git.failure.remote_unreachable.recovery", "Check the network and the remote URL, then try again."),
1884
+ retryable: true
1885
+ },
1886
+ {
1887
+ code: "push_lease_rejected",
1888
+ phrases: ["(stale info)"],
1889
+ message: (t) => t("git.failure.push_lease_rejected.message", "The remote branch moved since your last fetch, so the force push was refused."),
1890
+ recovery: (t) => t("git.failure.push_lease_rejected.recovery", "Pull to see the new commits, then decide whether to push again."),
1891
+ retryable: false
1892
+ },
1893
+ {
1894
+ code: "push_needs_force",
1895
+ phrases: ["(non-fast-forward)", "(fetch first)"],
1896
+ message: (t) => t("git.failure.push_needs_force.message", "The remote branch has commits yours replaced, usually after a rebase."),
1897
+ recovery: (t) => t("git.failure.push_needs_force.recovery", "Confirm a force push with lease, or pull first to keep the remote commits."),
1898
+ retryable: false
1899
+ },
1900
+ {
1901
+ code: "worktree_dirty",
1902
+ phrases: [
1903
+ "unstaged changes",
1904
+ "uncommitted changes",
1905
+ "would be overwritten",
1906
+ "your index contains uncommitted changes"
1907
+ ],
1908
+ message: (t) => t("git.failure.worktree_dirty.message", "There are uncommitted changes in the way."),
1909
+ recovery: (t) => t("git.failure.worktree_dirty.recovery", "Commit or stash your changes first."),
1910
+ retryable: false
1280
1911
  }
1281
- return { error: "The mode must be existing-branch or new-branch." };
1912
+ ];
1913
+ function classifyGitFailure(operation, result, mismatch, t = english) {
1914
+ 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."));
1915
+ const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1916
+ const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1917
+ if (rule === void 0) return new PoGitExpectedError("git_failed", t("git.failure.failed", "git {operation} failed (exit {code}).", {
1918
+ operation,
1919
+ code: String(result.code)
1920
+ }), false, t("git.failure.failedRecovery", "Run the same command in a terminal in this checkout to see what git says."));
1921
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery(t)}` : rule.recovery(t);
1922
+ return new PoGitExpectedError(rule.code, rule.message(t), rule.retryable, recovery);
1282
1923
  }
1283
1924
  //#endregion
1284
- //#region src/extensions/(backend)/api/git/_lib/route.server.ts
1925
+ //#region src/services/gitSync/index.ts
1285
1926
  /**
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.
1927
+ * Manual pull, push and rebase for a session's checkout.
1291
1928
  *
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 });
1929
+ * DESIGN PATTERNS:
1930
+ * - The workspace's auth goes into the environment of the one fetch or push
1931
+ * that needs it, built fresh per call. Rebase itself runs locally and never
1932
+ * sees a credential.
1933
+ * - Fetch and rebase are separate commands, so a hung network can never leave a
1934
+ * rebase half applied.
1935
+ * - A conflicted rebase is not an error. It is left paused for the reader to
1936
+ * hand to the agent or abort, and git's own state reports it from then on.
1937
+ * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1938
+ * Untracked files only block when git says they would be overwritten.
1939
+ * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1940
+ * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1941
+ * which git refuses if the remote holds commits this branch never integrated.
1942
+ */
1943
+ const DONE = { outcome: "done" };
1944
+ function expected(code, message, recovery) {
1945
+ return new PoGitExpectedError(code, message, false, recovery);
1946
+ }
1947
+ function createGitSync(options) {
1948
+ const baseEnv = options.baseEnv ?? {};
1949
+ async function readLine(cwd, args) {
1950
+ const result = await runGit(cwd, args, {
1951
+ timeout: READ_TIMEOUT_MS,
1952
+ env: baseEnv
1953
+ });
1954
+ const out = result.stdout.trim();
1955
+ return result.code === 0 && out !== "" ? out : void 0;
1956
+ }
1957
+ async function toplevel(cwd) {
1958
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1959
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1960
+ return root;
1961
+ }
1962
+ async function rebasing(root) {
1963
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1964
+ const gitPath = await readLine(root, [
1965
+ "rev-parse",
1966
+ "--git-path",
1967
+ name
1968
+ ]);
1969
+ if (gitPath !== void 0 && await fs.access(path.resolve(root, gitPath)).then(() => true, () => false)) return true;
1970
+ }
1971
+ return false;
1972
+ }
1973
+ async function conflicts(root) {
1974
+ return (await runGit(root, [
1975
+ "diff",
1976
+ "--name-only",
1977
+ "--diff-filter=U",
1978
+ "-z"
1979
+ ], {
1980
+ timeout: READ_TIMEOUT_MS,
1981
+ env: baseEnv
1982
+ })).stdout.split("\0").filter((file) => file !== "");
1983
+ }
1984
+ async function currentBranch(root) {
1985
+ const branch = await readLine(root, [
1986
+ "symbolic-ref",
1987
+ "--quiet",
1988
+ "--short",
1989
+ "HEAD"
1990
+ ]);
1991
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1992
+ return branch;
1993
+ }
1994
+ async function guard(root, needsCleanTree) {
1995
+ 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.");
1996
+ const branch = await currentBranch(root);
1997
+ if (needsCleanTree) {
1998
+ if (await readLine(root, [
1999
+ "status",
2000
+ "--porcelain",
2001
+ "--untracked-files=no"
2002
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
2003
+ }
2004
+ return branch;
2005
+ }
2006
+ const baselines = /* @__PURE__ */ new Map();
2007
+ /** One credentialed network command against `remote`, classified on failure. */
2008
+ const network = async (root, context, remote, operation, args, urlArgs = []) => {
2009
+ const url = await readLine(root, [
2010
+ "remote",
2011
+ "get-url",
2012
+ ...urlArgs,
2013
+ remote
2014
+ ]);
2015
+ if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
2016
+ const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
2017
+ const result = await runGit(root, args, {
2018
+ timeout: NETWORK_TIMEOUT_MS,
2019
+ env: prepared.env,
2020
+ ...context.signal ? { signal: context.signal } : {}
2021
+ });
2022
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch, context.t);
2023
+ };
2024
+ /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
2025
+ const rebaseOnto = async (root, onto, context) => {
2026
+ context.signal?.throwIfAborted();
2027
+ const before = baselines.get(root) ?? await revision(root, "HEAD", {
2028
+ env: baseEnv,
2029
+ ...context.signal ? { signal: context.signal } : {}
2030
+ });
2031
+ baselines.set(root, before);
2032
+ const result = await runGit(root, ["rebase", onto], {
2033
+ timeout: REBASE_TIMEOUT_MS,
2034
+ ...context.signal ? { signal: context.signal } : {},
2035
+ env: {
2036
+ ...baseEnv,
2037
+ GIT_EDITOR: "true",
2038
+ GIT_TERMINAL_PROMPT: "0"
2039
+ }
2040
+ });
2041
+ if (result.code === 0) {
2042
+ if (before !== await revision(root, "HEAD", {
2043
+ env: baseEnv,
2044
+ ...context.signal ? { signal: context.signal } : {}
2045
+ })) await options.reapplySparse?.(root, context.signal);
2046
+ baselines.delete(root);
2047
+ return DONE;
2048
+ }
2049
+ if (await rebasing(root)) return {
2050
+ outcome: "paused",
2051
+ conflicts: await conflicts(root)
2052
+ };
2053
+ baselines.delete(root);
2054
+ throw classifyGitFailure("rebase", result, void 0, context.t);
2055
+ };
2056
+ /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
2057
+ const remoteOfRef = async (root, ref) => {
2058
+ const full = await readLine(root, [
2059
+ "rev-parse",
2060
+ "--symbolic-full-name",
2061
+ ref
2062
+ ]);
2063
+ if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
2064
+ const rest = full.slice(13);
2065
+ const cut = rest.indexOf("/");
2066
+ return cut > 0 ? rest.slice(0, cut) : void 0;
2067
+ };
2068
+ return {
2069
+ async pull(context) {
2070
+ const root = await toplevel(context.cwd);
2071
+ const branch = await guard(root, true);
2072
+ const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
2073
+ const upstream = await readLine(root, [
2074
+ "rev-parse",
2075
+ "--abbrev-ref",
2076
+ "--symbolic-full-name",
2077
+ `${branch}@{upstream}`
2078
+ ]);
2079
+ if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
2080
+ if (remote !== ".") await network(root, context, remote, "fetch", [
2081
+ "fetch",
2082
+ "--prune",
2083
+ remote
2084
+ ]);
2085
+ return rebaseOnto(root, upstream, context);
2086
+ },
2087
+ async push(context, force) {
2088
+ const root = await toplevel(context.cwd);
2089
+ const branch = await guard(root, false);
2090
+ const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
2091
+ const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
2092
+ let remote = configuredRemote;
2093
+ let target = merge;
2094
+ const args = ["push", "--porcelain"];
2095
+ if (remote === void 0 || target === void 0 || remote === ".") {
2096
+ const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
2097
+ remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
2098
+ 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.");
2099
+ target = `refs/heads/${branch}`;
2100
+ args.push("--set-upstream");
2101
+ }
2102
+ if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
2103
+ args.push(remote, `HEAD:${target}`);
2104
+ await network(root, context, remote, "push", args, ["--push"]);
2105
+ return DONE;
2106
+ },
2107
+ async rebase(context) {
2108
+ const root = await toplevel(context.cwd);
2109
+ const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
2110
+ if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
2111
+ const remote = await remoteOfRef(root, base);
2112
+ if (remote !== void 0) await network(root, context, remote, "fetch", [
2113
+ "fetch",
2114
+ "--prune",
2115
+ remote
2116
+ ]);
2117
+ return rebaseOnto(root, base, context);
2118
+ },
2119
+ async abortRebase(context) {
2120
+ const root = await toplevel(context.cwd);
2121
+ if (!await rebasing(root)) {
2122
+ baselines.delete(root);
2123
+ return DONE;
2124
+ }
2125
+ const result = await runGit(root, ["rebase", "--abort"], {
2126
+ timeout: REBASE_TIMEOUT_MS,
2127
+ env: baseEnv,
2128
+ ...context.signal ? { signal: context.signal } : {}
2129
+ });
2130
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result, void 0, context.t);
2131
+ baselines.delete(root);
2132
+ return DONE;
2133
+ }
2134
+ };
2135
+ }
2136
+ //#endregion
2137
+ //#region src/services/newSessionRequest/index.ts
2138
+ const MAX_NAME_LENGTH = 120;
2139
+ /** Trimmed text, undefined when absent or blank, false when not text at all. */
2140
+ function optionalText(value) {
2141
+ if (value === void 0) return void 0;
2142
+ if (typeof value !== "string") return false;
2143
+ const trimmed = value.trim();
2144
+ return trimmed === "" ? void 0 : trimmed;
2145
+ }
2146
+ /**
2147
+ * Validates a new-session dialog request for a worktree session. Every ref is
2148
+ * checked here, before it can reach git as a positional argument.
2149
+ */
2150
+ function newSessionRequest(body) {
2151
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "A request body is required." };
2152
+ const record = body;
2153
+ if (Object.hasOwn(record, "profile")) return { error: "Use sparseProfile for a sparse checkout, or selection.profile for a launch profile." };
2154
+ const branch = optionalText(record.branch);
2155
+ if (branch === void 0 || branch === false || !validRefName(branch)) return { error: "A valid branch name is required." };
2156
+ const name = optionalText(record.name);
2157
+ 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.` };
2158
+ if (Object.hasOwn(record, "sparseProfile") && !validSparseProfile(record.sparseProfile)) return { error: "A valid sparse profile name is required." };
2159
+ const chosen = record.selection === void 0 ? {} : parseLaunchSelection(record.selection);
2160
+ if ("error" in chosen) return chosen;
2161
+ const profile = chosen.selection?.profile;
2162
+ const named = {
2163
+ ...record.sparseProfile === void 0 ? {} : { sparseProfile: record.sparseProfile },
2164
+ ...name === void 0 ? {} : { name },
2165
+ ...profile === void 0 ? {} : { selection: { profile } }
2166
+ };
2167
+ if (record.mode === "existing-branch") {
2168
+ const remote = optionalText(record.remote);
2169
+ if (remote === false || remote !== void 0 && !validRefName(remote)) return { error: "That remote name is not valid." };
2170
+ return {
2171
+ mode: "existing-branch",
2172
+ branch,
2173
+ ...remote === void 0 ? {} : { remote },
2174
+ ...named
2175
+ };
2176
+ }
2177
+ if (record.mode === "new-branch") {
2178
+ const baseRef = optionalText(record.baseRef);
2179
+ if (baseRef === false || baseRef !== void 0 && !validRefName(baseRef)) return { error: "That base branch is not valid." };
2180
+ return {
2181
+ mode: "new-branch",
2182
+ branch,
2183
+ ...baseRef === void 0 ? {} : { baseRef },
2184
+ ...named
2185
+ };
2186
+ }
2187
+ return { error: "The mode must be existing-branch or new-branch." };
2188
+ }
2189
+ //#endregion
2190
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
2191
+ /**
2192
+ * The worktree surface the cockpit panel calls.
2193
+ *
2194
+ * Hub-scoped because worktrees are a property of a repository, not of one
2195
+ * session: the panel lists and creates them whether or not the session that
2196
+ * made them is focused, and a session-scoped API would disappear with it.
2197
+ *
2198
+ * The panel names a repository by the hub's opaque id and never by path.
2199
+ * `resolveRepository` turns that into an admitted root, so a browser cannot
2200
+ * point this at a directory the cockpit was never given.
2201
+ */
2202
+ function badRequest(message) {
2203
+ return Response.json({ error: message }, { status: 400 });
1298
2204
  }
1299
2205
  function failed(error) {
1300
2206
  if (error instanceof PoGitExpectedError) return Response.json({
@@ -1303,7 +2209,7 @@ function failed(error) {
1303
2209
  }, { status: error.retryable ? 503 : 409 });
1304
2210
  return Response.json({ error: "The worktree operation failed." }, { status: 500 });
1305
2211
  }
1306
- function createGitApi(openDirectory) {
2212
+ function createGitApi(openDirectory, dependencies = {}, translate) {
1307
2213
  return {
1308
2214
  basePath: "git",
1309
2215
  start(context) {
@@ -1317,11 +2223,81 @@ function createGitApi(openDirectory) {
1317
2223
  };
1318
2224
  const git = createWorktreeGit();
1319
2225
  const operations = createWorktreeOperations({
2226
+ ...dependencies,
1320
2227
  git,
1321
2228
  sessionService: context.sessionService,
1322
2229
  ...context.homeDirectory === void 0 ? {} : { homeDir: context.homeDirectory },
1323
2230
  ...context.environment === void 0 ? {} : { environment: context.environment }
1324
2231
  });
2232
+ const sync = createGitSync({
2233
+ homeDir: context.homeDirectory ?? context.environment?.HOME ?? "",
2234
+ baseEnv: context.environment ?? {},
2235
+ async reapplySparse(cwd, signal) {
2236
+ const record = (await createWorktreeRegistry(await registryFile(cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.path === cwd && entry.sessionId === context.sessionId);
2237
+ if (record?.sparseProfile) await operations.reapply({
2238
+ cwd,
2239
+ sessionId: context.sessionId
2240
+ }, record.id, { signal });
2241
+ }
2242
+ });
2243
+ const sessionCommand = async (request, url) => {
2244
+ if (!["/session-worktrees", "/sync"].includes(url.pathname)) return void 0;
2245
+ if (context.scope !== "session" || !context.cwd || !context.sessionId) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
2246
+ if (request.method !== "POST") return Response.json({ error: "Use POST." }, { status: 405 });
2247
+ const caller = {
2248
+ cwd: context.cwd,
2249
+ sessionId: context.sessionId
2250
+ };
2251
+ const body = await request.json().catch(() => void 0);
2252
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return badRequest("A command is required.");
2253
+ const command = body;
2254
+ if (url.pathname === "/sync") {
2255
+ if (Object.keys(command).some((key) => !["action", "force"].includes(key)) || command.force !== void 0 && typeof command.force !== "boolean") return badRequest("Unknown sync command field.");
2256
+ const recordedBaseRef = (await createWorktreeRegistry(await registryFile(caller.cwd, context.homeDirectory, context.environment)).list()).find((entry) => entry.sessionId === caller.sessionId)?.baseRef;
2257
+ const auth = await createGitAuthStore(context.homeDirectory ?? context.environment?.HOME ?? "", context.environment).read(context.sessionContext?.workspaceRoot ?? caller.cwd);
2258
+ const syncContext = {
2259
+ ...caller,
2260
+ auth,
2261
+ recordedBaseRef,
2262
+ signal: request.signal,
2263
+ ...translate ? { t: translate } : {}
2264
+ };
2265
+ if (command.action === "pull") return Response.json(await sync.pull(syncContext));
2266
+ if (command.action === "push") return Response.json(await sync.push(syncContext, command.force === true));
2267
+ if (command.action === "rebase") return Response.json(await sync.rebase(syncContext));
2268
+ if (command.action === "abort-rebase") return Response.json(await sync.abortRebase(syncContext));
2269
+ return badRequest("Unknown sync command.");
2270
+ }
2271
+ if (Object.keys(command).some((key) => ![
2272
+ "action",
2273
+ "branch",
2274
+ "baseRef",
2275
+ "sparseProfile",
2276
+ "reservationId",
2277
+ "id",
2278
+ "force",
2279
+ "folders"
2280
+ ].includes(key))) return badRequest("Unknown command field.");
2281
+ if (command.reservationId !== void 0 && (typeof command.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(command.reservationId))) return badRequest("Invalid reservation.");
2282
+ if (command.action === "create") {
2283
+ if (typeof command.branch !== "string") return badRequest("A branch is required.");
2284
+ const result = await operations.spawn(caller, {
2285
+ branch: command.branch,
2286
+ ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2287
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2288
+ ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2289
+ }, { signal: request.signal });
2290
+ return Response.json({ worktree: result });
2291
+ }
2292
+ if (command.action === "close" && typeof command.id === "string") return Response.json({ worktree: await operations.close(caller, command.id, command.force === true) });
2293
+ if (![
2294
+ "profiles",
2295
+ "expand",
2296
+ "reapply"
2297
+ ].includes(String(command.action))) return badRequest("Unknown worktree command.");
2298
+ const result = await executeRunWorktreeTool(validateParams(body), operations, caller, { signal: request.signal });
2299
+ return Response.json(result.details);
2300
+ };
1325
2301
  /**
1326
2302
  * The new-session dialog's routes: the workspace's branches, and a top-level
1327
2303
  * worktree session on one. Workspace-mounted only, and always rooted at the
@@ -1343,7 +2319,8 @@ function createGitApi(openDirectory) {
1343
2319
  remote: []
1344
2320
  } : {
1345
2321
  repository: true,
1346
- ...await git.listBranches(repositoryRoot)
2322
+ ...await git.listBranches(repositoryRoot),
2323
+ ...await operations.profiles({ cwd: repositoryRoot }, url.searchParams.get("baseRef") ?? void 0, { signal: request.signal })
1347
2324
  };
1348
2325
  return Response.json(branches);
1349
2326
  }
@@ -1378,12 +2355,13 @@ function createGitApi(openDirectory) {
1378
2355
  if ("error" in parsed) return badRequest(parsed.error);
1379
2356
  const record = await operations.spawn({ cwd: workspaceRoot }, {
1380
2357
  branch: parsed.branch,
2358
+ ...parsed.sparseProfile === void 0 ? {} : { sparseProfile: parsed.sparseProfile },
1381
2359
  checkout: parsed.mode === "existing-branch" ? "existing" : "new",
1382
2360
  ...parsed.mode === "existing-branch" && parsed.remote !== void 0 ? { remote: parsed.remote } : {},
1383
2361
  ...parsed.mode === "new-branch" && parsed.baseRef !== void 0 ? { baseRef: parsed.baseRef } : {},
1384
2362
  ...parsed.name === void 0 ? {} : { name: parsed.name },
1385
2363
  ...parsed.selection === void 0 ? {} : { selection: parsed.selection }
1386
- });
2364
+ }, { signal: request.signal });
1387
2365
  publishLifecycle(record.sessionId, record.repositoryRoot);
1388
2366
  const created = {
1389
2367
  sessionId: record.sessionId,
@@ -1465,7 +2443,7 @@ function createGitApi(openDirectory) {
1465
2443
  async fetch(request) {
1466
2444
  const url = new URL(request.url);
1467
2445
  try {
1468
- const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
2446
+ const answered = await sessionCommand(request, url) ?? await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
1469
2447
  if (answered !== void 0) return answered;
1470
2448
  } catch (error) {
1471
2449
  context.onNotice(`git request failed: ${error.name}`);
@@ -1485,6 +2463,7 @@ function createGitApi(openDirectory) {
1485
2463
  if (typeof body.branch !== "string" || body.branch.trim() === "") return badRequest("A branch is required.");
1486
2464
  const record = await operations.spawn(callerContext, {
1487
2465
  branch: body.branch,
2466
+ ...body.sparseProfile === void 0 ? {} : { sparseProfile: body.sparseProfile },
1488
2467
  ...body.baseRef === void 0 ? {} : { baseRef: body.baseRef },
1489
2468
  ...body.name === void 0 ? {} : { name: body.name }
1490
2469
  });
@@ -1510,7 +2489,8 @@ function createGitApi(openDirectory) {
1510
2489
  }
1511
2490
  //#endregion
1512
2491
  //#region src/extensions/(backend)/api/git/route.server.ts
1513
- var route_server_default = defineRoute(({ context, host, signal }) => {
2492
+ var route_server_default = defineRoute((plugin) => {
2493
+ const { context, host, signal } = plugin;
1514
2494
  let openDirectory;
1515
2495
  context.inject([PO_SHELL_SERVICE], (child) => {
1516
2496
  const shell = requirePoShell(child);
@@ -1534,285 +2514,9 @@ var route_server_default = defineRoute(({ context, host, signal }) => {
1534
2514
  return createGitApi(async (path) => {
1535
2515
  if (openDirectory === void 0) throw new Error("The host shell is unavailable.");
1536
2516
  await openDirectory(path);
1537
- });
2517
+ }, createGitOperationDependencies(plugin), (key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(host.context.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars));
1538
2518
  });
1539
2519
  //#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
2520
  //#region src/types/gitReview.ts
1817
2521
  /**
1818
2522
  * The cockpit's view of what this session changed against its base: the counts
@@ -1964,17 +2668,30 @@ function createGitChangesChannel(options = {}) {
1964
2668
  delayed.set(sessionId, timer);
1965
2669
  };
1966
2670
  const run = async (scope, command) => {
2671
+ if (options.scopedCommands) {
2672
+ const response = await host.requestSessionApi(scope, {
2673
+ basePath: "git",
2674
+ path: "/sync",
2675
+ method: "POST",
2676
+ body: JSON.stringify(command)
2677
+ });
2678
+ const result = await response.json();
2679
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The git command failed.", false, "Inspect the checkout before retrying.");
2680
+ return result;
2681
+ }
1967
2682
  const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1968
2683
  const base = await recordedBaseRef(scope);
1969
2684
  const context = {
1970
2685
  cwd: scope.cwd,
2686
+ ...options.t ? { t: (key, fallback, vars) => options.t(scope, key, fallback, vars) } : {},
1971
2687
  auth: await auth.read(workspaceRoot),
1972
2688
  ...base === void 0 ? {} : { recordedBaseRef: base }
1973
2689
  };
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);
2690
+ const sessionSync = sync;
2691
+ if (command.action === "pull") return sessionSync.pull(context);
2692
+ if (command.action === "push") return sessionSync.push(context, command.force === true);
2693
+ if (command.action === "rebase") return sessionSync.rebase(context);
2694
+ return sessionSync.abortRebase(context);
1978
2695
  };
1979
2696
  const source = {
1980
2697
  payloadFor(scope) {
@@ -2041,7 +2758,12 @@ function createGitChangesChannel(options = {}) {
2041
2758
  }
2042
2759
  //#endregion
2043
2760
  //#region src/extensions/(backend)/channel/git-changes.server.ts
2044
- var git_changes_server_default = defineChannel(createGitChangesChannel);
2761
+ var git_changes_server_default = defineChannel(({ context, host }) => createGitChangesChannel({
2762
+ homeDir: host.context.homeDirectory,
2763
+ environment: host.context.environment,
2764
+ scopedCommands: true,
2765
+ t: (scope, key, fallback, vars) => readPoLang(context)?.t(readPoPersonLocale(context)?.read() ?? canonicalLocale(scope.environment?.PO_LANG), key, fallback, vars) ?? formatMessage(fallback, vars)
2766
+ }), { context: true });
2045
2767
  //#endregion
2046
2768
  //#region src/types/webWorktrees.ts
2047
2769
  /**
@@ -2114,7 +2836,9 @@ function parseCommand(payload) {
2114
2836
  if (value.action === "create") {
2115
2837
  if (typeof value.branch !== "string" || value.branch.trim() === "") return void 0;
2116
2838
  if (value.reservationId !== void 0 && (typeof value.reservationId !== "string" || !/^[A-Za-z0-9_-]+$/u.test(value.reservationId))) return void 0;
2839
+ if (value.sparseProfile !== void 0 && (typeof value.sparseProfile !== "string" || value.sparseProfile.trim() === "")) return void 0;
2117
2840
  return {
2841
+ ...typeof value.sparseProfile === "string" ? { sparseProfile: value.sparseProfile } : {},
2118
2842
  action: "create",
2119
2843
  branch: value.branch.trim(),
2120
2844
  ...typeof value.baseRef === "string" && value.baseRef.trim() !== "" ? { baseRef: value.baseRef.trim() } : {},
@@ -2168,6 +2892,22 @@ function createWorktreesChannel(options = {}) {
2168
2892
  const parent = host.sessions().find((scope) => scope.sessionId === parentSessionId);
2169
2893
  if (parent === void 0) throw new Error("The conversation parent session is unavailable.");
2170
2894
  const branch = `po/conversation-${reservationId.slice(0, 12)}`;
2895
+ if (options.scopedCommands) {
2896
+ if (!(await host.requestSessionApi(parent, {
2897
+ basePath: "git",
2898
+ path: "/session-worktrees",
2899
+ method: "POST",
2900
+ body: JSON.stringify({
2901
+ action: "create",
2902
+ branch,
2903
+ reservationId
2904
+ }),
2905
+ ...signal ? { signal } : {}
2906
+ })).ok) throw new Error("The conversation worktree could not be created.");
2907
+ const reservations = sessionService.reservations;
2908
+ if (!reservations) throw new Error("Conversation reservations are unavailable.");
2909
+ return reservations.complete(reservationId, parentSessionId);
2910
+ }
2171
2911
  const record = await worktrees.spawn({
2172
2912
  cwd: parent.cwd,
2173
2913
  sessionId: parent.sessionId
@@ -2231,10 +2971,24 @@ function createWorktreesChannel(options = {}) {
2231
2971
  if (generations.get(scope.sessionId) !== generation) return;
2232
2972
  mark(scope, pending, error, errorTarget);
2233
2973
  };
2974
+ if (options.scopedCommands) {
2975
+ markCurrent(command.action === "create" ? `creating ${command.branch}…` : `closing ${command.id}…`, void 0, void 0);
2976
+ const response = await host.requestSessionApi(scope, {
2977
+ basePath: "git",
2978
+ path: "/session-worktrees",
2979
+ method: "POST",
2980
+ body: JSON.stringify(command)
2981
+ });
2982
+ const result = await response.json();
2983
+ if (!response.ok) throw new PoGitExpectedError(result.code ?? "git_failed", result.error ?? "The worktree operation failed.", false, "Inspect the worktree before retrying.");
2984
+ if (result.worktree) publishLifecycle(scope, result.worktree.repositoryRoot);
2985
+ return;
2986
+ }
2234
2987
  if (command.action === "create") {
2235
2988
  markCurrent(`creating ${command.branch}…`, void 0, void 0);
2236
2989
  const record = await worktrees.spawn(context, {
2237
2990
  branch: command.branch,
2991
+ ...command.sparseProfile === void 0 ? {} : { sparseProfile: command.sparseProfile },
2238
2992
  ...command.baseRef === void 0 ? {} : { baseRef: command.baseRef },
2239
2993
  ...command.reservationId === void 0 ? {} : { reservationId: command.reservationId }
2240
2994
  }, { onProgress: (label) => markCurrent(label, void 0, void 0) });
@@ -2310,7 +3064,11 @@ function createWorktreesChannel(options = {}) {
2310
3064
  }
2311
3065
  //#endregion
2312
3066
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
2313
- var git_worktrees_server_default = defineChannel(createWorktreesChannel);
3067
+ var git_worktrees_server_default = defineChannel((plugin) => createWorktreesChannel({
3068
+ homeDir: plugin.host.context.homeDirectory,
3069
+ environment: plugin.host.context.environment,
3070
+ scopedCommands: true
3071
+ }), { context: true });
2314
3072
  //#endregion
2315
3073
  //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
2316
3074
  var agent_settled_server_default = defineHook((context) => context.root.hooks[1]);
@@ -2337,8 +3095,11 @@ const via = (identity, value) => value === void 0 ? void 0 : {
2337
3095
  };
2338
3096
  const serverPlugin = defineServerPlugin({
2339
3097
  name: "@agimon-ai/po-git",
2340
- providerOverrides: composeServerProviderOverrides(root_server_default),
2341
- injects: composeRootInjects({ session: [root_server_default] }),
3098
+ providerOverrides: composeServerProviderOverrides(root_server_default$1, root_server_default),
3099
+ injects: composeRootInjects({
3100
+ workspace: [root_server_default$1],
3101
+ session: [root_server_default$1, root_server_default]
3102
+ }),
2342
3103
  host: (context) => ({
2343
3104
  get api() {
2344
3105
  return [at(route_server_default, context)];
@@ -2347,22 +3108,32 @@ const serverPlugin = defineServerPlugin({
2347
3108
  return [() => via({ frameType: "git_changes" }, at(git_changes_server_default, context)), () => via({ frameType: "git_worktrees" }, at(git_worktrees_server_default, context))];
2348
3109
  }
2349
3110
  }),
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
- }),
3111
+ workspace: async (context) => {
3112
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3113
+ return {
3114
+ ...composeRootHooks(scopeWorkspace),
3115
+ get api() {
3116
+ return [at(route_server_default, context)];
3117
+ },
3118
+ get channels() {
3119
+ 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))]);
3120
+ },
3121
+ services: [...scopeWorkspace.services ?? []]
3122
+ };
3123
+ },
2358
3124
  session: async (context) => {
2359
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
2360
- const contextSession = {
3125
+ const scopeWorkspace = await context.scopeRoot("workspace", root_server_default$1, context);
3126
+ const contextWorkspace = {
2361
3127
  ...context,
3128
+ root: scopeWorkspace.value
3129
+ };
3130
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextWorkspace);
3131
+ const contextSession = {
3132
+ ...contextWorkspace,
2362
3133
  root: scopeSession.value
2363
3134
  };
2364
3135
  return {
2365
- ...composeRootHooks(scopeSession),
3136
+ ...composeRootHooks(scopeWorkspace, scopeSession),
2366
3137
  get api() {
2367
3138
  return [at(route_server_default, context)];
2368
3139
  },
@@ -2378,9 +3149,9 @@ const serverPlugin = defineServerPlugin({
2378
3149
  get tools() {
2379
3150
  return [via({ name: "run_worktree" }, at(runWorktree_server_default, contextSession))];
2380
3151
  },
2381
- services: [...scopeSession.services ?? []],
3152
+ services: [...scopeWorkspace.services ?? [], ...scopeSession.services ?? []],
2382
3153
  get activities() {
2383
- return [...scopeSession.activities ?? []];
3154
+ return [...scopeWorkspace.activities ?? [], ...scopeSession.activities ?? []];
2384
3155
  }
2385
3156
  };
2386
3157
  }