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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,18 +20,40 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  enumerable: true
21
21
  }) : target, mod));
22
22
  //#endregion
23
+ let node_module = require("node:module");
24
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
25
+ let _agimon_ai_po_core_workspaceRegistry = require("@agimon-ai/po-core/workspaceRegistry");
26
+ let _agimon_ai_po_sparo = require("@agimon-ai/po-sparo");
27
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
23
28
  let node_child_process = require("node:child_process");
24
29
  let node_fs_promises = require("node:fs/promises");
25
30
  node_fs_promises = __toESM(node_fs_promises, 1);
31
+ let js_yaml = require("js-yaml");
26
32
  let node_crypto = require("node:crypto");
27
33
  let node_path = require("node:path");
28
34
  node_path = __toESM(node_path, 1);
29
- let js_yaml = require("js-yaml");
30
35
  let node_os = require("node:os");
31
36
  node_os = __toESM(node_os, 1);
32
37
  let node_util = require("node:util");
33
38
  let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
34
39
  let node_timers_promises = require("node:timers/promises");
40
+ let typebox_value = require("typebox/value");
41
+ let _agimon_ai_po_core_apiContracts = require("@agimon-ai/po-core/apiContracts");
42
+ let typebox = require("typebox");
43
+ let _agimon_ai_po_core_workflow = require("@agimon-ai/po-core/workflow");
44
+ //#region src/services/extensionService/index.ts
45
+ var DefaultGitExtensionService = class {
46
+ async execute() {
47
+ return {
48
+ message: "Show git worktrees owned by this session",
49
+ level: "info"
50
+ };
51
+ }
52
+ };
53
+ //#endregion
54
+ //#region src/schemas/gitEngine.ts
55
+ const GIT_ENGINE_CONTRACT = (0, _agimon_ai_po_core_serverPlugin.defineServiceContract)(_agimon_ai_po_sparo.PO_GIT_ENGINE_SERVICE, { scope: "workspace" });
56
+ //#endregion
35
57
  //#region src/services/gitCli/index.ts
36
58
  /**
37
59
  * Git, as this package needs it.
@@ -72,6 +94,7 @@ function runGit(cwd, args, options) {
72
94
  return new Promise((resolve) => {
73
95
  (0, node_child_process.execFile)("git", [...args], {
74
96
  cwd,
97
+ ...options.signal === void 0 ? {} : { signal: options.signal },
75
98
  timeout: options.timeout,
76
99
  maxBuffer: options.maxBuffer ?? MAX_OUTPUT_BYTES,
77
100
  env: {
@@ -90,6 +113,63 @@ function runGit(cwd, args, options) {
90
113
  });
91
114
  });
92
115
  }
116
+ /** Resolve a commit or configured profile blob without reading the working cone. */
117
+ async function revision(cwd, ref, options = {}) {
118
+ const result = await runGit(cwd, [
119
+ "rev-parse",
120
+ "--verify",
121
+ ref
122
+ ], {
123
+ ...options,
124
+ timeout: READ_TIMEOUT_MS
125
+ });
126
+ options.signal?.throwIfAborted();
127
+ if (result.code !== 0) throw failure("rev-parse", result);
128
+ return result.stdout.trim();
129
+ }
130
+ /** A sparse remote-only checkout creates its tracking branch in the engine. */
131
+ async function trackBranch(cwd, branch, upstream, options) {
132
+ const result = await runGit(cwd, [
133
+ "branch",
134
+ `--set-upstream-to=${upstream}`,
135
+ branch
136
+ ], {
137
+ ...options,
138
+ timeout: READ_TIMEOUT_MS
139
+ });
140
+ options.signal?.throwIfAborted();
141
+ if (result.code !== 0) throw failure("branch --set-upstream-to", result);
142
+ }
143
+ /** Read only the exact named remote branch, never a stale local tracking ref. */
144
+ async function remoteBranchHead(cwd, remote, branch, options) {
145
+ options.signal.throwIfAborted();
146
+ const configured = await runGit(cwd, [
147
+ "remote",
148
+ "get-url",
149
+ "--",
150
+ remote
151
+ ], {
152
+ ...options,
153
+ timeout: READ_TIMEOUT_MS
154
+ });
155
+ options.signal.throwIfAborted();
156
+ if (configured.code !== 0) return void 0;
157
+ const ref = `refs/heads/${branch}`;
158
+ const result = await runGit(cwd, [
159
+ "ls-remote",
160
+ "--exit-code",
161
+ "--refs",
162
+ "--",
163
+ remote,
164
+ ref
165
+ ], {
166
+ ...options,
167
+ timeout: NETWORK_TIMEOUT_MS
168
+ });
169
+ options.signal.throwIfAborted();
170
+ if (result.code !== 0) return void 0;
171
+ return result.stdout.split("\n").map((line) => line.split(" ")).find((line) => line[1] === ref)?.[0];
172
+ }
93
173
  function git(cwd, args, timeout) {
94
174
  return runGit(cwd, args, { timeout });
95
175
  }
@@ -297,11 +377,11 @@ const GIT_REVIEW_PATH = "/review";
297
377
  const GIT_REVIEW_FILE_PATH = "/review/file";
298
378
  /** Repository file, relative to the checkout root, whose `setup` commands run in every new worktree. */
299
379
  const WORKTREE_CONFIG_FILE = ".po/worktree.yaml";
300
- /**
301
- * po-runner's session command, so setup runs as a runner of the worktree session and its log
302
- * shows in Runners. Mirrors po-runner's `runnerLaunchLine`; the command follows the separator.
303
- */
304
- const WORKTREE_SETUP_LAUNCH = "/runners start name=worktree-setup --";
380
+ /** Trusted same-host setup handoff, consumed before starting the child session's runner. */
381
+ const WORKTREE_SETUP_EVENT = "git_worktree_setup";
382
+ const WORKTREE_SETUP_RUNNER = "worktree-setup";
383
+ /** A missing or slow receiver is unconfirmed, never permission to retry a shell command. */
384
+ const WORKTREE_SETUP_TIMEOUT_MS = 3e3;
305
385
  /** Installs the rift CLI. Shown to the person to copy, and named in the error an agent reads. */
306
386
  const RIFT_INSTALL_COMMAND = "npm install -g rift-snapshot";
307
387
  //#endregion
@@ -329,6 +409,256 @@ function invalidRequest(message, recovery) {
329
409
  return new PoGitExpectedError("invalid_request", message, false, recovery);
330
410
  }
331
411
  //#endregion
412
+ //#region src/services/worktreeConfig/index.ts
413
+ function object(value) {
414
+ return typeof value === "object" && value !== null && !Array.isArray(value);
415
+ }
416
+ function invalid(field) {
417
+ throw invalidRequest(`${field} is not valid.`, "Fix the worktree configuration and try again.");
418
+ }
419
+ /** Sparse checkout names are separate from the launcher's selection.profile. */
420
+ function validSparseProfile(value) {
421
+ return _agimon_ai_po_sparo.ProfileName.safeParse(value).success;
422
+ }
423
+ /** Only this plugin's supplied fields are consumed; unrelated workspace metadata is left alone. */
424
+ function readWorktreeSparseDefaults(metadata) {
425
+ if (metadata === void 0) return {};
426
+ if (!object(metadata)) return invalid("Workspace metadata");
427
+ const field = Object.hasOwn(metadata, "git") ? "git" : Object.hasOwn(metadata, "sparo") ? "sparo" : void 0;
428
+ if (field === void 0) return {};
429
+ const value = metadata[field];
430
+ if (!object(value)) return invalid(`metadata.${field}`);
431
+ const profileKey = field === "sparo" ? "profile" : "sparseProfile";
432
+ if (Object.hasOwn(value, profileKey) && !validSparseProfile(value[profileKey])) return invalid(`metadata.${field}.${profileKey}`);
433
+ if (Object.hasOwn(value, "extraFolders") && (!Array.isArray(value.extraFolders) || !value.extraFolders.every((folder) => _agimon_ai_po_sparo.ConeFolder.safeParse(folder).success))) return invalid(`metadata.${field}.extraFolders`);
434
+ return {
435
+ ...value[profileKey] === void 0 ? {} : { sparseProfile: value[profileKey] },
436
+ ...value.extraFolders === void 0 ? {} : { extraFolders: [...value.extraFolders] }
437
+ };
438
+ }
439
+ /** Parse setup and sparse policy together, without repository-specific defaults. */
440
+ function parseWorktreeConfig(text) {
441
+ let value;
442
+ try {
443
+ const documents = (0, js_yaml.loadAll)(text);
444
+ if (documents.length > 1) return invalid(WORKTREE_CONFIG_FILE);
445
+ value = documents[0];
446
+ } catch {
447
+ return invalid(WORKTREE_CONFIG_FILE);
448
+ }
449
+ if (value === void 0 || value === null) return {};
450
+ if (!object(value)) return invalid(WORKTREE_CONFIG_FILE);
451
+ const result = {};
452
+ if (Object.hasOwn(value, "setup")) {
453
+ const commands = Array.isArray(value.setup) ? value.setup : [value.setup];
454
+ if (!commands.every((command) => typeof command === "string")) return invalid(`${WORKTREE_CONFIG_FILE} setup`);
455
+ const setup = commands.filter((command) => command.trim() !== "").join(" && ");
456
+ if (setup !== "") result.setup = setup;
457
+ }
458
+ if (Object.hasOwn(value, "sparse")) {
459
+ const sparse = _agimon_ai_po_sparo.SparsePolicy.safeParse(value.sparse);
460
+ if (!sparse.success) return invalid(`${WORKTREE_CONFIG_FILE} sparse`);
461
+ result.sparse = sparse.data;
462
+ }
463
+ return result;
464
+ }
465
+ /** One snapshot per repository in this composition, including missing or invalid files. */
466
+ function createWorktreeConfigReader(input) {
467
+ const snapshots = /* @__PURE__ */ new Map();
468
+ return (root) => {
469
+ let snapshot = snapshots.get(root);
470
+ if (snapshot === void 0) {
471
+ snapshot = (async () => {
472
+ const defaults = readWorktreeSparseDefaults(await input.readMetadata?.());
473
+ let text;
474
+ try {
475
+ text = await input.readTextFile(`${root.replace(/\/$/u, "")}/${WORKTREE_CONFIG_FILE}`);
476
+ } catch (error) {
477
+ if (error instanceof Error && "code" in error && (error.code === "not_found" || error.code === "ENOENT")) return Object.keys(defaults).length === 0 ? {} : { defaults };
478
+ throw error;
479
+ }
480
+ const config = parseWorktreeConfig(text);
481
+ return Object.keys(defaults).length === 0 ? config : {
482
+ ...config,
483
+ defaults
484
+ };
485
+ })();
486
+ snapshots.set(root, snapshot);
487
+ }
488
+ return snapshot;
489
+ };
490
+ }
491
+ //#endregion
492
+ //#region src/services/worktreeEvents/index.ts
493
+ const GIT_WORKTREE_LIFECYCLE_EVENT = "git_worktree_lifecycle";
494
+ const GIT_WORKTREE_MESSAGE_EVENT = "git_worktree_message";
495
+ /**
496
+ * A session's checkout may have changed: a tool call ended, or the agent
497
+ * settled. Carries nothing but its version; the '# diff' channel recomputes.
498
+ */
499
+ const GIT_SESSION_CHANGED_EVENT = "git_session_changed";
500
+ const MAX_WORKTREE_MESSAGE_BYTES = 65536;
501
+ function isMessageParty(value) {
502
+ return value === "parent" || value === "child";
503
+ }
504
+ function parseMessage(value) {
505
+ if (typeof value !== "object" || value === null) return void 0;
506
+ const record = value;
507
+ if (record.version !== 1) return void 0;
508
+ if (typeof record.worktreeId !== "string" || record.worktreeId === "") return void 0;
509
+ if (typeof record.fromSessionId !== "string" || record.fromSessionId === "") return void 0;
510
+ if (!isMessageParty(record.from)) return void 0;
511
+ if (typeof record.text !== "string" || record.text === "") return void 0;
512
+ if (Buffer.byteLength(record.text, "utf8") > 65536) return void 0;
513
+ if (typeof record.sentAt !== "string" || record.sentAt === "") return void 0;
514
+ return record;
515
+ }
516
+ function createWorktreeMessageInbox(directEvents, sessionId) {
517
+ if (sessionId === "") throw new Error("The Git message service requires a session identity.");
518
+ const messages = /* @__PURE__ */ new Map();
519
+ const unsubscribe = directEvents.subscribe(GIT_WORKTREE_MESSAGE_EVENT, sessionId, (payload) => {
520
+ const message = parseMessage(payload);
521
+ if (message === void 0) return;
522
+ const inbox = messages.get(message.worktreeId) ?? [];
523
+ if (inbox.length >= 100) inbox.shift();
524
+ inbox.push(message);
525
+ messages.set(message.worktreeId, inbox);
526
+ });
527
+ let closed = false;
528
+ return {
529
+ send(targetSessionId, message) {
530
+ if (closed) throw new Error("The Git message service is closed.");
531
+ directEvents.publish(GIT_WORKTREE_MESSAGE_EVENT, targetSessionId, message);
532
+ },
533
+ receive(worktreeId) {
534
+ if (closed) return [];
535
+ const inbox = messages.get(worktreeId);
536
+ if (inbox === void 0) return [];
537
+ messages.delete(worktreeId);
538
+ return inbox;
539
+ },
540
+ close() {
541
+ if (closed) return;
542
+ closed = true;
543
+ unsubscribe();
544
+ messages.clear();
545
+ }
546
+ };
547
+ }
548
+ function isWorktreeLifecycleEvent(value) {
549
+ if (typeof value !== "object" || value === null) return false;
550
+ const record = value;
551
+ return record.version === 1 && typeof record.repositoryRoot === "string" && record.repositoryRoot !== "";
552
+ }
553
+ /**
554
+ * One bounded issue/receipt on the trusted host bus. Timeout and cancellation
555
+ * overwrite the retained request so a late receiver cannot run abandoned setup.
556
+ * There are deliberately no retries: a lost receipt can mean the runner exists.
557
+ */
558
+ function startWorktreeSetup(directEvents, sessionId, command, signal) {
559
+ if (signal?.aborted) return Promise.resolve("unconfirmed");
560
+ const requestId = (0, node_crypto.randomUUID)();
561
+ return new Promise((resolve) => {
562
+ let settled = false;
563
+ const finish = (stage) => {
564
+ if (settled) return;
565
+ settled = true;
566
+ clearTimeout(timer);
567
+ unsubscribe();
568
+ signal?.removeEventListener("abort", abort);
569
+ if (stage === "unconfirmed") directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
570
+ version: 1,
571
+ kind: "cancel",
572
+ requestId
573
+ });
574
+ resolve(stage);
575
+ };
576
+ const abort = () => finish("unconfirmed");
577
+ const unsubscribe = directEvents.subscribe(WORKTREE_SETUP_EVENT, sessionId, (value) => {
578
+ if (!value || typeof value !== "object") return;
579
+ const receipt = value;
580
+ if (receipt.version !== 1 || receipt.kind !== "receipt" || receipt.requestId !== requestId) return;
581
+ if (receipt.stage === "started" || receipt.stage === "failed" || receipt.stage === "unconfirmed") finish(receipt.stage);
582
+ });
583
+ const timer = setTimeout(() => finish("unconfirmed"), WORKTREE_SETUP_TIMEOUT_MS);
584
+ signal?.addEventListener("abort", abort, { once: true });
585
+ if (signal?.aborted) abort();
586
+ if (!settled) directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
587
+ version: 1,
588
+ kind: "request",
589
+ requestId,
590
+ command
591
+ });
592
+ });
593
+ }
594
+ /**
595
+ * Runs only under the child's runner service injection. This receiver never
596
+ * reads the registry: the parent can hold its transaction through the receipt.
597
+ * Consuming retained requests synchronously prevents a remount replaying setup.
598
+ */
599
+ function receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal) {
600
+ const pending = /* @__PURE__ */ new Map();
601
+ const seen = /* @__PURE__ */ new Set();
602
+ let closed = false;
603
+ let unsubscribe = () => {};
604
+ const receipt = (requestId, stage) => directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
605
+ version: 1,
606
+ kind: "receipt",
607
+ requestId,
608
+ stage
609
+ });
610
+ const close = () => {
611
+ if (closed) return;
612
+ closed = true;
613
+ unsubscribe();
614
+ signal?.removeEventListener("abort", close);
615
+ for (const [requestId, controller] of pending) {
616
+ controller.abort();
617
+ receipt(requestId, "unconfirmed");
618
+ }
619
+ pending.clear();
620
+ };
621
+ if (signal?.aborted) return close;
622
+ unsubscribe = directEvents.subscribe(WORKTREE_SETUP_EVENT, sessionId, (value) => {
623
+ if (closed || !value || typeof value !== "object") return;
624
+ const event = value;
625
+ if (event.version !== 1 || typeof event.requestId !== "string" || !event.requestId) return;
626
+ const requestId = event.requestId;
627
+ if (event.kind === "cancel") {
628
+ pending.get(requestId)?.abort();
629
+ return;
630
+ }
631
+ if (event.kind !== "request" || typeof event.command !== "string" || !event.command.trim() || seen.has(requestId)) return;
632
+ seen.add(requestId);
633
+ const command = event.command;
634
+ const controller = new AbortController();
635
+ pending.set(requestId, controller);
636
+ directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
637
+ version: 1,
638
+ kind: "consumed",
639
+ requestId
640
+ });
641
+ Promise.resolve().then(async () => {
642
+ controller.signal.throwIfAborted();
643
+ await runner.start({
644
+ name: WORKTREE_SETUP_RUNNER,
645
+ command: [command],
646
+ cwd,
647
+ wakeOnExit: true
648
+ }, controller.signal);
649
+ if (!controller.signal.aborted && !closed) receipt(requestId, "started");
650
+ }).catch(() => {
651
+ if (!closed) receipt(requestId, controller.signal.aborted ? "unconfirmed" : "failed");
652
+ }).finally(() => pending.delete(requestId));
653
+ }, { replayLatest: true });
654
+ signal?.addEventListener("abort", close, { once: true });
655
+ if (signal?.aborted) close();
656
+ return close;
657
+ }
658
+ function isSessionChangedEvent(value) {
659
+ return typeof value === "object" && value !== null && value.version === 1;
660
+ }
661
+ //#endregion
332
662
  //#region src/services/atomicJson/index.ts
333
663
  const OWNER_ONLY_FILE = 384;
334
664
  /**
@@ -427,6 +757,803 @@ function shortId(seed) {
427
757
  return (0, node_crypto.createHash)("sha256").update(seed).digest("hex").slice(0, 8);
428
758
  }
429
759
  //#endregion
760
+ //#region src/schemas/apiContracts.ts
761
+ const S = typebox.Type.String();
762
+ const B = typebox.Type.Boolean();
763
+ const O$1 = typebox.Type.Optional;
764
+ const SparseProfileSchema = typebox.Type.String({ pattern: "^[A-Za-z0-9][A-Za-z0-9_-]*$" });
765
+ const SelectionSchema = typebox.Type.Object({ profile: typebox.Type.Union([S, typebox.Type.Null()]) });
766
+ const literals = (values) => typebox.Type.Union(values.map((value) => typebox.Type.Literal(value)));
767
+ const WorktreeRecordSchema = typebox.Type.Object({
768
+ version: typebox.Type.Literal(2),
769
+ id: S,
770
+ branch: S,
771
+ baseRef: S,
772
+ path: S,
773
+ repositoryRoot: S,
774
+ sessionId: S,
775
+ parentSessionId: typebox.Type.Optional(S),
776
+ status: literals([
777
+ "spawning",
778
+ "running",
779
+ "closing",
780
+ "orphaned"
781
+ ]),
782
+ setupStage: O$1(literals([
783
+ "none",
784
+ "started",
785
+ "failed",
786
+ "unconfirmed"
787
+ ])),
788
+ backend: O$1(typebox.Type.Literal("rift")),
789
+ sparseProfile: O$1(SparseProfileSchema),
790
+ extraFolders: O$1(typebox.Type.Array(S)),
791
+ sparseFingerprint: O$1(S),
792
+ baseCommit: O$1(S),
793
+ workflow: O$1(typebox.Type.Object({
794
+ attemptId: S,
795
+ fingerprint: S,
796
+ state: literals([
797
+ "spawned",
798
+ "admitted",
799
+ "retained"
800
+ ]),
801
+ admissionId: O$1(S),
802
+ runId: O$1(S),
803
+ reason: O$1(S)
804
+ })),
805
+ createdAt: S
806
+ });
807
+ const ErrorTargetSchema = typebox.Type.Union([typebox.Type.Object({
808
+ action: typebox.Type.Literal("create"),
809
+ riftMissing: O$1(typebox.Type.Literal(true))
810
+ }), typebox.Type.Object({
811
+ action: typebox.Type.Literal("close"),
812
+ id: S
813
+ })]);
814
+ const WorktreesPayloadSchema = typebox.Type.Object({
815
+ worktrees: typebox.Type.Array(typebox.Type.Object({
816
+ id: S,
817
+ branch: S,
818
+ path: S,
819
+ sessionId: typebox.Type.Union([S, typebox.Type.Null()]),
820
+ orphaned: B,
821
+ unowned: B
822
+ })),
823
+ pending: O$1(S),
824
+ error: O$1(S),
825
+ errorTarget: O$1(ErrorTargetSchema)
826
+ });
827
+ const WorktreesCommandSchema = typebox.Type.Union([typebox.Type.Object({
828
+ action: typebox.Type.Literal("create"),
829
+ branch: S,
830
+ baseRef: O$1(S),
831
+ reservationId: O$1(typebox.Type.String({
832
+ minLength: 1,
833
+ pattern: "^[A-Za-z0-9_-]+$"
834
+ }))
835
+ }), typebox.Type.Object({
836
+ action: typebox.Type.Literal("close"),
837
+ id: S,
838
+ force: O$1(B)
839
+ })]);
840
+ const N = typebox.Type.Integer({ minimum: 0 });
841
+ const ChangesSchema = typebox.Type.Object({
842
+ branch: O$1(S),
843
+ base: O$1(S),
844
+ added: N,
845
+ removed: N,
846
+ files: N,
847
+ truncated: O$1(B),
848
+ upstream: O$1(typebox.Type.Object({
849
+ ref: S,
850
+ ahead: N,
851
+ behind: N
852
+ })),
853
+ rebase: O$1(typebox.Type.Object({ conflicts: typebox.Type.Array(S) }))
854
+ });
855
+ const SyncErrorTargetSchema = typebox.Type.Union([typebox.Type.Object({ action: literals([
856
+ "pull",
857
+ "rebase",
858
+ "abort-rebase"
859
+ ]) }), typebox.Type.Object({
860
+ action: typebox.Type.Literal("push"),
861
+ forceRequired: O$1(typebox.Type.Literal(true))
862
+ })]);
863
+ const GitChangesPayloadSchema = typebox.Type.Object({
864
+ changes: O$1(ChangesSchema),
865
+ pending: O$1(S),
866
+ error: O$1(S),
867
+ errorTarget: O$1(SyncErrorTargetSchema)
868
+ });
869
+ const GitChangesCommandSchema = typebox.Type.Union([typebox.Type.Object({ action: literals([
870
+ "pull",
871
+ "rebase",
872
+ "abort-rebase"
873
+ ]) }), typebox.Type.Object({
874
+ action: typebox.Type.Literal("push"),
875
+ force: O$1(typebox.Type.Literal(true))
876
+ })]);
877
+ const AuthViewSchema = typebox.Type.Object({
878
+ method: literals([
879
+ "none",
880
+ "ssh",
881
+ "https"
882
+ ]),
883
+ ssh: O$1(typebox.Type.Object({ keyPath: O$1(S) })),
884
+ https: O$1(typebox.Type.Object({
885
+ host: S,
886
+ username: S,
887
+ hasToken: B
888
+ }))
889
+ });
890
+ const AuthSaveSchema = typebox.Type.Union([
891
+ typebox.Type.Object({ method: typebox.Type.Literal("none") }),
892
+ typebox.Type.Object({
893
+ method: typebox.Type.Literal("ssh"),
894
+ keyPath: O$1(S)
895
+ }),
896
+ typebox.Type.Object({
897
+ method: typebox.Type.Literal("https"),
898
+ host: S,
899
+ username: S,
900
+ token: O$1(typebox.Type.String({ writeOnly: true }))
901
+ })
902
+ ]);
903
+ const DiffRowSchema = typebox.Type.Object({
904
+ marker: literals([
905
+ "+",
906
+ "-",
907
+ " "
908
+ ]),
909
+ line: N,
910
+ content: S
911
+ });
912
+ const ReviewSummarySchema = typebox.Type.Object({
913
+ repository: B,
914
+ branch: O$1(S),
915
+ base: O$1(S),
916
+ mergeBase: O$1(S),
917
+ truncated: O$1(B),
918
+ files: typebox.Type.Array(typebox.Type.Object({
919
+ path: S,
920
+ status: literals([
921
+ "added",
922
+ "modified",
923
+ "deleted",
924
+ "untracked",
925
+ "conflicted"
926
+ ]),
927
+ added: N,
928
+ removed: N,
929
+ binary: O$1(B)
930
+ }))
931
+ });
932
+ const ReviewFileSchema = typebox.Type.Object({
933
+ path: S,
934
+ hunks: typebox.Type.Array(typebox.Type.Object({
935
+ start: N,
936
+ rows: typebox.Type.Array(DiffRowSchema)
937
+ })),
938
+ binary: O$1(typebox.Type.Literal(true)),
939
+ tooLarge: O$1(typebox.Type.Literal(true))
940
+ });
941
+ const query = [{
942
+ name: "repositoryId",
943
+ in: "query",
944
+ required: true,
945
+ schema: S
946
+ }, {
947
+ name: "sessionId",
948
+ in: "query",
949
+ required: true,
950
+ schema: S
951
+ }];
952
+ (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
953
+ version: 1,
954
+ dynamic: [],
955
+ http: ["host", "workspace"].flatMap((scope) => [
956
+ {
957
+ id: "git.list",
958
+ scope,
959
+ basePath: "git",
960
+ path: "/worktrees",
961
+ method: "GET",
962
+ authentication: "owner",
963
+ description: "List admitted repository worktrees.",
964
+ parameters: query.map((item) => ({
965
+ ...item,
966
+ required: item.name === "repositoryId"
967
+ })),
968
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ worktrees: typebox.Type.Array(WorktreeRecordSchema) }))
969
+ },
970
+ {
971
+ id: "git.create",
972
+ scope,
973
+ basePath: "git",
974
+ path: "/worktrees",
975
+ method: "POST",
976
+ authentication: "owner",
977
+ description: "Create a worktree and session.",
978
+ parameters: query,
979
+ body: {
980
+ required: true,
981
+ contentType: "application/json",
982
+ schema: typebox.Type.Object({
983
+ branch: typebox.Type.String({ minLength: 1 }),
984
+ baseRef: O$1(S),
985
+ name: O$1(S),
986
+ sparseProfile: O$1(SparseProfileSchema),
987
+ selection: O$1(SelectionSchema)
988
+ })
989
+ },
990
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ worktree: WorktreeRecordSchema }), 201)
991
+ },
992
+ {
993
+ id: "git.close",
994
+ scope,
995
+ basePath: "git",
996
+ path: "/worktrees/{id}",
997
+ method: "DELETE",
998
+ authentication: "owner",
999
+ description: "Close a worktree.",
1000
+ parameters: [...query, {
1001
+ name: "force",
1002
+ in: "query",
1003
+ required: false,
1004
+ schema: B
1005
+ }],
1006
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ worktree: WorktreeRecordSchema }))
1007
+ },
1008
+ ...scope === "workspace" ? [
1009
+ {
1010
+ id: "git.auth.read",
1011
+ scope,
1012
+ basePath: "git",
1013
+ path: "/auth",
1014
+ method: "GET",
1015
+ authentication: "owner",
1016
+ description: "Read a workspace's remote auth for manual sync. The token is never returned.",
1017
+ parameters: [{
1018
+ name: "repositoryId",
1019
+ in: "query",
1020
+ required: true,
1021
+ schema: S
1022
+ }],
1023
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(AuthViewSchema)
1024
+ },
1025
+ {
1026
+ id: "git.auth.save",
1027
+ scope,
1028
+ basePath: "git",
1029
+ path: "/auth",
1030
+ method: "PUT",
1031
+ authentication: "owner",
1032
+ description: "Replace a workspace's remote auth. Passkey step-up gated for remote devices.",
1033
+ parameters: [{
1034
+ name: "repositoryId",
1035
+ in: "query",
1036
+ required: true,
1037
+ schema: S
1038
+ }],
1039
+ body: {
1040
+ required: true,
1041
+ contentType: "application/json",
1042
+ schema: AuthSaveSchema
1043
+ },
1044
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(AuthViewSchema)
1045
+ },
1046
+ {
1047
+ id: "git.branches",
1048
+ scope,
1049
+ basePath: "git",
1050
+ path: "/branches",
1051
+ method: "GET",
1052
+ authentication: "owner",
1053
+ description: "List the workspace branches for the new-session dialog.",
1054
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({
1055
+ repository: B,
1056
+ current: O$1(S),
1057
+ defaultBase: O$1(S),
1058
+ sparseProfiles: O$1(typebox.Type.Array(S)),
1059
+ defaultSparseProfile: O$1(S),
1060
+ local: typebox.Type.Array(typebox.Type.Object({
1061
+ name: S,
1062
+ checkedOutAt: O$1(S)
1063
+ })),
1064
+ remote: typebox.Type.Array(typebox.Type.Object({
1065
+ remote: S,
1066
+ name: S
1067
+ }))
1068
+ }))
1069
+ },
1070
+ {
1071
+ id: "git.branches.delete",
1072
+ scope,
1073
+ basePath: "git",
1074
+ path: "/branches",
1075
+ method: "DELETE",
1076
+ authentication: "owner",
1077
+ description: "Safely delete a local branch that is not checked out. Never force-deletes unmerged work.",
1078
+ body: {
1079
+ required: true,
1080
+ contentType: "application/json",
1081
+ schema: typebox.Type.Object({ branch: S })
1082
+ },
1083
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ deleted: B }))
1084
+ },
1085
+ {
1086
+ id: "git.branches.open",
1087
+ scope,
1088
+ basePath: "git",
1089
+ path: "/branches/open",
1090
+ method: "POST",
1091
+ authentication: "owner",
1092
+ description: "Open the branch checkout in Finder. Local callers only, no client-supplied path.",
1093
+ body: {
1094
+ required: true,
1095
+ contentType: "application/json",
1096
+ schema: typebox.Type.Object({ branch: S })
1097
+ },
1098
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ opened: B }))
1099
+ },
1100
+ {
1101
+ id: "git.sessions.create",
1102
+ scope,
1103
+ basePath: "git",
1104
+ path: "/sessions",
1105
+ method: "POST",
1106
+ authentication: "owner",
1107
+ description: "Start a top-level worktree session on an existing or new branch.",
1108
+ body: {
1109
+ required: true,
1110
+ contentType: "application/json",
1111
+ schema: typebox.Type.Union([typebox.Type.Object({
1112
+ mode: typebox.Type.Literal("existing-branch"),
1113
+ branch: S,
1114
+ remote: O$1(S),
1115
+ name: O$1(S),
1116
+ sparseProfile: O$1(SparseProfileSchema),
1117
+ selection: O$1(SelectionSchema)
1118
+ }), typebox.Type.Object({
1119
+ mode: typebox.Type.Literal("new-branch"),
1120
+ branch: S,
1121
+ baseRef: O$1(S),
1122
+ name: O$1(S),
1123
+ sparseProfile: O$1(SparseProfileSchema),
1124
+ selection: O$1(SelectionSchema)
1125
+ })])
1126
+ },
1127
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({
1128
+ sessionId: S,
1129
+ worktreeId: S
1130
+ }), 201)
1131
+ }
1132
+ ] : [],
1133
+ ...scope === "host" ? [{
1134
+ id: "git.review.summary",
1135
+ scope: "session",
1136
+ basePath: "git",
1137
+ path: "/review",
1138
+ method: "GET",
1139
+ authentication: "owner",
1140
+ description: "List the files the session's checkout changed against its base.",
1141
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(ReviewSummarySchema)
1142
+ }, {
1143
+ id: "git.review.file",
1144
+ scope: "session",
1145
+ basePath: "git",
1146
+ path: "/review/file",
1147
+ method: "GET",
1148
+ authentication: "owner",
1149
+ description: "One changed file's hunks; the path must be in the session's change set.",
1150
+ parameters: [{
1151
+ name: "path",
1152
+ in: "query",
1153
+ required: true,
1154
+ schema: typebox.Type.String({ minLength: 1 })
1155
+ }],
1156
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(ReviewFileSchema)
1157
+ }] : []
1158
+ ]),
1159
+ sockets: ["host", "workspace"].flatMap((scope) => [
1160
+ {
1161
+ id: "git.changes.channel",
1162
+ scope,
1163
+ service: "po.hub",
1164
+ member: "git_changes",
1165
+ kind: "channel",
1166
+ direction: "server-to-client",
1167
+ description: "The session's change against its base, and manual sync state.",
1168
+ input: GitChangesPayloadSchema
1169
+ },
1170
+ {
1171
+ id: "git.changes.command",
1172
+ scope,
1173
+ service: "po.hub",
1174
+ member: "git_changes",
1175
+ kind: "channel",
1176
+ direction: "client-to-server",
1177
+ description: "Manual pull, push, rebase or abort-rebase for the session.",
1178
+ input: GitChangesCommandSchema
1179
+ },
1180
+ {
1181
+ id: "git.channel",
1182
+ scope,
1183
+ service: "po.hub",
1184
+ member: "git_worktrees",
1185
+ kind: "channel",
1186
+ direction: "server-to-client",
1187
+ description: "Worktree channel payload.",
1188
+ input: WorktreesPayloadSchema
1189
+ },
1190
+ {
1191
+ id: "git.command",
1192
+ scope,
1193
+ service: "po.hub",
1194
+ member: "git_worktrees",
1195
+ kind: "channel",
1196
+ direction: "client-to-server",
1197
+ description: "Worktree channel command payload.",
1198
+ input: WorktreesCommandSchema
1199
+ }
1200
+ ])
1201
+ });
1202
+ //#endregion
1203
+ //#region src/schemas/worktreeWorkflows.ts
1204
+ const PO_GIT_WORKFLOWS_SERVICE = "po/git-workflows";
1205
+ const GIT_WORKFLOWS_CONTRACT = (0, _agimon_ai_po_core_serverPlugin.defineServiceContract)(PO_GIT_WORKFLOWS_SERVICE, { scope: "session" });
1206
+ const Text = typebox.Type.String({ minLength: 1 });
1207
+ const O = typebox.Type.Optional;
1208
+ const Binding = O(typebox.Type.Unknown());
1209
+ const WorktreeWorkflowAttemptSchema = typebox.Type.Object({
1210
+ attemptId: Text,
1211
+ fingerprint: Text,
1212
+ launcherSessionId: Text,
1213
+ branch: Text,
1214
+ definition: O(_agimon_ai_po_core_workflow.PoWorkflowDefinitionRefSchema),
1215
+ createdAt: Text,
1216
+ state: typebox.Type.Union([
1217
+ "reserved",
1218
+ "spawned",
1219
+ "admitting",
1220
+ "admitted",
1221
+ "retained",
1222
+ "closed",
1223
+ "rejected"
1224
+ ].map((state) => typebox.Type.Literal(state))),
1225
+ worktreeId: O(Text),
1226
+ sessionId: O(Text),
1227
+ admission: O(typebox.Type.Union([
1228
+ typebox.Type.Object({
1229
+ attemptId: Text,
1230
+ admissionId: Text,
1231
+ state: typebox.Type.Literal("pending"),
1232
+ binding: Binding
1233
+ }),
1234
+ typebox.Type.Object({
1235
+ attemptId: Text,
1236
+ admissionId: Text,
1237
+ state: typebox.Type.Literal("rejected"),
1238
+ errors: typebox.Type.Array(Text)
1239
+ }),
1240
+ typebox.Type.Object({
1241
+ attemptId: Text,
1242
+ admissionId: Text,
1243
+ state: typebox.Type.Literal("registered"),
1244
+ run: _agimon_ai_po_core_workflow.PoWorkflowRunRefSchema,
1245
+ binding: Binding
1246
+ })
1247
+ ]))
1248
+ });
1249
+ /** Model-facing repository launch only. Trusted overrides and allocation never cross this boundary. */
1250
+ const StartWorktreeWorkflowSchema = typebox.Type.Object({
1251
+ key: Text,
1252
+ attemptId: O(Text),
1253
+ branch: O(Text),
1254
+ sparseProfile: O(Text),
1255
+ inputs: O(typebox.Type.Record(typebox.Type.String(), typebox.Type.String()))
1256
+ }, { additionalProperties: false });
1257
+ //#endregion
1258
+ //#region src/services/worktreeRegistry/index.ts
1259
+ const LOCK_WAIT_MS = 5e3;
1260
+ const LOCK_RETRY_MS = 25;
1261
+ function malformedRegistry() {
1262
+ throw new PoGitExpectedError("registry_read_failed", "The worktree registry is unreadable or malformed.", false, "Inspect and repair the registry before retrying. It has not been replaced.");
1263
+ }
1264
+ /** Explicit v1/v2 read compatibility. Nothing is rewritten until a caller replaces the file. */
1265
+ function parseWorktreeRegistry(value) {
1266
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return malformedRegistry();
1267
+ const file = value;
1268
+ if (file.version !== 1 && file.version !== 2 || !Array.isArray(file.entries)) return malformedRegistry();
1269
+ if (Object.hasOwn(file, "workflowAttempts")) {
1270
+ if (file.version !== 2 || !Array.isArray(file.workflowAttempts)) return malformedRegistry();
1271
+ const keys = /* @__PURE__ */ new Set();
1272
+ for (const attempt of file.workflowAttempts) {
1273
+ if (!(0, typebox_value.Check)(WorktreeWorkflowAttemptSchema, attempt)) return malformedRegistry();
1274
+ const key = JSON.stringify([attempt.launcherSessionId, attempt.attemptId]);
1275
+ if (keys.has(key)) return malformedRegistry();
1276
+ keys.add(key);
1277
+ if (attempt.admission && attempt.admission.attemptId !== attempt.attemptId) return malformedRegistry();
1278
+ if (attempt.admission?.state === "registered" && attempt.admission.run.ownerSessionId !== attempt.sessionId) return malformedRegistry();
1279
+ }
1280
+ }
1281
+ if (Object.hasOwn(file, "sparoImport")) {
1282
+ const marker = file.sparoImport;
1283
+ if (file.version !== 2 || !marker || typeof marker !== "object" || Array.isArray(marker) || typeof marker.source !== "string" || !node_path.default.isAbsolute(marker.source) || typeof marker.sourceDigest !== "string" || !/^[a-f0-9]{64}$/u.test(marker.sourceDigest) || typeof marker.completedAt !== "string" || !Number.isFinite(Date.parse(marker.completedAt)) || !Array.isArray(marker.recordIds) || !marker.recordIds.every((id) => typeof id === "string" && id !== "")) return malformedRegistry();
1284
+ }
1285
+ return file.entries.map((value) => {
1286
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return malformedRegistry();
1287
+ const record = value;
1288
+ if (record.version !== file.version) return malformedRegistry();
1289
+ if (file.version === 1 && [
1290
+ "sparseProfile",
1291
+ "extraFolders",
1292
+ "sparseFingerprint"
1293
+ ].some((key) => Object.hasOwn(record, key))) return malformedRegistry();
1294
+ const normalized = {
1295
+ ...record,
1296
+ version: 2
1297
+ };
1298
+ if (!(0, typebox_value.Check)(WorktreeRecordSchema, normalized) || normalized.id === "") return malformedRegistry();
1299
+ if (Object.hasOwn(record, "sparseProfile") && !_agimon_ai_po_sparo.ProfileName.safeParse(record.sparseProfile).success) return malformedRegistry();
1300
+ if (Object.hasOwn(record, "extraFolders") && (!Array.isArray(record.extraFolders) || !record.extraFolders.every((folder) => _agimon_ai_po_sparo.ConeFolder.safeParse(folder).success))) return malformedRegistry();
1301
+ return normalized;
1302
+ });
1303
+ }
1304
+ /** Read metadata and records together, with the same fail-closed validation. */
1305
+ async function readWorktreeRegistryFile(file) {
1306
+ let text;
1307
+ try {
1308
+ text = await node_fs_promises.default.readFile(file, "utf8");
1309
+ } catch (error) {
1310
+ if (error.code === "ENOENT") return {
1311
+ version: 2,
1312
+ entries: []
1313
+ };
1314
+ return malformedRegistry();
1315
+ }
1316
+ let parsed;
1317
+ try {
1318
+ parsed = JSON.parse(text);
1319
+ } catch {
1320
+ return malformedRegistry();
1321
+ }
1322
+ const entries = parseWorktreeRegistry(parsed);
1323
+ const { sparoImport } = parsed;
1324
+ const workflowAttempts = [...parsed.workflowAttempts ?? []];
1325
+ for (const record of entries) {
1326
+ if (!record.workflow || !record.parentSessionId || workflowAttempts.some((attempt) => attempt.launcherSessionId === record.parentSessionId && attempt.attemptId === record.workflow.attemptId)) continue;
1327
+ workflowAttempts.push({
1328
+ attemptId: record.workflow.attemptId,
1329
+ fingerprint: record.workflow.fingerprint,
1330
+ launcherSessionId: record.parentSessionId,
1331
+ branch: record.branch,
1332
+ createdAt: record.createdAt,
1333
+ state: record.workflow.state,
1334
+ worktreeId: record.id,
1335
+ sessionId: record.sessionId
1336
+ });
1337
+ }
1338
+ return {
1339
+ version: 2,
1340
+ entries,
1341
+ ...sparoImport ? { sparoImport } : {},
1342
+ ...workflowAttempts.length ? { workflowAttempts } : {}
1343
+ };
1344
+ }
1345
+ /**
1346
+ * Repository mutations hold an exclusive directory lock from the read through
1347
+ * the final commit. This works across independently loaded packages and hosts.
1348
+ * A crashed owner leaves a visible lock, never a lease another writer may steal.
1349
+ */
1350
+ function createWorktreeRegistry(file, options = {}) {
1351
+ return {
1352
+ async list() {
1353
+ return [...(await readWorktreeRegistryFile(file)).entries];
1354
+ },
1355
+ async workflowAttempts() {
1356
+ return [...(await readWorktreeRegistryFile(file)).workflowAttempts ?? []];
1357
+ },
1358
+ async replaceWorkflowAttempts(workflowAttempts) {
1359
+ const value = {
1360
+ ...await readWorktreeRegistryFile(file),
1361
+ workflowAttempts
1362
+ };
1363
+ parseWorktreeRegistry(value);
1364
+ await writeJsonAtomic(file, value);
1365
+ },
1366
+ async replace(entries) {
1367
+ const previous = await readWorktreeRegistryFile(file);
1368
+ const value = {
1369
+ version: 2,
1370
+ entries,
1371
+ ...previous.sparoImport ? { sparoImport: previous.sparoImport } : {},
1372
+ ...previous.workflowAttempts ? { workflowAttempts: previous.workflowAttempts } : {}
1373
+ };
1374
+ parseWorktreeRegistry(value);
1375
+ await writeJsonAtomic(file, value);
1376
+ },
1377
+ async transaction(operation, signal) {
1378
+ const lock = `${file}.lock`;
1379
+ if (options.createDirectory !== false) await node_fs_promises.default.mkdir(node_path.default.dirname(file), { recursive: true });
1380
+ const deadline = Date.now() + LOCK_WAIT_MS;
1381
+ for (;;) {
1382
+ signal?.throwIfAborted();
1383
+ try {
1384
+ await node_fs_promises.default.mkdir(lock, { mode: 448 });
1385
+ break;
1386
+ } catch (error) {
1387
+ if (error.code !== "EEXIST") throw error;
1388
+ if (Date.now() >= deadline) throw new PoGitExpectedError("registry_busy", "Another worktree operation holds the repository registry.", true, "Retry after it finishes. After a host crash, inspect and remove the abandoned worktrees.json.lock directory.");
1389
+ await (0, node_timers_promises.setTimeout)(LOCK_RETRY_MS, void 0, { signal });
1390
+ }
1391
+ }
1392
+ try {
1393
+ await node_fs_promises.default.writeFile(node_path.default.join(lock, "owner.json"), JSON.stringify({
1394
+ pid: process.pid,
1395
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1396
+ }), { mode: 384 });
1397
+ signal?.throwIfAborted();
1398
+ return await operation();
1399
+ } finally {
1400
+ await node_fs_promises.default.rm(lock, { recursive: true });
1401
+ }
1402
+ }
1403
+ };
1404
+ }
1405
+ //#endregion
1406
+ //#region src/services/sparoRegistryImport/index.ts
1407
+ function refuse(reason) {
1408
+ throw new Error(`Sparo registry import refused: ${reason}. No import was committed.`);
1409
+ }
1410
+ function sourceEntries(text) {
1411
+ let value;
1412
+ try {
1413
+ value = JSON.parse(text);
1414
+ } catch {
1415
+ return refuse("malformed source JSON");
1416
+ }
1417
+ if (!value || typeof value !== "object" || Array.isArray(value)) return refuse("malformed source registry");
1418
+ const file = value;
1419
+ if (file.version !== 2 || !Array.isArray(file.entries)) return refuse("expected Sparo v2 records");
1420
+ return parseWorktreeRegistry({
1421
+ version: 2,
1422
+ entries: file.entries.map((value) => {
1423
+ if (!value || typeof value !== "object" || Array.isArray(value)) return refuse("malformed source record");
1424
+ const record = value;
1425
+ if (record.version !== 2 || record.provider !== "po-sparo" || record.backend !== void 0) return refuse("unsupported source provider or backend");
1426
+ if (["sparseProfile", "sparseFingerprint"].some((key) => Object.hasOwn(record, key))) return refuse("source contains destination-only sparse fields");
1427
+ for (const key of [
1428
+ "baseCommit",
1429
+ "fingerprint",
1430
+ "reservationId"
1431
+ ]) if (Object.hasOwn(record, key) && (typeof record[key] !== "string" || record[key] === "")) return refuse(`invalid ${key}`);
1432
+ if (Object.hasOwn(record, "setupStage") && ![
1433
+ "none",
1434
+ "started",
1435
+ "failed"
1436
+ ].includes(String(record.setupStage))) return refuse("invalid setup stage");
1437
+ if (Object.hasOwn(record, "workflow")) {
1438
+ const workflow = record.workflow;
1439
+ if (!workflow || typeof workflow !== "object" || Array.isArray(workflow)) return refuse("invalid workflow");
1440
+ const evidence = workflow;
1441
+ for (const key of ["attemptId", "fingerprint"]) if (typeof evidence[key] !== "string" || evidence[key] === "") return refuse(`invalid workflow ${key}`);
1442
+ if (![
1443
+ "spawned",
1444
+ "admitted",
1445
+ "retained"
1446
+ ].includes(String(evidence.state))) return refuse("invalid workflow state");
1447
+ for (const key of [
1448
+ "admissionId",
1449
+ "runId",
1450
+ "reason"
1451
+ ]) if (Object.hasOwn(evidence, key) && typeof evidence[key] !== "string") return refuse(`invalid workflow ${key}`);
1452
+ }
1453
+ const { profile, fingerprint, ...preserved } = record;
1454
+ return {
1455
+ ...preserved,
1456
+ provider: "po-git",
1457
+ ...Object.hasOwn(record, "profile") ? { sparseProfile: profile } : {},
1458
+ ...Object.hasOwn(record, "fingerprint") ? { sparseFingerprint: fingerprint } : {}
1459
+ };
1460
+ })
1461
+ });
1462
+ }
1463
+ /**
1464
+ * The caller has stopped po-sparo. Destination lock is outermost; the source's
1465
+ * actual directory-lock protocol excludes a racing old writer through publish.
1466
+ * Only that transient source sidecar is touched, never its records or checkouts.
1467
+ */
1468
+ async function importSparoRegistry(options, source, destination, managedRoot) {
1469
+ const files = options.fs;
1470
+ const context = options.signal ? (0, _agimon_ai_po_core_platform.withAbortSignal)(options.signal, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT) : _agimon_ai_po_core_platform.BACKGROUND_CONTEXT;
1471
+ const canonical = async (file) => (0, _agimon_ai_po_core_platform.getOrThrow)(await files.canonicalPath(file, context));
1472
+ const readText = async (file) => (0, _agimon_ai_po_core_platform.getOrThrow)(await files.readTextFile(file, context));
1473
+ const inside = (root, candidate) => {
1474
+ const relative = node_path.default.relative(root, candidate);
1475
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${node_path.default.sep}`) && !node_path.default.isAbsolute(relative);
1476
+ };
1477
+ if (options.sourceProviderStopped !== true) return refuse("stop the source provider before cutover");
1478
+ const result = {
1479
+ source,
1480
+ destination,
1481
+ imported: 0,
1482
+ duplicates: 0
1483
+ };
1484
+ return createWorktreeRegistry(destination).transaction(async () => {
1485
+ const current = await readWorktreeRegistryFile(destination);
1486
+ if (current.sparoImport) {
1487
+ if (current.sparoImport.source !== source) return refuse("completion belongs to a different source");
1488
+ return {
1489
+ ...result,
1490
+ status: "already-imported"
1491
+ };
1492
+ }
1493
+ const sourceInfo = await files.fileInfo(source, context);
1494
+ if (!sourceInfo.ok && sourceInfo.error.code === "not_found") return {
1495
+ ...result,
1496
+ status: "source-absent"
1497
+ };
1498
+ (0, _agimon_ai_po_core_platform.getOrThrow)(sourceInfo);
1499
+ return createWorktreeRegistry(source, { createDirectory: false }).transaction(async () => {
1500
+ const snapshot = await readText(source);
1501
+ const imported = sourceEntries(snapshot);
1502
+ const common = await gitCommonDirectory(options.repositoryRoot);
1503
+ if (!common) return refuse("destination is not a Git repository");
1504
+ const identity = await canonical(common);
1505
+ const canonicalManagedRoot = imported.length ? await canonical(managedRoot) : managedRoot;
1506
+ const membership = new Set(await Promise.all((await options.git.listWorktreePaths(options.repositoryRoot)).map((entry) => canonical(entry))));
1507
+ const combined = [...current.entries];
1508
+ for (const entry of imported) {
1509
+ options.signal?.throwIfAborted();
1510
+ if (!node_path.default.isAbsolute(entry.path) || !node_path.default.isAbsolute(entry.repositoryRoot)) return refuse("non-absolute path");
1511
+ const entryCommon = await gitCommonDirectory(entry.repositoryRoot);
1512
+ const checkoutCommon = await gitCommonDirectory(entry.path);
1513
+ if (!entryCommon || !checkoutCommon || await canonical(entryCommon) !== identity || await canonical(checkoutCommon) !== identity) return refuse(`wrong repository for '${entry.id}'`);
1514
+ const realPath = await canonical(entry.path);
1515
+ if (!inside(managedRoot, node_path.default.resolve(entry.path)) || !inside(canonicalManagedRoot, realPath)) return refuse(`'${entry.id}' is outside the admitted Sparo worktrees root`);
1516
+ if ((0, _agimon_ai_po_core_platform.getOrThrow)(await files.fileInfo(node_path.default.join(realPath, ".git"), context)).kind !== "file") return refuse(`'${entry.id}' is not a linked worktree`);
1517
+ if (!membership.has(realPath)) return refuse(`Git does not list '${entry.id}'`);
1518
+ if (await options.git.currentBranch(entry.path) !== entry.branch) return refuse(`branch mismatch for '${entry.id}'`);
1519
+ if (!entry.sessionId || !Number.isFinite(Date.parse(entry.createdAt))) return refuse(`invalid ownership or timestamp for '${entry.id}'`);
1520
+ const collisions = [];
1521
+ for (const existing of combined) {
1522
+ const resolved = await files.canonicalPath(existing.path, context);
1523
+ const existingPath = !resolved.ok && resolved.error.code === "not_found" ? node_path.default.resolve(existing.path) : (0, _agimon_ai_po_core_platform.getOrThrow)(resolved);
1524
+ if (existing.id === entry.id || existingPath === realPath || existing.sessionId === entry.sessionId || "reservationId" in entry && "reservationId" in existing && entry.reservationId === existing.reservationId) collisions.push(existing);
1525
+ }
1526
+ if (collisions.length) {
1527
+ if (collisions.length !== 1 || !(0, node_util.isDeepStrictEqual)(collisions[0], entry)) return refuse(`conflicting id, path or owner for '${entry.id}'`);
1528
+ result.duplicates++;
1529
+ } else {
1530
+ combined.push(entry);
1531
+ result.imported++;
1532
+ }
1533
+ }
1534
+ if (await readText(source) !== snapshot) return refuse("source changed during import");
1535
+ options.signal?.throwIfAborted();
1536
+ const value = {
1537
+ version: 2,
1538
+ entries: combined,
1539
+ ...current.workflowAttempts ? { workflowAttempts: current.workflowAttempts } : {},
1540
+ sparoImport: {
1541
+ source,
1542
+ sourceDigest: (0, node_crypto.createHash)("sha256").update(snapshot).digest("hex"),
1543
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
1544
+ recordIds: imported.map((entry) => entry.id)
1545
+ }
1546
+ };
1547
+ parseWorktreeRegistry(value);
1548
+ await writeJsonAtomic(destination, value);
1549
+ return {
1550
+ ...result,
1551
+ status: "imported"
1552
+ };
1553
+ }, options.signal);
1554
+ }, options.signal);
1555
+ }
1556
+ //#endregion
430
1557
  //#region src/services/paths/index.ts
431
1558
  /**
432
1559
  * Where this package keeps its own state.
@@ -440,6 +1567,19 @@ function shortId(seed) {
440
1567
  function poGitRoot(homeDir = node_os.default.homedir(), environment = {}) {
441
1568
  return node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDir, environment), "git");
442
1569
  }
1570
+ /**
1571
+ * Deliberate operator cutover, never called by normal registry discovery.
1572
+ * Stop po-sparo first and pass admitted home/environment and Git capabilities.
1573
+ * Label migration completes first; the import then owns the canonical transaction,
1574
+ * even when the canonical registry already existed. No checkout is moved.
1575
+ */
1576
+ async function importSparoWorktrees(options) {
1577
+ if (!node_path.default.isAbsolute(options.homeDirectory) || !node_path.default.isAbsolute(options.repositoryRoot)) throw new Error("Sparo cutover requires explicit absolute home and repository roots.");
1578
+ if (!options.fs) throw new Error("Sparo cutover requires the admitted host filesystem.");
1579
+ if (!options.environment || options.sourceProviderStopped !== true) throw new Error("Sparo cutover requires an admitted environment and a stopped source provider.");
1580
+ const destination = await registryFile(options.repositoryRoot, options.homeDirectory, options.environment);
1581
+ return importSparoRegistry(options, node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(options.homeDirectory, options.environment), "sparo", "registry", await repositoryId(options.repositoryRoot), "worktrees.json"), destination, node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(options.homeDirectory, options.environment), "sparo", "worktrees"));
1582
+ }
443
1583
  /** The directory every worktree for every repository is created under. */
444
1584
  function worktreesRoot(homeDir = node_os.default.homedir(), environment = {}) {
445
1585
  return node_path.default.join(poGitRoot(homeDir, environment), "worktrees");
@@ -472,12 +1612,16 @@ async function registryFile(repositoryRoot, homeDir = node_os.default.homedir(),
472
1612
  }
473
1613
  if (legacyFiles.length === 0) return canonical;
474
1614
  const entries = /* @__PURE__ */ new Map();
1615
+ const workflowAttempts = /* @__PURE__ */ new Map();
475
1616
  for (const file of legacyFiles) {
476
- const legacy = await readJson(file);
477
- if (legacy?.version !== 1 || !Array.isArray(legacy.entries)) continue;
478
- for (const value of legacy.entries) {
479
- if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "string" || value.id === "") continue;
480
- const entry = value;
1617
+ const snapshot = await readWorktreeRegistryFile(file);
1618
+ for (const attempt of snapshot.workflowAttempts ?? []) {
1619
+ const key = JSON.stringify([attempt.launcherSessionId, attempt.attemptId]);
1620
+ const previous = workflowAttempts.get(key);
1621
+ if (previous && !(0, node_util.isDeepStrictEqual)(previous, attempt)) throw new Error("Conflicting legacy workflow attempt metadata.");
1622
+ workflowAttempts.set(key, attempt);
1623
+ }
1624
+ for (const entry of snapshot.entries) {
481
1625
  const existing = entries.get(entry.id);
482
1626
  if (existing !== void 0 && !(0, node_util.isDeepStrictEqual)(existing, entry)) throw new Error(`Conflicting legacy worktree registry entries for '${entry.id}'.`);
483
1627
  entries.set(entry.id, entry);
@@ -485,8 +1629,9 @@ async function registryFile(repositoryRoot, homeDir = node_os.default.homedir(),
485
1629
  }
486
1630
  const temporary = `${canonical}.${(0, node_crypto.randomUUID)()}.migration`;
487
1631
  await writeJsonAtomic(temporary, {
488
- version: 1,
489
- entries: [...entries.values()]
1632
+ version: 2,
1633
+ entries: [...entries.values()],
1634
+ ...workflowAttempts.size ? { workflowAttempts: [...workflowAttempts.values()] } : {}
490
1635
  });
491
1636
  try {
492
1637
  await node_fs_promises.default.link(temporary, canonical);
@@ -597,71 +1742,6 @@ function createWorktreeRift() {
597
1742
  };
598
1743
  }
599
1744
  //#endregion
600
- //#region src/services/worktreeEvents/index.ts
601
- const GIT_WORKTREE_LIFECYCLE_EVENT = "git_worktree_lifecycle";
602
- const GIT_WORKTREE_MESSAGE_EVENT = "git_worktree_message";
603
- /**
604
- * A session's checkout may have changed: a tool call ended, or the agent
605
- * settled. Carries nothing but its version; the '# diff' channel recomputes.
606
- */
607
- const GIT_SESSION_CHANGED_EVENT = "git_session_changed";
608
- const MAX_WORKTREE_MESSAGE_BYTES = 65536;
609
- function isMessageParty(value) {
610
- return value === "parent" || value === "child";
611
- }
612
- function parseMessage(value) {
613
- if (typeof value !== "object" || value === null) return void 0;
614
- const record = value;
615
- if (record.version !== 1) return void 0;
616
- if (typeof record.worktreeId !== "string" || record.worktreeId === "") return void 0;
617
- if (typeof record.fromSessionId !== "string" || record.fromSessionId === "") return void 0;
618
- if (!isMessageParty(record.from)) return void 0;
619
- if (typeof record.text !== "string" || record.text === "") return void 0;
620
- if (Buffer.byteLength(record.text, "utf8") > 65536) return void 0;
621
- if (typeof record.sentAt !== "string" || record.sentAt === "") return void 0;
622
- return record;
623
- }
624
- function createWorktreeMessageInbox(directEvents, sessionId) {
625
- if (sessionId === "") throw new Error("The Git message service requires a session identity.");
626
- const messages = /* @__PURE__ */ new Map();
627
- const unsubscribe = directEvents.subscribe(GIT_WORKTREE_MESSAGE_EVENT, sessionId, (payload) => {
628
- const message = parseMessage(payload);
629
- if (message === void 0) return;
630
- const inbox = messages.get(message.worktreeId) ?? [];
631
- if (inbox.length >= 100) inbox.shift();
632
- inbox.push(message);
633
- messages.set(message.worktreeId, inbox);
634
- });
635
- let closed = false;
636
- return {
637
- send(targetSessionId, message) {
638
- if (closed) throw new Error("The Git message service is closed.");
639
- directEvents.publish(GIT_WORKTREE_MESSAGE_EVENT, targetSessionId, message);
640
- },
641
- receive(worktreeId) {
642
- if (closed) return [];
643
- const inbox = messages.get(worktreeId);
644
- if (inbox === void 0) return [];
645
- messages.delete(worktreeId);
646
- return inbox;
647
- },
648
- close() {
649
- if (closed) return;
650
- closed = true;
651
- unsubscribe();
652
- messages.clear();
653
- }
654
- };
655
- }
656
- function isWorktreeLifecycleEvent(value) {
657
- if (typeof value !== "object" || value === null) return false;
658
- const record = value;
659
- return record.version === 1 && typeof record.repositoryRoot === "string" && record.repositoryRoot !== "";
660
- }
661
- function isSessionChangedEvent(value) {
662
- return typeof value === "object" && value !== null && value.version === 1;
663
- }
664
- //#endregion
665
1745
  //#region src/services/worktreeNaming/index.ts
666
1746
  const MAX_SLUG_LENGTH = 64;
667
1747
  /** Anything git forbids in a ref, plus a leading `-` that `worktree add` would read as an option. */
@@ -771,84 +1851,13 @@ function validRefName(name) {
771
1851
  return true;
772
1852
  }
773
1853
  //#endregion
774
- //#region src/services/worktreeRegistry/index.ts
775
- const LOCK_WAIT_MS = 5e3;
776
- const LOCK_RETRY_MS = 25;
777
- function isRecord(value) {
778
- if (typeof value !== "object" || value === null) return false;
779
- const record = value;
780
- return record.version === 1 && typeof record.id === "string" && record.id !== "" && typeof record.path === "string" && typeof record.branch === "string" && typeof record.sessionId === "string";
781
- }
782
- /**
783
- * Repository mutations hold an exclusive directory lock from the read through
784
- * the final commit. This works across independently loaded packages and hosts.
785
- * A crashed owner leaves a visible lock, never a lease another writer may steal.
786
- */
787
- function createWorktreeRegistry(file) {
788
- return {
789
- async list() {
790
- const parsed = await readJson(file);
791
- if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.entries)) return [];
792
- return parsed.entries.filter(isRecord);
793
- },
794
- async replace(entries) {
795
- await writeJsonAtomic(file, {
796
- version: 1,
797
- entries
798
- });
799
- },
800
- async transaction(operation, signal) {
801
- const lock = `${file}.lock`;
802
- await node_fs_promises.default.mkdir(node_path.default.dirname(file), { recursive: true });
803
- const deadline = Date.now() + LOCK_WAIT_MS;
804
- for (;;) {
805
- signal?.throwIfAborted();
806
- try {
807
- await node_fs_promises.default.mkdir(lock, { mode: 448 });
808
- break;
809
- } catch (error) {
810
- if (error.code !== "EEXIST") throw error;
811
- if (Date.now() >= deadline) throw new PoGitExpectedError("registry_busy", "Another worktree operation holds the repository registry.", true, "Retry after it finishes. After a host crash, inspect and remove the abandoned worktrees.json.lock directory.");
812
- await (0, node_timers_promises.setTimeout)(LOCK_RETRY_MS, void 0, { signal });
813
- }
814
- }
815
- try {
816
- await node_fs_promises.default.writeFile(node_path.default.join(lock, "owner.json"), JSON.stringify({
817
- pid: process.pid,
818
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
819
- }), { mode: 384 });
820
- signal?.throwIfAborted();
821
- return await operation();
822
- } finally {
823
- await node_fs_promises.default.rm(lock, { recursive: true });
824
- }
825
- }
826
- };
827
- }
828
- //#endregion
829
1854
  //#region src/services/worktreeOperations/index.ts
830
1855
  const GIT_WORKTREE_DELEGATION_KIND = "git.worktree.delegation";
831
1856
  const GIT_WORKTREE_MESSAGE_KIND = "git.worktree.message";
832
1857
  const GIT_WORKTREE_REPORT_KIND = "git.worktree.report";
833
- /**
834
- * The repository's worktree setup as one shell command, or undefined when it asks for none.
835
- * Read from the checkout the spawn starts in, so an uncommitted edit applies at once.
836
- */
837
- async function readWorktreeSetup(root) {
838
- const file = node_path.default.join(root, WORKTREE_CONFIG_FILE);
839
- let setup;
840
- try {
841
- setup = (0, js_yaml.load)(await node_fs_promises.default.readFile(file, "utf8"))?.setup;
842
- } catch (error) {
843
- if (error.code === "ENOENT") return void 0;
844
- throw new PoGitExpectedError("invalid_request", `${WORKTREE_CONFIG_FILE} is not valid YAML (${error.message}).`, false, "Fix the file and try again.");
845
- }
846
- const commands = [setup ?? []].flat();
847
- if (!commands.every((command) => typeof command === "string")) throw new PoGitExpectedError("invalid_request", `${WORKTREE_CONFIG_FILE} setup must be a command or a list of commands.`, false, "Fix the file and try again.");
848
- return commands.filter((command) => command.trim() !== "").join(" && ") || void 0;
849
- }
850
1858
  function createWorktreeOperations(deps) {
851
1859
  const { git } = deps;
1860
+ const readConfig = deps.worktreeConfig ?? createWorktreeConfigReader({ readTextFile: (file) => node_fs_promises.default.readFile(file, "utf8") });
852
1861
  const rift = deps.rift ?? createWorktreeRift();
853
1862
  const sessionService = deps.sessionService;
854
1863
  const now = deps.now ?? (() => /* @__PURE__ */ new Date());
@@ -933,7 +1942,58 @@ function createWorktreeOperations(deps) {
933
1942
  const requirePeerLive = (peerSessionId) => {
934
1943
  if (!requireSessionService().isLive(peerSessionId)) throw new PoGitExpectedError("worktree_peer_unavailable", "The other worktree session is no longer live.", false, "Start a new worktree session before sending a message.");
935
1944
  };
1945
+ const operation = (options) => ({
1946
+ environment: deps.environment ?? {},
1947
+ signal: AbortSignal.any([...deps.signal ? [deps.signal] : [], ...options?.signal ? [options.signal] : []])
1948
+ });
1949
+ const engine = () => {
1950
+ const service = deps.gitEngine?.();
1951
+ if (!service) throw new PoGitExpectedError("invalid_request", "Sparse checkout requires po/git-engine.", false, "Enable the Git engine workspace service.");
1952
+ return service;
1953
+ };
1954
+ const fingerprint = async (root, config, ref, options) => {
1955
+ const policy = config.sparse;
1956
+ const request = operation(options);
1957
+ const names = await engine().profiles(root, policy, request, ref);
1958
+ const blobs = await Promise.all(names.filter((name) => name !== "full").map(async (name) => [(0, _agimon_ai_po_sparo.profilePath)(name, policy), await revision(root, `${ref}:${(0, _agimon_ai_po_sparo.profilePath)(name, policy)}`, {
1959
+ env: request.environment,
1960
+ signal: request.signal
1961
+ })]));
1962
+ return (0, node_crypto.createHash)("sha256").update(JSON.stringify([policy, blobs])).digest("hex");
1963
+ };
1964
+ const sparseMutation = async (context, id, folders, options) => {
1965
+ const { store, records } = await resolve(context);
1966
+ const record = require$1(records, id);
1967
+ if (context.sessionId !== record.sessionId) requireOwner(context, record, folders ? "expand" : "reapply");
1968
+ if (!record.sparseProfile) throw new PoGitExpectedError("invalid_request", "This worktree has no sparse profile.", false, "Choose a sparse worktree.");
1969
+ const config = await readConfig(record.repositoryRoot);
1970
+ if (!config.sparse) throw new PoGitExpectedError("invalid_request", "Sparse policy is not configured.", false, "Restore the worktree sparse configuration.");
1971
+ const result = folders ? await engine().expand(record.path, folders, config.sparse, operation(options)) : await engine().reapply(record.path, config.sparse, operation(options));
1972
+ const updated = {
1973
+ ...record,
1974
+ extraFolders: [.../* @__PURE__ */ new Set([...record.extraFolders ?? [], ...folders ?? []])].sort(),
1975
+ sparseFingerprint: await fingerprint(record.path, config, "HEAD", options)
1976
+ };
1977
+ await store.replace(records.map((entry) => entry.id === id ? updated : entry));
1978
+ return {
1979
+ ...updated,
1980
+ coneFolders: result.coneFolders
1981
+ };
1982
+ };
936
1983
  const operations = {
1984
+ async profiles(context, baseRef, options) {
1985
+ if (baseRef !== void 0 && !validRefName(baseRef)) throw new PoGitExpectedError("invalid_request", "The profile base ref is invalid.", false, "Use a valid Git ref.");
1986
+ const { root } = await resolve(context);
1987
+ const config = await readConfig(root);
1988
+ if (!config.sparse) return {};
1989
+ const ref = baseRef ?? await git.remoteBaseRef(root) ?? "HEAD";
1990
+ return {
1991
+ sparseProfiles: await engine().profiles(root, config.sparse, operation(options), ref),
1992
+ ...config.defaults?.sparseProfile ? { defaultSparseProfile: config.defaults.sparseProfile } : {}
1993
+ };
1994
+ },
1995
+ expand: (context, id, folders, options) => sparseMutation(context, id, folders, options),
1996
+ reapply: (context, id, options) => sparseMutation(context, id, void 0, options),
937
1997
  async spawn(context, request, options) {
938
1998
  const parentSessionId = context.sessionId;
939
1999
  const parented = parentSessionId === void 0 ? {} : { parentSessionId };
@@ -970,8 +2030,19 @@ function createWorktreeOperations(deps) {
970
2030
  });
971
2031
  if (refusal !== void 0) throw new PoGitExpectedError("worktree_exists", refusal, false, "Pick another branch name, or close it.");
972
2032
  const taskDelivery = request.task === void 0 ? void 0 : requireSessionDelivery();
973
- const setup = await readWorktreeSetup(root);
974
- const useRift = await rift.enabled(root);
2033
+ const config = await readConfig(root);
2034
+ const setup = options?.workflow ? void 0 : config.setup;
2035
+ const sparseProfile = config.sparse ? config.defaults?.sparseProfile ?? request.sparseProfile : void 0;
2036
+ if (request.sparseProfile !== void 0 && (!config.sparse || config.defaults?.sparseProfile !== void 0 && request.sparseProfile !== config.defaults.sparseProfile)) throw new PoGitExpectedError("invalid_request", "The sparse profile does not match the workspace configuration.", false, "Use the workspace sparse default.");
2037
+ let setupCommand = setup;
2038
+ if (setup !== void 0 && sparseProfile !== void 0) {
2039
+ const cli = deps.sparoCliPath?.();
2040
+ if (!cli || !node_path.default.isAbsolute(cli) || cli.includes("\0")) throw new PoGitExpectedError("invalid_request", "The installed Sparo setup CLI is unavailable.", false, "Repair the plugin installation before creating this checkout.");
2041
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
2042
+ const policy = JSON.stringify(_agimon_ai_po_sparo.SparsePolicy.parse(config.sparse));
2043
+ setupCommand = `${quote(cli)} --policy-json ${quote(policy)} install . && ${setup}`;
2044
+ }
2045
+ const useRift = sparseProfile === void 0 && await rift.enabled(root);
975
2046
  const existingBranch = request.checkout === "existing";
976
2047
  const id = shortId(reserved?.sessionId ?? (0, node_crypto.randomUUID)());
977
2048
  let path = worktreeDirectory({
@@ -1007,9 +2078,35 @@ function createWorktreeOperations(deps) {
1007
2078
  branch: request.branch
1008
2079
  }).catch(() => false) ? "" : ` The branch ${request.branch} has work on it and was kept.`;
1009
2080
  };
2081
+ const workflowBaseCommit = options?.workflow ? await revision(root, baseRef, {
2082
+ env: deps.environment ?? {},
2083
+ signal: operation(options).signal
2084
+ }) : void 0;
1010
2085
  options?.onProgress?.(`creating branch ${request.branch}\u2026`);
2086
+ let coneFolders;
2087
+ let sparseFingerprint;
1011
2088
  if (!recovering) {
1012
- if (useRift) await rift.create({
2089
+ if (sparseProfile !== void 0) {
2090
+ sparseFingerprint = await fingerprint(root, config, baseRef, options);
2091
+ try {
2092
+ coneFolders = (await engine().create({
2093
+ repoRoot: root,
2094
+ path,
2095
+ branch: request.branch,
2096
+ base: baseRef,
2097
+ profile: sparseProfile,
2098
+ extraFolders: config.defaults?.extraFolders ?? [],
2099
+ install: false
2100
+ }, config.sparse, operation(options))).coneFolders;
2101
+ if (existingBranch && request.remote !== void 0) await trackBranch(path, request.branch, baseRef, {
2102
+ env: deps.environment ?? {},
2103
+ signal: operation(options).signal
2104
+ });
2105
+ } catch (error) {
2106
+ await rollback();
2107
+ throw error;
2108
+ }
2109
+ } else if (useRift) await rift.create({
1013
2110
  repositoryRoot: root,
1014
2111
  path,
1015
2112
  branch: request.branch,
@@ -1039,7 +2136,7 @@ function createWorktreeOperations(deps) {
1039
2136
  name: request.name ?? request.branch,
1040
2137
  ...parented,
1041
2138
  sessionProvenance: "worktree",
1042
- ...request.selection === void 0 ? {} : { selection: request.selection },
2139
+ ...options?.preset === void 0 ? request.selection === void 0 ? {} : { selection: request.selection } : { selection: { preset: options.preset } },
1043
2140
  ...options?.signal === void 0 ? {} : { signal: options.signal },
1044
2141
  ...request.reservationId === void 0 ? {} : { reservationId: request.reservationId }
1045
2142
  })).sessionId;
@@ -1051,7 +2148,7 @@ function createWorktreeOperations(deps) {
1051
2148
  throw error;
1052
2149
  }
1053
2150
  const record = {
1054
- version: 1,
2151
+ version: 2,
1055
2152
  id,
1056
2153
  branch: request.branch,
1057
2154
  baseRef,
@@ -1060,8 +2157,21 @@ function createWorktreeOperations(deps) {
1060
2157
  sessionId,
1061
2158
  ...parented,
1062
2159
  status: "running",
2160
+ setupStage: setup === void 0 ? "none" : "unconfirmed",
2161
+ ...sparseProfile === void 0 ? {} : {
2162
+ sparseProfile,
2163
+ extraFolders: config.defaults?.extraFolders ?? [],
2164
+ sparseFingerprint
2165
+ },
1063
2166
  ...useRift ? { backend: "rift" } : {},
1064
- createdAt: now().toISOString()
2167
+ createdAt: now().toISOString(),
2168
+ ...options?.workflow ? {
2169
+ baseCommit: workflowBaseCommit,
2170
+ workflow: {
2171
+ ...options.workflow,
2172
+ state: "spawned"
2173
+ }
2174
+ } : {}
1065
2175
  };
1066
2176
  try {
1067
2177
  await store.replace([...records, record]);
@@ -1070,20 +2180,22 @@ function createWorktreeOperations(deps) {
1070
2180
  const kept = await rollback();
1071
2181
  throw new PoGitExpectedError("registry_write_failed", `The worktree was created but the registry could not be written (${error.message}).${kept}`, true, "Check the registry file for permissions or free space, then try again.");
1072
2182
  }
1073
- let setupStarted = false;
1074
- if (setup !== void 0) try {
1075
- const service = requireSessionService();
1076
- if (service.prompt === void 0) throw new Error("this host cannot run session commands");
1077
- await service.prompt(sessionId, `${WORKTREE_SETUP_LAUNCH} ${setup}`);
1078
- setupStarted = true;
1079
- } catch (error) {
1080
- options?.onProgress?.(`worktree setup did not start (${String(error)})`);
2183
+ if (setupCommand !== void 0) {
2184
+ try {
2185
+ const stage = await deps.startSetup?.(sessionId, setupCommand, operation(options).signal);
2186
+ record.setupStage = stage === "started" || stage === "failed" ? stage : "unconfirmed";
2187
+ } catch {
2188
+ record.setupStage = operation(options).signal.aborted ? "unconfirmed" : "failed";
2189
+ }
2190
+ await store.replace([...records, record]);
2191
+ if (record.setupStage !== "started") options?.onProgress?.(`worktree setup ${record.setupStage}; inspect worktree-setup before deciding whether to retry. Do not retry automatically.`);
1081
2192
  }
2193
+ const setupStarted = record.setupStage === "started";
1082
2194
  if (request.task !== void 0 && taskDelivery !== void 0) try {
1083
2195
  const receipt = await taskDelivery.deliver({
1084
2196
  recipientKey: sessionId,
1085
2197
  kind: GIT_WORKTREE_DELEGATION_KIND,
1086
- prompt: setupStarted ? `${request.task}\n\nThe worktree setup (${setup}) is running as the runner "worktree-setup". Check it with po-runner before relying on installed dependencies or builds.` : request.task,
2198
+ prompt: setupStarted ? `${request.task}\n\nThe worktree setup (${setup}) is running as the runner "worktree-setup". Check it with po-runner before relying on installed dependencies or builds.` : setup === void 0 ? request.task : `${request.task}\n\nThe worktree setup handoff is ${record.setupStage}. Inspect the runner "worktree-setup" before relying on dependencies or deciding whether to retry. Do not retry automatically.`,
1087
2199
  metadata: {
1088
2200
  worktreeId: record.id,
1089
2201
  fromRole: "parent",
@@ -1098,12 +2210,36 @@ function createWorktreeOperations(deps) {
1098
2210
  throw new PoGitExpectedError("task_delivery_failed", `Worktree ${record.id} was created, but task delivery failed (${String(error)}).`, true, `Inspect worktree ${record.id} and the sender outbox before using send to deliver the task. Do not recreate the worktree.`);
1099
2211
  }
1100
2212
  if (request.reservationId !== void 0) await reservations.complete(request.reservationId, parentSessionId);
1101
- return record;
2213
+ return coneFolders === void 0 ? record : {
2214
+ ...record,
2215
+ coneFolders
2216
+ };
2217
+ },
2218
+ async linkWorkflow(context, id, workflow) {
2219
+ const { store, records } = await resolve(context);
2220
+ const record = require$1(records, id);
2221
+ if (record.parentSessionId !== context.sessionId || record.workflow?.attemptId !== workflow.attemptId || record.workflow.fingerprint !== workflow.fingerprint) throw new PoGitExpectedError("invalid_request", "The workflow does not own this checkout.", false, "Inspect the recorded workflow owner.");
2222
+ if (record.workflow.admissionId && record.workflow.admissionId !== workflow.admissionId || record.workflow.runId && record.workflow.runId !== workflow.runId || record.workflow.state === "retained" && workflow.state !== "retained") throw new PoGitExpectedError("invalid_request", "The workflow admission or terminal identity changed.", false, "Keep and inspect the recorded workflow.");
2223
+ const updated = {
2224
+ ...record,
2225
+ workflow
2226
+ };
2227
+ await store.replace(records.map((entry) => entry.id === id ? updated : entry));
2228
+ return updated;
1102
2229
  },
1103
- async close(context, id, force) {
2230
+ async close(context, id, force, expectedWorkflow) {
1104
2231
  const { root, store, records } = await resolve(context);
1105
2232
  const record = require$1(records, id);
1106
2233
  requireOwner(context, record, "close");
2234
+ if (expectedWorkflow && (record.status !== "running" || record.workflow?.state !== "admitted" || record.sessionId !== expectedWorkflow.sessionId || record.path !== expectedWorkflow.path || await revision(record.path, "HEAD", {
2235
+ env: deps.environment ?? {},
2236
+ signal: operation().signal
2237
+ }) !== expectedWorkflow.head || record.parentSessionId !== context.sessionId || [
2238
+ "attemptId",
2239
+ "fingerprint",
2240
+ "admissionId",
2241
+ "runId"
2242
+ ].some((key) => record.workflow?.[key] !== expectedWorkflow[key]))) throw new PoGitExpectedError("invalid_request", "The workflow checkout evidence changed.", false, "Keep and inspect this checkout.");
1107
2243
  const refusal = refuseClose({
1108
2244
  record,
1109
2245
  dirtyFiles: await probe.exists(record.path) ? await git.dirtyFiles(record.path) : [],
@@ -1234,6 +2370,7 @@ function createWorktreeOperations(deps) {
1234
2370
  return await store.transaction(operation, signal);
1235
2371
  } catch (error) {
1236
2372
  if (signal?.aborted && !(error instanceof PoGitExpectedError)) throw new PoGitExpectedError("spawn_cancelled", "The worktree operation was cancelled.", false, "Inspect its recorded state before retrying.");
2373
+ if (error instanceof _agimon_ai_po_sparo.SparoError && error.code !== "COMMAND_FAILED") throw new PoGitExpectedError("invalid_request", error.message, false, "Run sparo init explicitly before sparse checkout, or fix the configured profile.");
1237
2374
  if ([
1238
2375
  "ENOTDIR",
1239
2376
  "EACCES",
@@ -1247,17 +2384,76 @@ function createWorktreeOperations(deps) {
1247
2384
  ...operations,
1248
2385
  spawn: (context, request, options) => {
1249
2386
  if (sessionService === void 0) return Promise.reject(new PoGitExpectedError("hub_unavailable", "The cockpit session service is unavailable.", true, "Use the cockpit worktree tool after its Git server plugin is available."));
1250
- if (!validRefName(request.branch) || request.baseRef !== void 0 && !validRefName(request.baseRef)) return Promise.reject(new PoGitExpectedError("invalid_request", "That is not a valid branch name.", false, "Pick another name."));
2387
+ if (request.sparseProfile !== void 0 && !validSparseProfile(request.sparseProfile) || !validRefName(request.branch) || request.baseRef !== void 0 && !validRefName(request.baseRef)) return Promise.reject(new PoGitExpectedError("invalid_request", "That is not a valid branch name.", false, "Pick another name."));
1251
2388
  if (request.reservationId !== void 0 && context.sessionId === void 0) return Promise.reject(new PoGitExpectedError("invalid_request", "A reserved worktree session requires its owning parent.", false, "Create the session from its pending setup card."));
1252
2389
  return locked(context, () => operations.spawn(context, request, options), options?.signal);
1253
2390
  },
1254
- close: (context, id, force) => locked(context, () => operations.close(context, id, force)),
2391
+ expand: (context, id, folders, options) => {
2392
+ if (!Array.isArray(folders) || folders.length === 0 || !folders.every((folder) => _agimon_ai_po_sparo.ConeFolder.safeParse(folder).success)) return Promise.reject(new PoGitExpectedError("invalid_request", "Pass nonempty relative cone folders.", false, "Use repository-relative folders."));
2393
+ return locked(context, () => operations.expand(context, id, folders, options), options?.signal);
2394
+ },
2395
+ reapply: (context, id, options) => locked(context, () => operations.reapply(context, id, options), options?.signal),
2396
+ linkWorkflow: (context, id, workflow) => locked(context, () => operations.linkWorkflow(context, id, workflow)),
2397
+ close: (context, id, force, expectedWorkflow) => locked(context, () => operations.close(context, id, force, expectedWorkflow)),
1255
2398
  list: (context) => locked(context, () => operations.list(context)),
1256
2399
  merge: (context, id, message) => locked(context, () => operations.merge(context, id, message)),
1257
2400
  prune: (context, dryRun) => locked(context, () => operations.prune(context, dryRun))
1258
2401
  };
1259
2402
  }
1260
2403
  //#endregion
2404
+ //#region src/services/gitDependencies/index.ts
2405
+ function createGitDependencies(overrides = {}) {
2406
+ return {
2407
+ service: overrides.service ?? new DefaultGitExtensionService(),
2408
+ operations: overrides.operations ?? createWorktreeOperations({ git: createWorktreeGit() })
2409
+ };
2410
+ }
2411
+ /** One admitted environment and config snapshot per session or API composition. */
2412
+ function createGitOperationDependencies({ context, host, signal }, scope = host.context) {
2413
+ let files;
2414
+ let gitEngine;
2415
+ context.inject([_agimon_ai_po_core_platform.PO_FS_SERVICE], (child) => {
2416
+ files = (0, _agimon_ai_po_core_platform.requirePoFs)(child);
2417
+ return () => {
2418
+ files = void 0;
2419
+ };
2420
+ });
2421
+ context.inject([_agimon_ai_po_sparo.PO_GIT_ENGINE_SERVICE], (child) => {
2422
+ gitEngine = child.get(_agimon_ai_po_sparo.PO_GIT_ENGINE_SERVICE);
2423
+ return () => {
2424
+ gitEngine = void 0;
2425
+ };
2426
+ });
2427
+ return {
2428
+ gitEngine: () => gitEngine,
2429
+ sparoCliPath: () => (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href).resolve("@agimon-ai/po-sparo/bin/cli"),
2430
+ startSetup: (sessionId, command, setupSignal) => host.context.directEvents ? startWorktreeSetup(host.context.directEvents, sessionId, command, setupSignal) : Promise.resolve("unconfirmed"),
2431
+ environment: scope.environment ?? {},
2432
+ homeDir: host.context.homeDirectory,
2433
+ signal,
2434
+ worktreeConfig: createWorktreeConfigReader({
2435
+ async readTextFile(file) {
2436
+ if (!files) throw new Error("The Git host filesystem is unavailable.");
2437
+ const result = await files.readTextFile(file, (0, _agimon_ai_po_core_platform.withAbortSignal)(signal, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
2438
+ if (!result.ok) throw result.error;
2439
+ return result.value;
2440
+ },
2441
+ async readMetadata() {
2442
+ const registry = (0, _agimon_ai_po_core_workspaceRegistry.readPoWorkspaceRegistry)(context);
2443
+ if (!scope.workspaceId || !registry) return void 0;
2444
+ const result = await registry.resolve({ id: scope.workspaceId });
2445
+ return result.status === "found" ? result.workspace.metadata : void 0;
2446
+ }
2447
+ })
2448
+ };
2449
+ }
2450
+ //#endregion
2451
+ Object.defineProperty(exports, "DefaultGitExtensionService", {
2452
+ enumerable: true,
2453
+ get: function() {
2454
+ return DefaultGitExtensionService;
2455
+ }
2456
+ });
1261
2457
  Object.defineProperty(exports, "GIT_AUTH_PATH", {
1262
2458
  enumerable: true,
1263
2459
  get: function() {
@@ -1270,6 +2466,12 @@ Object.defineProperty(exports, "GIT_BRANCHES_PATH", {
1270
2466
  return GIT_BRANCHES_PATH;
1271
2467
  }
1272
2468
  });
2469
+ Object.defineProperty(exports, "GIT_ENGINE_CONTRACT", {
2470
+ enumerable: true,
2471
+ get: function() {
2472
+ return GIT_ENGINE_CONTRACT;
2473
+ }
2474
+ });
1273
2475
  Object.defineProperty(exports, "GIT_REVIEW_FILE_PATH", {
1274
2476
  enumerable: true,
1275
2477
  get: function() {
@@ -1294,6 +2496,12 @@ Object.defineProperty(exports, "GIT_SESSION_CHANGED_EVENT", {
1294
2496
  return GIT_SESSION_CHANGED_EVENT;
1295
2497
  }
1296
2498
  });
2499
+ Object.defineProperty(exports, "GIT_WORKFLOWS_CONTRACT", {
2500
+ enumerable: true,
2501
+ get: function() {
2502
+ return GIT_WORKFLOWS_CONTRACT;
2503
+ }
2504
+ });
1297
2505
  Object.defineProperty(exports, "GIT_WORKTREE_LIFECYCLE_EVENT", {
1298
2506
  enumerable: true,
1299
2507
  get: function() {
@@ -1312,6 +2520,12 @@ Object.defineProperty(exports, "NETWORK_TIMEOUT_MS", {
1312
2520
  return NETWORK_TIMEOUT_MS;
1313
2521
  }
1314
2522
  });
2523
+ Object.defineProperty(exports, "PO_GIT_WORKFLOWS_SERVICE", {
2524
+ enumerable: true,
2525
+ get: function() {
2526
+ return PO_GIT_WORKFLOWS_SERVICE;
2527
+ }
2528
+ });
1315
2529
  Object.defineProperty(exports, "PoGitExpectedError", {
1316
2530
  enumerable: true,
1317
2531
  get: function() {
@@ -1330,12 +2544,30 @@ Object.defineProperty(exports, "REBASE_TIMEOUT_MS", {
1330
2544
  return REBASE_TIMEOUT_MS;
1331
2545
  }
1332
2546
  });
2547
+ Object.defineProperty(exports, "StartWorktreeWorkflowSchema", {
2548
+ enumerable: true,
2549
+ get: function() {
2550
+ return StartWorktreeWorkflowSchema;
2551
+ }
2552
+ });
1333
2553
  Object.defineProperty(exports, "__toESM", {
1334
2554
  enumerable: true,
1335
2555
  get: function() {
1336
2556
  return __toESM;
1337
2557
  }
1338
2558
  });
2559
+ Object.defineProperty(exports, "createGitDependencies", {
2560
+ enumerable: true,
2561
+ get: function() {
2562
+ return createGitDependencies;
2563
+ }
2564
+ });
2565
+ Object.defineProperty(exports, "createGitOperationDependencies", {
2566
+ enumerable: true,
2567
+ get: function() {
2568
+ return createGitOperationDependencies;
2569
+ }
2570
+ });
1339
2571
  Object.defineProperty(exports, "createWorktreeGit", {
1340
2572
  enumerable: true,
1341
2573
  get: function() {
@@ -1366,6 +2598,12 @@ Object.defineProperty(exports, "credentialsFile", {
1366
2598
  return credentialsFile;
1367
2599
  }
1368
2600
  });
2601
+ Object.defineProperty(exports, "importSparoWorktrees", {
2602
+ enumerable: true,
2603
+ get: function() {
2604
+ return importSparoWorktrees;
2605
+ }
2606
+ });
1369
2607
  Object.defineProperty(exports, "invalidRequest", {
1370
2608
  enumerable: true,
1371
2609
  get: function() {
@@ -1396,12 +2634,30 @@ Object.defineProperty(exports, "readJson", {
1396
2634
  return readJson;
1397
2635
  }
1398
2636
  });
2637
+ Object.defineProperty(exports, "receiveWorktreeSetup", {
2638
+ enumerable: true,
2639
+ get: function() {
2640
+ return receiveWorktreeSetup;
2641
+ }
2642
+ });
1399
2643
  Object.defineProperty(exports, "registryFile", {
1400
2644
  enumerable: true,
1401
2645
  get: function() {
1402
2646
  return registryFile;
1403
2647
  }
1404
2648
  });
2649
+ Object.defineProperty(exports, "remoteBranchHead", {
2650
+ enumerable: true,
2651
+ get: function() {
2652
+ return remoteBranchHead;
2653
+ }
2654
+ });
2655
+ Object.defineProperty(exports, "revision", {
2656
+ enumerable: true,
2657
+ get: function() {
2658
+ return revision;
2659
+ }
2660
+ });
1405
2661
  Object.defineProperty(exports, "runGit", {
1406
2662
  enumerable: true,
1407
2663
  get: function() {
@@ -1414,6 +2670,12 @@ Object.defineProperty(exports, "validRefName", {
1414
2670
  return validRefName;
1415
2671
  }
1416
2672
  });
2673
+ Object.defineProperty(exports, "validSparseProfile", {
2674
+ enumerable: true,
2675
+ get: function() {
2676
+ return validSparseProfile;
2677
+ }
2678
+ });
1417
2679
  Object.defineProperty(exports, "writeJsonAtomic", {
1418
2680
  enumerable: true,
1419
2681
  get: function() {
@@ -1421,4 +2683,4 @@ Object.defineProperty(exports, "writeJsonAtomic", {
1421
2683
  }
1422
2684
  });
1423
2685
 
1424
- //# sourceMappingURL=worktreeOperations-BEk4VEj3.cjs.map
2686
+ //# sourceMappingURL=gitDependencies-BnNuImZi.cjs.map