@agimon-ai/doompi-git 0.0.1-alpha.36 → 0.0.1-alpha.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +21 -1
  2. package/dist/apiContracts.cjs +249 -60
  3. package/dist/apiContracts.cjs.map +1 -1
  4. package/dist/apiContracts.d.mts.map +1 -1
  5. package/dist/apiContracts.mjs +249 -60
  6. package/dist/apiContracts.mjs.map +1 -1
  7. package/dist/extensions/pi.cjs +2 -2
  8. package/dist/extensions/pi.mjs +2 -2
  9. package/dist/extensions/server.cjs +1279 -39
  10. package/dist/extensions/server.cjs.map +1 -1
  11. package/dist/extensions/server.d.mts.map +1 -1
  12. package/dist/extensions/server.mjs +1277 -40
  13. package/dist/extensions/server.mjs.map +1 -1
  14. package/dist/extensions/web.mjs +1625 -23
  15. package/dist/extensions/web.mjs.map +1 -1
  16. package/dist/{gitDependencies-CZLZ_YwU.mjs → gitDependencies-CtVubYvU.mjs} +2 -2
  17. package/dist/{gitDependencies-CZLZ_YwU.mjs.map → gitDependencies-CtVubYvU.mjs.map} +1 -1
  18. package/dist/{gitDependencies-Bv_1StiU.cjs → gitDependencies-Dqsz2HjK.cjs} +2 -2
  19. package/dist/{gitDependencies-Bv_1StiU.cjs.map → gitDependencies-Dqsz2HjK.cjs.map} +1 -1
  20. package/dist/index-D79MSCee.d.mts.map +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.mjs +1 -1
  23. package/dist/{runWorktree-CtdyNIpZ.cjs → runWorktree-BE795LxL.cjs} +25 -2
  24. package/dist/runWorktree-BE795LxL.cjs.map +1 -0
  25. package/dist/{runWorktree-x0pLorlB.mjs → runWorktree-SPzJvIBt.mjs} +8 -3
  26. package/dist/runWorktree-SPzJvIBt.mjs.map +1 -0
  27. package/dist/{worktreeOperations-CEbq7iUE.cjs → worktreeOperations-BYmVU0UV.cjs} +106 -9
  28. package/dist/worktreeOperations-BYmVU0UV.cjs.map +1 -0
  29. package/dist/{worktreeOperations-BgE26zO3.mjs → worktreeOperations-BrWG2muV.mjs} +41 -10
  30. package/dist/worktreeOperations-BrWG2muV.mjs.map +1 -0
  31. package/package.json +8 -6
  32. package/dist/runWorktree-CtdyNIpZ.cjs.map +0 -1
  33. package/dist/runWorktree-x0pLorlB.mjs.map +0 -1
  34. package/dist/worktreeOperations-BgE26zO3.mjs.map +0 -1
  35. package/dist/worktreeOperations-CEbq7iUE.cjs.map +0 -1
@@ -2,8 +2,14 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_worktreeOperations = require("../worktreeOperations-CEbq7iUE.cjs");
6
- const require_runWorktree = require("../runWorktree-CtdyNIpZ.cjs");
5
+ const require_worktreeOperations = require("../worktreeOperations-BYmVU0UV.cjs");
6
+ const require_runWorktree = require("../runWorktree-BE795LxL.cjs");
7
+ let node_fs = require("node:fs");
8
+ node_fs = require_worktreeOperations.__toESM(node_fs, 1);
9
+ let node_path = require("node:path");
10
+ node_path = require_worktreeOperations.__toESM(node_path, 1);
11
+ let node_os = require("node:os");
12
+ node_os = require_worktreeOperations.__toESM(node_os, 1);
7
13
  let _agimon_ai_doompi_core_extensionFile = require("@agimon-ai/doompi-core/extensionFile");
8
14
  let _agimon_ai_doompi_core_serverFacet = require("@agimon-ai/doompi-core/serverFacet");
9
15
  let _agimon_ai_doompi_session = require("@agimon-ai/doompi-session");
@@ -29,39 +35,51 @@ function createGitSession({ context, host: serverHost }) {
29
35
  messageInbox,
30
36
  sessionDelivery: () => (0, _agimon_ai_doompi_session.readDoomSessionDelivery)(context)
31
37
  });
38
+ const resources = [{
39
+ when: {
40
+ state: { "minor-mode": "help" },
41
+ attribution: {
42
+ kind: "minor",
43
+ mode: "help"
44
+ }
45
+ },
46
+ name: "doompi-git",
47
+ kind: "context",
48
+ read: () => (0, _agimon_ai_doompi_core_serverFacet.readPackageResource)(require("url").pathToFileURL(__filename).href, "llms.txt")
49
+ }, {
50
+ name: "doompi-use-git",
51
+ kind: "skill",
52
+ read: () => (0, _agimon_ai_doompi_core_serverFacet.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/doompi-use-git/SKILL.md")
53
+ }];
54
+ const tool = {
55
+ name: require_runWorktree.RUN_WORKTREE_TOOL_NAME,
56
+ label: "Worktree",
57
+ description: require_runWorktree.RUN_WORKTREE_DESCRIPTION,
58
+ parameters: require_runWorktree.RunWorktreeToolSchema,
59
+ promptSnippet: "Create and manage Git worktree sessions",
60
+ executionMode: "serial",
61
+ async execute(_toolCallId, parameters, signal, onUpdate, execution) {
62
+ const params = require_runWorktree.validateParams(parameters);
63
+ return require_runWorktree.executeRunWorktreeTool(params, operations, execution, {
64
+ ...signal === void 0 ? {} : { signal },
65
+ onProgress: (label) => onUpdate?.(progressResult(params.action, label))
66
+ });
67
+ }
68
+ };
69
+ const changed = (_event, execution) => {
70
+ directEvents.publish(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, execution.sessionId, { version: 1 });
71
+ };
32
72
  return {
33
73
  value: {
34
- resources: [{
35
- when: {
36
- state: { "minor-mode": "help" },
37
- attribution: {
38
- kind: "minor",
39
- mode: "help"
40
- }
41
- },
42
- name: "doompi-git",
43
- kind: "context",
44
- read: () => (0, _agimon_ai_doompi_core_serverFacet.readPackageResource)(require("url").pathToFileURL(__filename).href, "llms.txt")
74
+ resources,
75
+ tool,
76
+ hooks: [{
77
+ event: "tool_execution_end",
78
+ handle: changed
45
79
  }, {
46
- name: "doompi-use-git",
47
- kind: "skill",
48
- read: () => (0, _agimon_ai_doompi_core_serverFacet.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/doompi-use-git/SKILL.md")
49
- }],
50
- tool: {
51
- name: require_runWorktree.RUN_WORKTREE_TOOL_NAME,
52
- label: "Worktree",
53
- description: require_runWorktree.RUN_WORKTREE_DESCRIPTION,
54
- parameters: require_runWorktree.RunWorktreeToolSchema,
55
- promptSnippet: "Create and manage Git worktree sessions",
56
- executionMode: "serial",
57
- async execute(_toolCallId, parameters, signal, onUpdate, execution) {
58
- const params = require_runWorktree.validateParams(parameters);
59
- return require_runWorktree.executeRunWorktreeTool(params, operations, execution, {
60
- ...signal === void 0 ? {} : { signal },
61
- onProgress: (label) => onUpdate?.(progressResult(params.action, label))
62
- });
63
- }
64
- }
80
+ event: "agent_settled",
81
+ handle: changed
82
+ }]
65
83
  },
66
84
  onDispose: () => messageInbox.close()
67
85
  };
@@ -71,6 +89,678 @@ const root = (0, _agimon_ai_doompi_core_extensionFile.defineRoot)(createGitSessi
71
89
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
72
90
  var root_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineRoot)(root);
73
91
  //#endregion
92
+ //#region src/services/branchDiff/index.ts
93
+ /**
94
+ * What a session's checkout changed against its base, the way a pull request
95
+ * shows it: every commit since the branch left its base, plus staged, unstaged
96
+ * and untracked work.
97
+ *
98
+ * DESIGN PATTERNS:
99
+ * - git computes every diff. The counts come from `--numstat` and the hunks
100
+ * from the same unified diff, so the two always agree.
101
+ * - The base is the worktree's own recorded base when there is one, then the
102
+ * remote's default branch, then the branch's upstream, and with none of those
103
+ * only uncommitted work counts. It is always named in the UI.
104
+ * - Untracked files are read only when they are small regular files; a symlink
105
+ * shows its link text and is never followed.
106
+ *
107
+ * AVOID:
108
+ * - Passing a browser path to git without checking it against the change set.
109
+ */
110
+ /** git's well-known empty tree, the base of a repository with no commits. */
111
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
112
+ const MAX_LISTED_FILES = 500;
113
+ const MAX_UNTRACKED_COUNTED = 200;
114
+ const MAX_FILE_BYTES = 1048576;
115
+ const MAX_ROWS = 5e3;
116
+ const BINARY_PROBE_BYTES = 8192;
117
+ const SHORT_SHA = 7;
118
+ const DEFAULT_BRANCHES = ["main", "master"];
119
+ async function read(cwd, args) {
120
+ const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
121
+ return result.code === 0 ? result.stdout : void 0;
122
+ }
123
+ async function readLine$1(cwd, args) {
124
+ const out = (await read(cwd, args))?.trim();
125
+ return out === void 0 || out === "" ? void 0 : out;
126
+ }
127
+ async function commitExists(cwd, ref) {
128
+ return await readLine$1(cwd, [
129
+ "rev-parse",
130
+ "--verify",
131
+ "--quiet",
132
+ `${ref}^{commit}`
133
+ ]) !== void 0;
134
+ }
135
+ /** A local branch's upstream, so the review measures against what fetch keeps current. */
136
+ async function upstreamOf(cwd, ref) {
137
+ return readLine$1(cwd, [
138
+ "rev-parse",
139
+ "--abbrev-ref",
140
+ "--symbolic-full-name",
141
+ `${ref}@{upstream}`
142
+ ]);
143
+ }
144
+ /** The ref the review is measured against. Exported for sync, whose rebase uses the same base. */
145
+ async function resolveBaseRef(cwd, branch, recordedBaseRef) {
146
+ if (!(recordedBaseRef === void 0 || branch !== void 0 && (recordedBaseRef === branch || recordedBaseRef.endsWith(`/${branch}`))) && recordedBaseRef !== void 0 && await commitExists(cwd, recordedBaseRef)) return (await readLine$1(cwd, [
147
+ "rev-parse",
148
+ "--verify",
149
+ "--quiet",
150
+ `refs/heads/${recordedBaseRef}`
151
+ ]) !== void 0 ? await upstreamOf(cwd, recordedBaseRef) : void 0) ?? recordedBaseRef;
152
+ const originHead = await readLine$1(cwd, [
153
+ "symbolic-ref",
154
+ "--quiet",
155
+ "--short",
156
+ "refs/remotes/origin/HEAD"
157
+ ]);
158
+ if (originHead !== void 0) return originHead;
159
+ for (const name of DEFAULT_BRANCHES) if (await commitExists(cwd, `origin/${name}`)) return `origin/${name}`;
160
+ return branch === void 0 ? void 0 : upstreamOf(cwd, branch);
161
+ }
162
+ async function resolveBase(cwd, branch, recordedBaseRef) {
163
+ const ref = await resolveBaseRef(cwd, branch, recordedBaseRef);
164
+ const head = await commitExists(cwd, "HEAD");
165
+ if (ref !== void 0 && head) {
166
+ const mergeBase = await readLine$1(cwd, [
167
+ "merge-base",
168
+ ref,
169
+ "HEAD"
170
+ ]);
171
+ if (mergeBase !== void 0) return {
172
+ ref,
173
+ from: mergeBase,
174
+ mergeBase: mergeBase.slice(0, SHORT_SHA)
175
+ };
176
+ }
177
+ return { from: head ? "HEAD" : EMPTY_TREE };
178
+ }
179
+ /** NUL-separated fields from a `-z` listing, without the trailing empty one. */
180
+ function zFields(out) {
181
+ if (out === void 0 || out === "") return [];
182
+ const fields = out.split("\0");
183
+ if (fields.at(-1) === "") fields.pop();
184
+ return fields;
185
+ }
186
+ const NAME_STATUS = {
187
+ A: "added",
188
+ D: "deleted",
189
+ M: "modified",
190
+ T: "modified"
191
+ };
192
+ /** Line count of a small regular file, or undefined when it is binary, large, or not a regular file. */
193
+ function untrackedLines(root, relPath) {
194
+ const absolute = node_path.default.join(root, relPath);
195
+ let stat;
196
+ try {
197
+ stat = node_fs.default.lstatSync(absolute);
198
+ } catch {
199
+ return;
200
+ }
201
+ if (stat.isSymbolicLink()) return {
202
+ lines: 1,
203
+ binary: false
204
+ };
205
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return void 0;
206
+ const content = node_fs.default.readFileSync(absolute);
207
+ if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
208
+ lines: 0,
209
+ binary: true
210
+ };
211
+ if (content.length === 0) return {
212
+ lines: 0,
213
+ binary: false
214
+ };
215
+ const text = content.toString("utf8");
216
+ const newlines = text.split("\n").length - 1;
217
+ return {
218
+ lines: text.endsWith("\n") ? newlines : newlines + 1,
219
+ binary: false
220
+ };
221
+ }
222
+ /** The hunks of a unified diff, numbering each row by the file it lives in. */
223
+ function parseUnifiedDiff(diff) {
224
+ const hunks = [];
225
+ let current;
226
+ let oldLine = 0;
227
+ let newLine = 0;
228
+ let rows = 0;
229
+ let binary = false;
230
+ for (const line of diff.split("\n")) {
231
+ const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(line);
232
+ if (header !== null) {
233
+ oldLine = Number(header[1]);
234
+ newLine = Number(header[2]);
235
+ current = {
236
+ start: newLine,
237
+ rows: []
238
+ };
239
+ hunks.push(current);
240
+ continue;
241
+ }
242
+ if (current === void 0) {
243
+ if (line.startsWith("Binary files ") || line === "GIT binary patch") binary = true;
244
+ continue;
245
+ }
246
+ const marker = line[0];
247
+ let row;
248
+ if (marker === " ") row = {
249
+ marker: " ",
250
+ line: newLine,
251
+ content: line.slice(1)
252
+ };
253
+ else if (marker === "-") row = {
254
+ marker: "-",
255
+ line: oldLine,
256
+ content: line.slice(1)
257
+ };
258
+ else if (marker === "+") row = {
259
+ marker: "+",
260
+ line: newLine,
261
+ content: line.slice(1)
262
+ };
263
+ if (row === void 0) continue;
264
+ if (marker !== "+") oldLine += 1;
265
+ if (marker !== "-") newLine += 1;
266
+ current.rows.push(row);
267
+ rows += 1;
268
+ }
269
+ return {
270
+ hunks,
271
+ binary,
272
+ rows
273
+ };
274
+ }
275
+ function createBranchDiff() {
276
+ return {
277
+ async review(cwd, options = {}) {
278
+ const root = await readLine$1(cwd, ["rev-parse", "--show-toplevel"]);
279
+ if (root === void 0) return void 0;
280
+ const branch = await readLine$1(root, [
281
+ "symbolic-ref",
282
+ "--quiet",
283
+ "--short",
284
+ "HEAD"
285
+ ]);
286
+ const base = await resolveBase(root, branch, options.recordedBaseRef);
287
+ const numstat = zFields(await read(root, [
288
+ "diff",
289
+ "--numstat",
290
+ "-z",
291
+ "--no-renames",
292
+ base.from
293
+ ]));
294
+ const nameStatus = zFields(await read(root, [
295
+ "diff",
296
+ "--name-status",
297
+ "-z",
298
+ "--no-renames",
299
+ base.from
300
+ ]));
301
+ const unmerged = new Set(zFields(await read(root, [
302
+ "diff",
303
+ "--name-only",
304
+ "--diff-filter=U",
305
+ "-z"
306
+ ])));
307
+ const statusOf = /* @__PURE__ */ new Map();
308
+ for (let index = 0; index + 1 < nameStatus.length; index += 2) statusOf.set(nameStatus[index + 1] ?? "", NAME_STATUS[(nameStatus[index] ?? "").charAt(0)] ?? "modified");
309
+ const entries = [];
310
+ for (const field of numstat) {
311
+ const [added = "", removed = "", ...rest] = field.split(" ");
312
+ const filePath = rest.join(" ");
313
+ if (filePath === "") continue;
314
+ const binary = added === "-" && removed === "-";
315
+ entries.push({
316
+ path: filePath,
317
+ status: unmerged.has(filePath) ? "conflicted" : statusOf.get(filePath) ?? "modified",
318
+ added: binary ? 0 : Number(added),
319
+ removed: binary ? 0 : Number(removed),
320
+ ...binary ? { binary: true } : {}
321
+ });
322
+ }
323
+ const untracked = zFields(await read(root, [
324
+ "ls-files",
325
+ "--others",
326
+ "--exclude-standard",
327
+ "-z"
328
+ ]));
329
+ untracked.forEach((relPath, index) => {
330
+ const counted = index < MAX_UNTRACKED_COUNTED ? untrackedLines(root, relPath) : void 0;
331
+ entries.push({
332
+ path: relPath,
333
+ status: "untracked",
334
+ added: counted?.lines ?? 0,
335
+ removed: 0,
336
+ ...counted?.binary ? { binary: true } : {}
337
+ });
338
+ });
339
+ entries.sort((left, right) => left.path.localeCompare(right.path));
340
+ const conflicts = [...unmerged];
341
+ const rebasing = [await readLine$1(root, [
342
+ "rev-parse",
343
+ "--git-path",
344
+ "rebase-merge"
345
+ ]), await readLine$1(root, [
346
+ "rev-parse",
347
+ "--git-path",
348
+ "rebase-apply"
349
+ ])].some((gitPath) => gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath)));
350
+ const upstreamRef = branch === void 0 ? void 0 : await upstreamOf(root, branch);
351
+ let upstream;
352
+ if (upstreamRef !== void 0) {
353
+ const [behind, ahead] = (await readLine$1(root, [
354
+ "rev-list",
355
+ "--left-right",
356
+ "--count",
357
+ `${upstreamRef}...HEAD`
358
+ ]) ?? "").split(/\s+/u).map(Number);
359
+ if (Number.isInteger(ahead) && Number.isInteger(behind)) upstream = {
360
+ ref: upstreamRef,
361
+ ahead,
362
+ behind
363
+ };
364
+ }
365
+ const truncated = entries.length > MAX_LISTED_FILES || untracked.length > MAX_UNTRACKED_COUNTED;
366
+ return {
367
+ root,
368
+ base,
369
+ changes: {
370
+ added: entries.reduce((sum, entry) => sum + entry.added, 0),
371
+ removed: entries.reduce((sum, entry) => sum + entry.removed, 0),
372
+ files: entries.length,
373
+ ...branch === void 0 ? {} : { branch },
374
+ ...base.ref === void 0 ? {} : { base: base.ref },
375
+ ...truncated ? { truncated: true } : {},
376
+ ...upstream === void 0 ? {} : { upstream },
377
+ ...rebasing ? { rebase: { conflicts } } : {}
378
+ },
379
+ summary: {
380
+ repository: true,
381
+ files: entries.slice(0, MAX_LISTED_FILES),
382
+ ...branch === void 0 ? {} : { branch },
383
+ ...base.ref === void 0 ? {} : { base: base.ref },
384
+ ...base.mergeBase === void 0 ? {} : { mergeBase: base.mergeBase },
385
+ ...truncated ? { truncated: true } : {}
386
+ }
387
+ };
388
+ },
389
+ async fileDiff(review, filePath) {
390
+ const entry = review.summary.files.find((file) => file.path === filePath);
391
+ if (entry === void 0) throw new Error("That path is not in this review.");
392
+ if (entry.status === "untracked") {
393
+ const absolute = node_path.default.join(review.root, entry.path);
394
+ const stat = node_fs.default.lstatSync(absolute);
395
+ if (stat.isSymbolicLink()) return {
396
+ path: entry.path,
397
+ hunks: [{
398
+ start: 1,
399
+ rows: [{
400
+ marker: "+",
401
+ line: 1,
402
+ content: node_fs.default.readlinkSync(absolute)
403
+ }]
404
+ }]
405
+ };
406
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return {
407
+ path: entry.path,
408
+ hunks: [],
409
+ tooLarge: true
410
+ };
411
+ const content = node_fs.default.readFileSync(absolute);
412
+ if (content.subarray(0, BINARY_PROBE_BYTES).includes(0)) return {
413
+ path: entry.path,
414
+ hunks: [],
415
+ binary: true
416
+ };
417
+ const lines = content.toString("utf8").split("\n");
418
+ if (lines.at(-1) === "") lines.pop();
419
+ if (lines.length > MAX_ROWS) return {
420
+ path: entry.path,
421
+ hunks: [],
422
+ tooLarge: true
423
+ };
424
+ return {
425
+ path: entry.path,
426
+ hunks: lines.length === 0 ? [] : [{
427
+ start: 1,
428
+ rows: lines.map((content, index) => ({
429
+ marker: "+",
430
+ line: index + 1,
431
+ content
432
+ }))
433
+ }]
434
+ };
435
+ }
436
+ const result = await require_worktreeOperations.runGit(review.root, [
437
+ "diff",
438
+ "-U3",
439
+ "--no-color",
440
+ "--no-ext-diff",
441
+ "--no-textconv",
442
+ "--no-renames",
443
+ review.base.from,
444
+ "--",
445
+ `:(top,literal)${entry.path}`
446
+ ], {
447
+ timeout: require_worktreeOperations.READ_TIMEOUT_MS,
448
+ maxBuffer: MAX_FILE_BYTES
449
+ });
450
+ if (result.overflow) return {
451
+ path: entry.path,
452
+ hunks: [],
453
+ tooLarge: true
454
+ };
455
+ if (result.code !== 0) throw new Error(`git diff failed (exit ${String(result.code)}).`);
456
+ const parsed = parseUnifiedDiff(result.stdout);
457
+ if (parsed.binary || entry.binary === true) return {
458
+ path: entry.path,
459
+ hunks: [],
460
+ binary: true
461
+ };
462
+ if (parsed.rows > MAX_ROWS) return {
463
+ path: entry.path,
464
+ hunks: [],
465
+ tooLarge: true
466
+ };
467
+ return {
468
+ path: entry.path,
469
+ hunks: parsed.hunks
470
+ };
471
+ }
472
+ };
473
+ }
474
+ //#endregion
475
+ //#region src/services/gitAuth/index.ts
476
+ /**
477
+ * Per-workspace remote auth for doompi-git's own fetch, pull, push and rebase.
478
+ *
479
+ * DESIGN PATTERNS:
480
+ * - One file outside every repository, folder 0700 and file 0600, repaired on
481
+ * read if something loosened it. The token never leaves this module except
482
+ * into the environment of one git child process.
483
+ * - Config reaches git through GIT_CONFIG_COUNT environment entries, never
484
+ * argv, so nothing secret shows in `ps`. The first entry empties the
485
+ * credential helper list, which is what keeps macOS's osxkeychain helper from
486
+ * storing the token after a successful push.
487
+ * - The token is offered only to the host it was entered for. A repository
488
+ * whose remote points anywhere else gets this machine's own credentials.
489
+ *
490
+ * AVOID:
491
+ * - Touching process.env. The hub runs every session; anything set there
492
+ * would reach the agent's shell, which the user ruled out.
493
+ */
494
+ const OWNER_ONLY_DIRECTORY = 448;
495
+ const OWNER_ONLY_FILE = 384;
496
+ const LOOSE_BITS = 63;
497
+ const HOST_PATTERN = /^[a-z0-9.-]{1,253}(:\d{1,5})?$/u;
498
+ const MAX_USERNAME = 256;
499
+ const MAX_TOKEN = 4096;
500
+ const SETTINGS_HINT = "Open settings, then repository, then git remote.";
501
+ /** Environment that would make git log or skip what this module relies on. */
502
+ const STRIPPED_ALWAYS = ["GIT_CURL_VERBOSE", "GIT_TRACE_REDACT"];
503
+ const STRIPPED_PREFIXES = ["GIT_TRACE"];
504
+ /** Environment that could redirect or override credentials when the workspace's own are in play. */
505
+ const STRIPPED_CREDENTIALED = [
506
+ "GIT_CONFIG_PARAMETERS",
507
+ "GIT_CONFIG_COUNT",
508
+ "GIT_SSL_NO_VERIFY",
509
+ "SSH_ASKPASS",
510
+ "GIT_SSH",
511
+ "GIT_SSH_COMMAND"
512
+ ];
513
+ const CONFIG_ENTRY = /^GIT_CONFIG_(KEY|VALUE)_\d+$/u;
514
+ /** The inline helper: answers `get` from this child's environment, and ignores `store` and `erase`. */
515
+ const ENV_CREDENTIAL_HELPER = "!f(){ test \"$1\" = get && printf \"username=%s\\npassword=%s\\n\" \"$DOOMPI_GIT_USERNAME\" \"$DOOMPI_GIT_TOKEN\"; }; f";
516
+ /** Whether a value holds an ASCII control character; a newline in a credential field could add a line to git's credential protocol. */
517
+ function hasControl(value) {
518
+ for (let index = 0; index < value.length; index += 1) {
519
+ const code = value.charCodeAt(index);
520
+ if (code < 32 || code === 127) return true;
521
+ }
522
+ return false;
523
+ }
524
+ function isRecord(value) {
525
+ return typeof value === "object" && value !== null && !Array.isArray(value);
526
+ }
527
+ /** The workspace key: the canonical root, so a symlinked path and its target share one entry. */
528
+ function workspaceKey(workspaceRoot) {
529
+ try {
530
+ return node_fs.default.realpathSync(workspaceRoot);
531
+ } catch {
532
+ return node_path.default.resolve(workspaceRoot);
533
+ }
534
+ }
535
+ function expandHome(keyPath, homeDir) {
536
+ return keyPath.startsWith("~/") ? node_path.default.join(homeDir, keyPath.slice(2)) : keyPath;
537
+ }
538
+ function parseConfig(value) {
539
+ if (!isRecord(value)) return void 0;
540
+ if (value.method === "none") return { method: "none" };
541
+ if (value.method === "ssh") {
542
+ if (value.keyPath === void 0) return { method: "ssh" };
543
+ return typeof value.keyPath === "string" && value.keyPath !== "" ? {
544
+ method: "ssh",
545
+ keyPath: value.keyPath
546
+ } : void 0;
547
+ }
548
+ if (value.method === "https" && typeof value.host === "string" && typeof value.username === "string" && typeof value.token === "string" && value.token !== "") return {
549
+ method: "https",
550
+ host: value.host,
551
+ username: value.username,
552
+ token: value.token
553
+ };
554
+ }
555
+ /** What the browser may see. The token becomes a yes or no. */
556
+ function publicView(config) {
557
+ if (config.method === "ssh") return config.keyPath === void 0 ? {
558
+ method: "ssh",
559
+ ssh: {}
560
+ } : {
561
+ method: "ssh",
562
+ ssh: { keyPath: config.keyPath }
563
+ };
564
+ if (config.method === "https") return {
565
+ method: "https",
566
+ https: {
567
+ host: config.host,
568
+ username: config.username,
569
+ hasToken: config.token !== ""
570
+ }
571
+ };
572
+ return { method: "none" };
573
+ }
574
+ /**
575
+ * A browser save request, checked field by field. An absent HTTPS token keeps
576
+ * the saved one, and only for the same host: a token never follows a host it
577
+ * was not entered for.
578
+ */
579
+ function parseGitAuthSave(request, current, homeDir) {
580
+ if (!isRecord(request)) throw require_worktreeOperations.invalidRequest("The git auth request is not an object.", "Send method none, ssh or https.");
581
+ if (request.method === "none") return { method: "none" };
582
+ if (request.method === "ssh") {
583
+ if (request.keyPath === void 0 || request.keyPath === "") return { method: "ssh" };
584
+ if (typeof request.keyPath !== "string" || hasControl(request.keyPath)) throw require_worktreeOperations.invalidRequest("The key path is not a plain path.", "Give the key as an absolute path or one under ~/.");
585
+ const keyPath = request.keyPath.trim();
586
+ if (!keyPath.startsWith("/") && !keyPath.startsWith("~/")) throw require_worktreeOperations.invalidRequest("The key path is not absolute.", "Give the key as an absolute path or one under ~/.");
587
+ let isFile = false;
588
+ try {
589
+ isFile = node_fs.default.statSync(expandHome(keyPath, homeDir)).isFile();
590
+ } catch {
591
+ isFile = false;
592
+ }
593
+ if (!isFile) throw require_worktreeOperations.invalidRequest(`No key file at ${keyPath}.`, "Check the path, or leave it blank to use ssh-agent.");
594
+ return {
595
+ method: "ssh",
596
+ keyPath
597
+ };
598
+ }
599
+ if (request.method === "https") {
600
+ const host = typeof request.host === "string" ? request.host.trim().toLowerCase() : "";
601
+ if (!HOST_PATTERN.test(host)) throw require_worktreeOperations.invalidRequest("The host is not a host name.", "Use a host like github.com, with an optional :port.");
602
+ const username = typeof request.username === "string" ? request.username.trim() : "";
603
+ if (username === "" || username.length > MAX_USERNAME || hasControl(username)) throw require_worktreeOperations.invalidRequest("The username is empty or not plain text.", "Enter the username the host knows you by.");
604
+ if (request.token !== void 0 && request.token !== "") {
605
+ if (typeof request.token !== "string" || request.token.length > MAX_TOKEN || hasControl(request.token)) throw require_worktreeOperations.invalidRequest("The token is not plain text.", "Paste the token again without line breaks.");
606
+ return {
607
+ method: "https",
608
+ host,
609
+ username,
610
+ token: request.token
611
+ };
612
+ }
613
+ if (current.method === "https" && current.host === host && current.token !== "") return {
614
+ method: "https",
615
+ host,
616
+ username,
617
+ token: current.token
618
+ };
619
+ throw require_worktreeOperations.invalidRequest(current.method === "https" ? "The host changed, so the saved token cannot follow it." : "A token is required.", "Enter the personal access token for this host.");
620
+ }
621
+ throw require_worktreeOperations.invalidRequest("The git auth method is unknown.", "Send method none, ssh or https.");
622
+ }
623
+ /** Tightens a file or folder something left readable by group or others. */
624
+ function tighten(target, mode) {
625
+ try {
626
+ if ((node_fs.default.statSync(target).mode & LOOSE_BITS) !== 0) node_fs.default.chmodSync(target, mode);
627
+ } catch {}
628
+ }
629
+ function createGitAuthStore(homeDir = node_os.default.homedir()) {
630
+ const file = require_worktreeOperations.credentialsFile(homeDir);
631
+ const readFile = () => {
632
+ tighten(file, OWNER_ONLY_FILE);
633
+ const raw = require_worktreeOperations.readJson(file);
634
+ const workspaces = {};
635
+ if (isRecord(raw) && raw.version === 1 && isRecord(raw.workspaces)) for (const [key, value] of Object.entries(raw.workspaces)) {
636
+ const config = parseConfig(value);
637
+ if (config !== void 0) workspaces[key] = config;
638
+ }
639
+ return {
640
+ version: 1,
641
+ workspaces
642
+ };
643
+ };
644
+ const read = (workspaceRoot) => readFile().workspaces[workspaceKey(workspaceRoot)] ?? { method: "none" };
645
+ return {
646
+ read,
647
+ view: (workspaceRoot) => publicView(read(workspaceRoot)),
648
+ save(workspaceRoot, request) {
649
+ const key = workspaceKey(workspaceRoot);
650
+ const current = readFile();
651
+ const next = parseGitAuthSave(request, current.workspaces[key] ?? { method: "none" }, homeDir);
652
+ const root = require_worktreeOperations.doomGitRoot(homeDir);
653
+ node_fs.default.mkdirSync(root, {
654
+ recursive: true,
655
+ mode: OWNER_ONLY_DIRECTORY
656
+ });
657
+ node_fs.default.chmodSync(root, OWNER_ONLY_DIRECTORY);
658
+ const workspaces = { ...current.workspaces };
659
+ if (next.method === "none") delete workspaces[key];
660
+ else workspaces[key] = next;
661
+ require_worktreeOperations.writeJsonAtomic(file, {
662
+ version: 1,
663
+ workspaces
664
+ });
665
+ node_fs.default.chmodSync(file, OWNER_ONLY_FILE);
666
+ return publicView(next);
667
+ }
668
+ };
669
+ }
670
+ /** The transport and host a remote URL names, or undefined for a local path or anything else. */
671
+ function remoteTransport(url) {
672
+ const trimmed = url.trim();
673
+ if (/^[a-z][a-z0-9+.-]*:\/\//iu.test(trimmed)) try {
674
+ const parsed = new URL(trimmed);
675
+ const kind = parsed.protocol === "https:" ? "https" : parsed.protocol === "http:" ? "http" : parsed.protocol === "ssh:" ? "ssh" : void 0;
676
+ return kind === void 0 ? void 0 : {
677
+ kind,
678
+ host: parsed.host.toLowerCase()
679
+ };
680
+ } catch {
681
+ return;
682
+ }
683
+ const scp = /^(?:[^@/]+@)?([^:/]+):(?!\/\/)/u.exec(trimmed);
684
+ if (scp !== null && scp[1] !== void 0 && scp[1].length > 1) return {
685
+ kind: "ssh",
686
+ host: scp[1].toLowerCase()
687
+ };
688
+ }
689
+ /** Quotes one word for the POSIX shell git runs GIT_SSH_COMMAND through. */
690
+ function shellQuote(value) {
691
+ return `'${value.replaceAll("'", "'\\''")}'`;
692
+ }
693
+ /**
694
+ * The environment for one fetch or push against `remoteUrl`.
695
+ *
696
+ * Every call drops tracing (which can log credentials) and turns prompts off,
697
+ * because no terminal is attached. Only when the workspace's method matches the
698
+ * remote does anything secret go in, and then only into this child's env.
699
+ */
700
+ function remoteEnv(config, remoteUrl, baseEnv, homeDir) {
701
+ const env = { ...baseEnv };
702
+ for (const key of Object.keys(env)) if (STRIPPED_ALWAYS.includes(key) || STRIPPED_PREFIXES.some((prefix) => key.startsWith(prefix))) delete env[key];
703
+ env.GIT_TERMINAL_PROMPT = "0";
704
+ env.GCM_INTERACTIVE = "never";
705
+ const transport = remoteTransport(remoteUrl);
706
+ const credentialed = () => {
707
+ for (const key of Object.keys(env)) if (STRIPPED_CREDENTIALED.includes(key) || CONFIG_ENTRY.test(key)) delete env[key];
708
+ env.GIT_ASKPASS = "true";
709
+ };
710
+ if (config.method === "https") {
711
+ if (transport?.kind !== "https" || transport.host !== config.host) return {
712
+ env,
713
+ credentialed: false,
714
+ mismatch: `This workspace's token is for https://${config.host}, and this remote is not.`
715
+ };
716
+ credentialed();
717
+ env.GIT_CONFIG_COUNT = "3";
718
+ env.GIT_CONFIG_KEY_0 = "credential.helper";
719
+ env.GIT_CONFIG_VALUE_0 = "";
720
+ env.GIT_CONFIG_KEY_1 = `credential.https://${config.host}.helper`;
721
+ env.GIT_CONFIG_VALUE_1 = ENV_CREDENTIAL_HELPER;
722
+ env.GIT_CONFIG_KEY_2 = "http.sslVerify";
723
+ env.GIT_CONFIG_VALUE_2 = "true";
724
+ env.GIT_ALLOW_PROTOCOL = "https";
725
+ env.DOOMPI_GIT_USERNAME = config.username;
726
+ env.DOOMPI_GIT_TOKEN = config.token;
727
+ return {
728
+ env,
729
+ credentialed: true
730
+ };
731
+ }
732
+ if (config.method === "ssh") {
733
+ if (transport?.kind !== "ssh") return {
734
+ env,
735
+ credentialed: false,
736
+ mismatch: "This workspace uses SSH, and this remote is not an SSH remote."
737
+ };
738
+ credentialed();
739
+ env.GIT_SSH_COMMAND = [
740
+ "ssh",
741
+ ...config.keyPath === void 0 ? [] : [
742
+ "-i",
743
+ shellQuote(expandHome(config.keyPath, homeDir)),
744
+ "-o",
745
+ "IdentitiesOnly=yes"
746
+ ],
747
+ "-o",
748
+ "BatchMode=yes",
749
+ "-o",
750
+ "ConnectTimeout=15"
751
+ ].join(" ");
752
+ env.GIT_ALLOW_PROTOCOL = "ssh";
753
+ return {
754
+ env,
755
+ credentialed: true
756
+ };
757
+ }
758
+ return {
759
+ env,
760
+ credentialed: false
761
+ };
762
+ }
763
+ //#endregion
74
764
  //#region src/services/newSessionRequest/index.ts
75
765
  const MAX_NAME_LENGTH = 120;
76
766
  /** Trimmed text, undefined when absent or blank, false when not text at all. */
@@ -115,7 +805,7 @@ function newSessionRequest(body) {
115
805
  return { error: "The mode must be existing-branch or new-branch." };
116
806
  }
117
807
  //#endregion
118
- //#region src/extensions/(backend)/api/_lib/route.server.ts
808
+ //#region src/extensions/(backend)/api/git/_lib/route.server.ts
119
809
  /**
120
810
  * The worktree surface the cockpit panel calls.
121
811
  *
@@ -138,7 +828,7 @@ function failed(error) {
138
828
  return Response.json({ error: "The worktree operation failed." }, { status: 500 });
139
829
  }
140
830
  //#endregion
141
- //#region src/extensions/(backend)/api/route.server.ts
831
+ //#region src/extensions/(backend)/api/git/route.server.ts
142
832
  var route_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineRoute)({
143
833
  basePath: "git",
144
834
  start(context) {
@@ -203,14 +893,67 @@ var route_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineRoute)
203
893
  if (root === void 0) return badRequest("That repository is not admitted to this cockpit.");
204
894
  return root;
205
895
  };
896
+ const homeDir = context.homeDirectory ?? node_os.default.homedir();
897
+ const gitAuth = createGitAuthStore(homeDir);
898
+ const branchDiff = createBranchDiff();
899
+ /**
900
+ * A workspace's remote auth. Workspace mounts only, so the step-up gate on
901
+ * `PUT /api/workspaces/<id>/plugins/git/auth` is the one way to write it.
902
+ * The view never carries the token.
903
+ */
904
+ const auth = async (request, url) => {
905
+ if (url.pathname !== "/auth") return void 0;
906
+ if (context.scope !== "workspace") return Response.json({ error: "This route belongs to a workspace." }, { status: 404 });
907
+ if (request.method !== "GET" && request.method !== "PUT") return Response.json({ error: "Use GET or PUT." }, { status: 405 });
908
+ const root = rootOf(url);
909
+ if (root instanceof Response) return root;
910
+ if (request.method === "GET") return Response.json(gitAuth.view(root));
911
+ try {
912
+ return Response.json(gitAuth.save(root, await request.json().catch(() => void 0)));
913
+ } catch (error) {
914
+ if (error instanceof require_worktreeOperations.DoomGitExpectedError && error.code === "invalid_request") {
915
+ const text = error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
916
+ return Response.json({
917
+ error: text,
918
+ code: error.code
919
+ }, { status: 400 });
920
+ }
921
+ throw error;
922
+ }
923
+ };
924
+ /**
925
+ * The session's change against its base. Session mounts only, rooted at the
926
+ * session's own checkout; a file is served only when it is in the change set
927
+ * computed for the same request.
928
+ */
929
+ const review = async (request, url) => {
930
+ if (url.pathname !== "/review" && url.pathname !== "/review/file") return void 0;
931
+ const cwd = context.scope === "session" ? context.cwd : void 0;
932
+ if (cwd === void 0) return Response.json({ error: "This route belongs to a session." }, { status: 404 });
933
+ if (request.method !== "GET") return Response.json({ error: "Use GET." }, { status: 405 });
934
+ let recordedBaseRef;
935
+ try {
936
+ recordedBaseRef = require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(cwd, homeDir)).list().find((record) => record.sessionId === context.sessionId)?.baseRef;
937
+ } catch {
938
+ recordedBaseRef = void 0;
939
+ }
940
+ const result = await branchDiff.review(cwd, recordedBaseRef === void 0 ? {} : { recordedBaseRef });
941
+ if (url.pathname === "/review") return Response.json(result?.summary ?? {
942
+ repository: false,
943
+ files: []
944
+ });
945
+ const filePath = url.searchParams.get("path") ?? "";
946
+ if (result === void 0 || !result.summary.files.some((file) => file.path === filePath)) return Response.json({ error: "That file is not part of this review." }, { status: 404 });
947
+ return Response.json(await branchDiff.fileDiff(result, filePath));
948
+ };
206
949
  return {
207
950
  async fetch(request) {
208
951
  const url = new URL(request.url);
209
952
  try {
210
- const answered = await newSession(request, url);
953
+ const answered = await newSession(request, url) ?? await auth(request, url) ?? await review(request, url);
211
954
  if (answered !== void 0) return answered;
212
955
  } catch (error) {
213
- context.onNotice(`new-session request failed: ${error.name}`);
956
+ context.onNotice(`git request failed: ${error.name}`);
214
957
  return failed(error);
215
958
  }
216
959
  const root = rootOf(url);
@@ -250,6 +993,494 @@ var route_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineRoute)
250
993
  }
251
994
  });
252
995
  //#endregion
996
+ //#region src/services/gitFailure/index.ts
997
+ const RULES = [
998
+ {
999
+ code: "host_key_changed",
1000
+ phrases: ["remote host identification has changed"],
1001
+ message: "The remote's SSH host key changed since this machine last saw it.",
1002
+ recovery: "Check with the host that the change is expected, then update ~/.ssh/known_hosts from a terminal.",
1003
+ retryable: false
1004
+ },
1005
+ {
1006
+ code: "host_key_unknown",
1007
+ phrases: [
1008
+ "host key verification failed",
1009
+ "no ed25519 host key is known",
1010
+ "no rsa host key is known"
1011
+ ],
1012
+ message: "This machine does not trust the remote's SSH host key yet.",
1013
+ recovery: "Run `ssh -T git@<host>` once in a terminal and accept the key, then try again.",
1014
+ retryable: false
1015
+ },
1016
+ {
1017
+ code: "auth_failed",
1018
+ phrases: [
1019
+ "authentication failed",
1020
+ "could not read username",
1021
+ "could not read password",
1022
+ "permission denied (publickey",
1023
+ "returned error: 401",
1024
+ "returned error: 403",
1025
+ "terminal prompts disabled",
1026
+ "load key",
1027
+ "unprotected private key",
1028
+ "invalid format"
1029
+ ],
1030
+ message: "The remote refused the credentials.",
1031
+ recovery: `Check this workspace's git remote auth. ${SETTINGS_HINT}`,
1032
+ retryable: false
1033
+ },
1034
+ {
1035
+ code: "repository_not_found",
1036
+ phrases: ["repository not found", "does not appear to be a git repository"],
1037
+ message: "The remote repository was not found, or these credentials cannot see it.",
1038
+ recovery: `Check the remote URL and that the credentials have access. ${SETTINGS_HINT}`,
1039
+ retryable: false
1040
+ },
1041
+ {
1042
+ code: "remote_unreachable",
1043
+ phrases: [
1044
+ "could not resolve host",
1045
+ "connection refused",
1046
+ "connection timed out",
1047
+ "operation timed out",
1048
+ "unable to access",
1049
+ "network is unreachable"
1050
+ ],
1051
+ message: "The remote could not be reached.",
1052
+ recovery: "Check the network and the remote URL, then try again.",
1053
+ retryable: true
1054
+ },
1055
+ {
1056
+ code: "push_lease_rejected",
1057
+ phrases: ["(stale info)"],
1058
+ message: "The remote branch moved since your last fetch, so the force push was refused.",
1059
+ recovery: "Pull to see the new commits, then decide whether to push again.",
1060
+ retryable: false
1061
+ },
1062
+ {
1063
+ code: "push_needs_force",
1064
+ phrases: ["(non-fast-forward)", "(fetch first)"],
1065
+ message: "The remote branch has commits yours replaced, usually after a rebase.",
1066
+ recovery: "Confirm a force push with lease, or pull first to keep the remote commits.",
1067
+ retryable: false
1068
+ },
1069
+ {
1070
+ code: "worktree_dirty",
1071
+ phrases: [
1072
+ "unstaged changes",
1073
+ "uncommitted changes",
1074
+ "would be overwritten",
1075
+ "your index contains uncommitted changes"
1076
+ ],
1077
+ message: "There are uncommitted changes in the way.",
1078
+ recovery: "Commit or stash your changes first.",
1079
+ retryable: false
1080
+ }
1081
+ ];
1082
+ function classifyGitFailure(operation, result, mismatch) {
1083
+ if (result.timedOut) return new require_worktreeOperations.DoomGitExpectedError("git_timeout", `git ${operation} took too long and was stopped.`, true, "Check the network, then try again.");
1084
+ const text = `${result.stderr}\n${result.stdout}`.toLowerCase();
1085
+ const rule = RULES.find((candidate) => candidate.phrases.some((phrase) => text.includes(phrase)));
1086
+ if (rule === void 0) return new require_worktreeOperations.DoomGitExpectedError("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.");
1087
+ const recovery = rule.code === "auth_failed" && mismatch !== void 0 ? `${mismatch} ${rule.recovery}` : rule.recovery;
1088
+ return new require_worktreeOperations.DoomGitExpectedError(rule.code, rule.message, rule.retryable, recovery);
1089
+ }
1090
+ //#endregion
1091
+ //#region src/services/gitSync/index.ts
1092
+ /**
1093
+ * Manual pull, push and rebase for a session's checkout.
1094
+ *
1095
+ * DESIGN PATTERNS:
1096
+ * - The workspace's auth goes into the environment of the one fetch or push
1097
+ * that needs it, built fresh per call. Rebase itself runs locally and never
1098
+ * sees a credential.
1099
+ * - Fetch and rebase are separate commands, so a hung network can never leave a
1100
+ * rebase half applied.
1101
+ * - A conflicted rebase is not an error. It is left paused for the reader to
1102
+ * hand to the agent or abort, and git's own state reports it from then on.
1103
+ * - Pull and rebase refuse uncommitted tracked changes rather than stash them.
1104
+ * Untracked files only block when git says they would be overwritten.
1105
+ * - Push never forces on its own. A rejection comes back as `push_needs_force`,
1106
+ * and only a confirmed retry sends `--force-with-lease --force-if-includes`,
1107
+ * which git refuses if the remote holds commits this branch never integrated.
1108
+ */
1109
+ const DONE = { outcome: "done" };
1110
+ function expected(code, message, recovery) {
1111
+ return new require_worktreeOperations.DoomGitExpectedError(code, message, false, recovery);
1112
+ }
1113
+ async function readLine(cwd, args) {
1114
+ const result = await require_worktreeOperations.runGit(cwd, args, { timeout: require_worktreeOperations.READ_TIMEOUT_MS });
1115
+ const out = result.stdout.trim();
1116
+ return result.code === 0 && out !== "" ? out : void 0;
1117
+ }
1118
+ async function toplevel(cwd) {
1119
+ const root = await readLine(cwd, ["rev-parse", "--show-toplevel"]);
1120
+ if (root === void 0) throw expected("not_a_repository", "This session is not in a git checkout.", "Open the session in a git repository.");
1121
+ return root;
1122
+ }
1123
+ async function rebasing(root) {
1124
+ for (const name of ["rebase-merge", "rebase-apply"]) {
1125
+ const gitPath = await readLine(root, [
1126
+ "rev-parse",
1127
+ "--git-path",
1128
+ name
1129
+ ]);
1130
+ if (gitPath !== void 0 && node_fs.default.existsSync(node_path.default.resolve(root, gitPath))) return true;
1131
+ }
1132
+ return false;
1133
+ }
1134
+ async function conflicts(root) {
1135
+ return (await require_worktreeOperations.runGit(root, [
1136
+ "diff",
1137
+ "--name-only",
1138
+ "--diff-filter=U",
1139
+ "-z"
1140
+ ], { timeout: require_worktreeOperations.READ_TIMEOUT_MS })).stdout.split("\0").filter((file) => file !== "");
1141
+ }
1142
+ async function currentBranch(root) {
1143
+ const branch = await readLine(root, [
1144
+ "symbolic-ref",
1145
+ "--quiet",
1146
+ "--short",
1147
+ "HEAD"
1148
+ ]);
1149
+ if (branch === void 0) throw expected("detached_head", "HEAD is detached, so there is no branch to sync.", "Check out a branch first.");
1150
+ return branch;
1151
+ }
1152
+ async function guard(root, needsCleanTree) {
1153
+ 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.");
1154
+ const branch = await currentBranch(root);
1155
+ if (needsCleanTree) {
1156
+ if (await readLine(root, [
1157
+ "status",
1158
+ "--porcelain",
1159
+ "--untracked-files=no"
1160
+ ]) !== void 0) throw expected("worktree_dirty", "There are uncommitted changes.", "Commit or stash your changes first.");
1161
+ }
1162
+ return branch;
1163
+ }
1164
+ function createGitSync(options) {
1165
+ const baseEnv = options.baseEnv ?? process.env;
1166
+ /** One credentialed network command against `remote`, classified on failure. */
1167
+ const network = async (root, context, remote, operation, args, urlArgs = []) => {
1168
+ const url = await readLine(root, [
1169
+ "remote",
1170
+ "get-url",
1171
+ ...urlArgs,
1172
+ remote
1173
+ ]);
1174
+ if (url === void 0) throw expected("no_remote", `There is no remote named ${remote}.`, "Add the remote in a terminal first.");
1175
+ const prepared = remoteEnv(context.auth, url, baseEnv, options.homeDir);
1176
+ const result = await require_worktreeOperations.runGit(root, args, {
1177
+ timeout: require_worktreeOperations.NETWORK_TIMEOUT_MS,
1178
+ env: prepared.env
1179
+ });
1180
+ if (result.code !== 0) throw classifyGitFailure(operation, result, prepared.mismatch);
1181
+ };
1182
+ /** Rebases onto `onto`; a stop on conflicts leaves the rebase paused and says so. */
1183
+ const rebaseOnto = async (root, onto) => {
1184
+ const result = await require_worktreeOperations.runGit(root, ["rebase", onto], {
1185
+ timeout: require_worktreeOperations.REBASE_TIMEOUT_MS,
1186
+ env: {
1187
+ ...baseEnv,
1188
+ GIT_EDITOR: "true",
1189
+ GIT_TERMINAL_PROMPT: "0"
1190
+ }
1191
+ });
1192
+ if (result.code === 0) return DONE;
1193
+ if (await rebasing(root)) return {
1194
+ outcome: "paused",
1195
+ conflicts: await conflicts(root)
1196
+ };
1197
+ throw classifyGitFailure("rebase", result);
1198
+ };
1199
+ /** The remote a ref like `origin/main` or `refs/remotes/origin/main` belongs to. */
1200
+ const remoteOfRef = async (root, ref) => {
1201
+ const full = await readLine(root, [
1202
+ "rev-parse",
1203
+ "--symbolic-full-name",
1204
+ ref
1205
+ ]);
1206
+ if (full === void 0 || !full.startsWith("refs/remotes/")) return void 0;
1207
+ const rest = full.slice(13);
1208
+ const cut = rest.indexOf("/");
1209
+ return cut > 0 ? rest.slice(0, cut) : void 0;
1210
+ };
1211
+ return {
1212
+ async pull(context) {
1213
+ const root = await toplevel(context.cwd);
1214
+ const branch = await guard(root, true);
1215
+ const remote = await readLine(root, ["config", `branch.${branch}.remote`]);
1216
+ const upstream = await readLine(root, [
1217
+ "rev-parse",
1218
+ "--abbrev-ref",
1219
+ "--symbolic-full-name",
1220
+ `${branch}@{upstream}`
1221
+ ]);
1222
+ if (remote === void 0 || upstream === void 0) throw expected("no_upstream", `${branch} has no upstream to pull from.`, "Push once to set an upstream.");
1223
+ if (remote !== ".") await network(root, context, remote, "fetch", [
1224
+ "fetch",
1225
+ "--prune",
1226
+ remote
1227
+ ]);
1228
+ return rebaseOnto(root, upstream);
1229
+ },
1230
+ async push(context, force) {
1231
+ const root = await toplevel(context.cwd);
1232
+ const branch = await guard(root, false);
1233
+ const configuredRemote = await readLine(root, ["config", `branch.${branch}.remote`]);
1234
+ const merge = await readLine(root, ["config", `branch.${branch}.merge`]);
1235
+ let remote = configuredRemote;
1236
+ let target = merge;
1237
+ const args = ["push", "--porcelain"];
1238
+ if (remote === void 0 || target === void 0 || remote === ".") {
1239
+ const remotes = (await readLine(root, ["remote"]) ?? "").split("\n").filter((name) => name !== "");
1240
+ remote = remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : void 0;
1241
+ 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.");
1242
+ target = `refs/heads/${branch}`;
1243
+ args.push("--set-upstream");
1244
+ }
1245
+ if (force) args.push(`--force-with-lease=${target}`, "--force-if-includes");
1246
+ args.push(remote, `HEAD:${target}`);
1247
+ await network(root, context, remote, "push", args, ["--push"]);
1248
+ return DONE;
1249
+ },
1250
+ async rebase(context) {
1251
+ const root = await toplevel(context.cwd);
1252
+ const base = await resolveBaseRef(root, await guard(root, true), context.recordedBaseRef);
1253
+ if (base === void 0) throw expected("no_base", "No base branch to rebase onto.", "Fetch the remote, or create the worktree from a base.");
1254
+ const remote = await remoteOfRef(root, base);
1255
+ if (remote !== void 0) await network(root, context, remote, "fetch", [
1256
+ "fetch",
1257
+ "--prune",
1258
+ remote
1259
+ ]);
1260
+ return rebaseOnto(root, base);
1261
+ },
1262
+ async abortRebase(context) {
1263
+ const root = await toplevel(context.cwd);
1264
+ if (!await rebasing(root)) return DONE;
1265
+ const result = await require_worktreeOperations.runGit(root, ["rebase", "--abort"], { timeout: require_worktreeOperations.REBASE_TIMEOUT_MS });
1266
+ if (result.code !== 0) throw classifyGitFailure("rebase --abort", result);
1267
+ return DONE;
1268
+ }
1269
+ };
1270
+ }
1271
+ //#endregion
1272
+ //#region src/types/gitReview.ts
1273
+ /**
1274
+ * The cockpit's view of what this session changed against its base: the counts
1275
+ * the '# diff' group shows, what the review tab lists and draws, and the manual
1276
+ * sync that sits beside them.
1277
+ *
1278
+ * DESIGN PATTERNS:
1279
+ * - Declarations only, shared by the hub and the page.
1280
+ * - Its own channel, apart from worktrees. Worktrees are repository
1281
+ * management; the diff is this session's code change.
1282
+ * - A diff row carries one line number whose file follows from its marker: the
1283
+ * new file's for context and additions, the old file's for removals. It is
1284
+ * the same shape the shared DiffView draws.
1285
+ *
1286
+ * AVOID:
1287
+ * - Behaviour or node builtins. Browser code imports this file.
1288
+ */
1289
+ /** The session channel carrying this checkout's changes and the sync around them. */
1290
+ const GIT_CHANGES_TYPE = "git_changes";
1291
+ //#endregion
1292
+ //#region src/extensions/(backend)/channel/_lib/git-changes.server.ts
1293
+ /**
1294
+ * The '# diff' data channel: this session's change against its base, and the
1295
+ * manual sync commands the review tab sends back through it.
1296
+ *
1297
+ * DESIGN PATTERNS:
1298
+ * - Apart from the worktrees channel. Worktrees are repository management;
1299
+ * this is the session's own code change.
1300
+ * - Push, not poll. The session facet publishes a "changed" event after every
1301
+ * tool call and settled turn; recounts are coalesced to one in flight plus
1302
+ * one rerun, so a burst of tool calls costs at most two.
1303
+ * - One sync command per session. A rebase and a push must never overlap.
1304
+ * - Auth is read fresh for each command from the session's workspace, and goes
1305
+ * only into that command's git child.
1306
+ *
1307
+ * AVOID:
1308
+ * - Echoing git output. Failures go through classifyGitFailure, which matches
1309
+ * stderr and drops it, because a remote URL in it can carry a token.
1310
+ */
1311
+ function payloadOf$1(state) {
1312
+ return {
1313
+ ...state.changes === void 0 ? {} : { changes: state.changes },
1314
+ ...state.pending === void 0 ? {} : { pending: state.pending },
1315
+ ...state.error === void 0 ? {} : { error: state.error },
1316
+ ...state.errorTarget === void 0 ? {} : { errorTarget: state.errorTarget }
1317
+ };
1318
+ }
1319
+ /** A command the page sent, or undefined when the frame was not one. */
1320
+ function parseChangesCommand(payload) {
1321
+ if (typeof payload !== "object" || payload === null) return void 0;
1322
+ const value = payload;
1323
+ if (value.action === "pull" || value.action === "rebase" || value.action === "abort-rebase") return { action: value.action };
1324
+ if (value.action === "push") return value.force === true ? {
1325
+ action: "push",
1326
+ force: true
1327
+ } : { action: "push" };
1328
+ }
1329
+ const PENDING = {
1330
+ pull: "pulling…",
1331
+ push: "pushing…",
1332
+ rebase: "rebasing…",
1333
+ "abort-rebase": "aborting the rebase…"
1334
+ };
1335
+ /** The error target a failure maps to: a rejected plain push asks for a confirmed lease force. */
1336
+ function errorTargetFor$1(command, error) {
1337
+ if (command.action !== "push") return { action: command.action };
1338
+ return error instanceof require_worktreeOperations.DoomGitExpectedError && error.code === "push_needs_force" && command.force !== true ? {
1339
+ action: "push",
1340
+ forceRequired: true
1341
+ } : { action: "push" };
1342
+ }
1343
+ function failureText$1(error) {
1344
+ if (error instanceof require_worktreeOperations.DoomGitExpectedError) return error.message.replace(/^\[[a-z_]+\] /u, "").replace("\nRecovery: ", " ");
1345
+ return "The git command failed.";
1346
+ }
1347
+ function createGitChangesChannel(options = {}) {
1348
+ let receiveCommand;
1349
+ return {
1350
+ frameType: GIT_CHANGES_TYPE,
1351
+ start(host) {
1352
+ const homeDir = options.homeDir ?? node_os.default.homedir();
1353
+ const diff = options.diff ?? createBranchDiff();
1354
+ const sync = options.sync ?? createGitSync({ homeDir });
1355
+ const auth = options.auth ?? createGitAuthStore(homeDir);
1356
+ const latest = /* @__PURE__ */ new Map();
1357
+ const subscriptions = /* @__PURE__ */ new Map();
1358
+ const scopes = /* @__PURE__ */ new Map();
1359
+ const inFlight = /* @__PURE__ */ new Set();
1360
+ const rerun = /* @__PURE__ */ new Set();
1361
+ const busy = /* @__PURE__ */ new Set();
1362
+ /** The base the session's own worktree was created from, when it has one. */
1363
+ const recordedBaseRef = (scope) => {
1364
+ try {
1365
+ return require_worktreeOperations.createWorktreeRegistry(require_worktreeOperations.registryFile(scope.cwd, homeDir)).list().find((record) => record.sessionId === scope.sessionId)?.baseRef;
1366
+ } catch {
1367
+ return;
1368
+ }
1369
+ };
1370
+ /** Republishes a session, skipping a frame that would say nothing new. */
1371
+ const publish = (sessionId, next) => {
1372
+ const previous = latest.get(sessionId);
1373
+ latest.set(sessionId, next);
1374
+ if (previous !== void 0 && JSON.stringify(payloadOf$1(previous)) === JSON.stringify(payloadOf$1(next))) return;
1375
+ host.publish(sessionId, payloadOf$1(next));
1376
+ };
1377
+ const update = (sessionId, patch) => {
1378
+ const previous = latest.get(sessionId) ?? {
1379
+ changes: void 0,
1380
+ pending: void 0,
1381
+ error: void 0,
1382
+ errorTarget: void 0
1383
+ };
1384
+ publish(sessionId, {
1385
+ ...previous,
1386
+ ...patch
1387
+ });
1388
+ };
1389
+ /** Recounts one session; a request while one runs schedules exactly one more. */
1390
+ const refresh = (sessionId) => {
1391
+ const scope = scopes.get(sessionId);
1392
+ if (scope === void 0) return;
1393
+ if (inFlight.has(sessionId)) {
1394
+ rerun.add(sessionId);
1395
+ return;
1396
+ }
1397
+ inFlight.add(sessionId);
1398
+ const base = recordedBaseRef(scope);
1399
+ diff.review(scope.cwd, base === void 0 ? {} : { recordedBaseRef: base }).then((review) => {
1400
+ if (scopes.has(sessionId)) update(sessionId, { changes: review?.changes });
1401
+ }).catch((error) => {
1402
+ host.onNotice(`git diff refresh failed for ${sessionId} (${error instanceof Error ? error.name : "unknown"})`);
1403
+ }).finally(() => {
1404
+ inFlight.delete(sessionId);
1405
+ if (rerun.delete(sessionId)) refresh(sessionId);
1406
+ });
1407
+ };
1408
+ const run = (scope, command) => {
1409
+ const workspaceRoot = scope.sessionContext?.workspaceRoot ?? scope.cwd;
1410
+ const base = recordedBaseRef(scope);
1411
+ const context = {
1412
+ cwd: scope.cwd,
1413
+ auth: auth.read(workspaceRoot),
1414
+ ...base === void 0 ? {} : { recordedBaseRef: base }
1415
+ };
1416
+ if (command.action === "pull") return sync.pull(context);
1417
+ if (command.action === "push") return sync.push(context, command.force === true);
1418
+ if (command.action === "rebase") return sync.rebase(context);
1419
+ return sync.abortRebase(context);
1420
+ };
1421
+ const source = {
1422
+ payloadFor(scope) {
1423
+ const state = latest.get(scope.sessionId);
1424
+ return state === void 0 ? void 0 : payloadOf$1(state);
1425
+ },
1426
+ sessionAdded(scope) {
1427
+ scopes.set(scope.sessionId, scope);
1428
+ refresh(scope.sessionId);
1429
+ const unsubscribe = host.directEvents.subscribe(require_worktreeOperations.GIT_SESSION_CHANGED_EVENT, scope.sessionId, (payload) => {
1430
+ if (require_worktreeOperations.isSessionChangedEvent(payload)) refresh(scope.sessionId);
1431
+ });
1432
+ subscriptions.set(scope.sessionId, unsubscribe);
1433
+ },
1434
+ sessionRemoved(sessionId) {
1435
+ subscriptions.get(sessionId)?.();
1436
+ subscriptions.delete(sessionId);
1437
+ scopes.delete(sessionId);
1438
+ latest.delete(sessionId);
1439
+ rerun.delete(sessionId);
1440
+ busy.delete(sessionId);
1441
+ },
1442
+ close() {
1443
+ for (const unsubscribe of subscriptions.values()) unsubscribe();
1444
+ subscriptions.clear();
1445
+ scopes.clear();
1446
+ latest.clear();
1447
+ rerun.clear();
1448
+ busy.clear();
1449
+ }
1450
+ };
1451
+ receiveCommand = (scope, payload) => {
1452
+ const command = parseChangesCommand(payload);
1453
+ if (command === void 0 || !scopes.has(scope.sessionId)) return;
1454
+ if (busy.has(scope.sessionId)) return;
1455
+ busy.add(scope.sessionId);
1456
+ update(scope.sessionId, {
1457
+ pending: PENDING[command.action],
1458
+ error: void 0,
1459
+ errorTarget: void 0
1460
+ });
1461
+ run(scope, command).then(() => update(scope.sessionId, { pending: void 0 })).catch((error) => {
1462
+ host.onNotice(`git ${command.action} failed for ${scope.sessionId} (${error instanceof require_worktreeOperations.DoomGitExpectedError ? error.code : "unexpected"})`);
1463
+ update(scope.sessionId, {
1464
+ pending: void 0,
1465
+ error: failureText$1(error),
1466
+ errorTarget: errorTargetFor$1(command, error)
1467
+ });
1468
+ }).finally(() => {
1469
+ busy.delete(scope.sessionId);
1470
+ refresh(scope.sessionId);
1471
+ });
1472
+ };
1473
+ return source;
1474
+ },
1475
+ receive(scope, payload) {
1476
+ receiveCommand?.(scope, payload);
1477
+ }
1478
+ };
1479
+ }
1480
+ //#endregion
1481
+ //#region src/extensions/(backend)/channel/git-changes.server.ts
1482
+ var git_changes_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineChannel)(createGitChangesChannel);
1483
+ //#endregion
253
1484
  //#region src/types/webWorktrees.ts
254
1485
  /**
255
1486
  * The cockpit's view of this session's worktrees.
@@ -505,6 +1736,12 @@ function createWorktreesChannel(options = {}) {
505
1736
  //#region src/extensions/(backend)/channel/git-worktrees.server.ts
506
1737
  var git_worktrees_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineChannel)(createWorktreesChannel);
507
1738
  //#endregion
1739
+ //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
1740
+ var agent_settled_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineHook)((context) => context.root.hooks[1]);
1741
+ //#endregion
1742
+ //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
1743
+ var tool_execution_end_server_default = (0, _agimon_ai_doompi_core_extensionFile.defineHook)((context) => context.root.hooks[0]);
1744
+ //#endregion
508
1745
  //#region src/extensions/workspaces/sessions/(backend)/resource/_lib/doompiGit.server.ts
509
1746
  var doompiGit_server_default$1 = (context) => context.root.resources[0];
510
1747
  //#endregion
@@ -539,7 +1776,7 @@ const facet = (0, _agimon_ai_doompi_core_serverFacet.defineServerPlugin)({
539
1776
  return [at(route_server_default, context)];
540
1777
  },
541
1778
  get channels() {
542
- return [() => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
1779
+ return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
543
1780
  }
544
1781
  }),
545
1782
  workspace: (context) => ({
@@ -547,7 +1784,7 @@ const facet = (0, _agimon_ai_doompi_core_serverFacet.defineServerPlugin)({
547
1784
  return [at(route_server_default, context)];
548
1785
  },
549
1786
  get channels() {
550
- return [() => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
1787
+ return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
551
1788
  }
552
1789
  }),
553
1790
  session: async (context) => {
@@ -562,7 +1799,10 @@ const facet = (0, _agimon_ai_doompi_core_serverFacet.defineServerPlugin)({
562
1799
  return [at(route_server_default, context)];
563
1800
  },
564
1801
  get channels() {
565
- return [() => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
1802
+ return [() => via({ frameType: "git_changes" }, git_changes_server_default()), () => via({ frameType: "git_worktrees" }, git_worktrees_server_default())];
1803
+ },
1804
+ get hooks() {
1805
+ return [via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)), via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession))];
566
1806
  },
567
1807
  get resources() {
568
1808
  return [