overlord-cli 0.2611291037.0 → 0.2612011631.0

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.
package/dist/index.js CHANGED
@@ -843,10 +843,10 @@ function mergeDefs(...defs) {
843
843
  function cloneDef(schema) {
844
844
  return mergeDefs(schema._zod.def);
845
845
  }
846
- function getElementAtPath(obj, path55) {
847
- if (!path55)
846
+ function getElementAtPath(obj, path60) {
847
+ if (!path60)
848
848
  return obj;
849
- return path55.reduce((acc, key) => acc?.[key], obj);
849
+ return path60.reduce((acc, key) => acc?.[key], obj);
850
850
  }
851
851
  function promiseAllObject(promisesObj) {
852
852
  const keys = Object.keys(promisesObj);
@@ -1105,11 +1105,11 @@ function explicitlyAborted(x, startIndex = 0) {
1105
1105
  }
1106
1106
  return false;
1107
1107
  }
1108
- function prefixIssues(path55, issues) {
1108
+ function prefixIssues(path60, issues) {
1109
1109
  return issues.map((iss) => {
1110
1110
  var _a3;
1111
1111
  (_a3 = iss).path ?? (_a3.path = []);
1112
- iss.path.unshift(path55);
1112
+ iss.path.unshift(path60);
1113
1113
  return iss;
1114
1114
  });
1115
1115
  }
@@ -1642,16 +1642,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
1642
1642
  }
1643
1643
  function formatError(error62, mapper = (issue2) => issue2.message) {
1644
1644
  const fieldErrors = { _errors: [] };
1645
- const processError = (error63, path55 = []) => {
1645
+ const processError = (error63, path60 = []) => {
1646
1646
  for (const issue2 of error63.issues) {
1647
1647
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1648
- issue2.errors.map((issues) => processError({ issues }, [...path55, ...issue2.path]));
1648
+ issue2.errors.map((issues) => processError({ issues }, [...path60, ...issue2.path]));
1649
1649
  } else if (issue2.code === "invalid_key") {
1650
- processError({ issues: issue2.issues }, [...path55, ...issue2.path]);
1650
+ processError({ issues: issue2.issues }, [...path60, ...issue2.path]);
1651
1651
  } else if (issue2.code === "invalid_element") {
1652
- processError({ issues: issue2.issues }, [...path55, ...issue2.path]);
1652
+ processError({ issues: issue2.issues }, [...path60, ...issue2.path]);
1653
1653
  } else {
1654
- const fullpath = [...path55, ...issue2.path];
1654
+ const fullpath = [...path60, ...issue2.path];
1655
1655
  if (fullpath.length === 0) {
1656
1656
  fieldErrors._errors.push(mapper(issue2));
1657
1657
  } else {
@@ -1690,17 +1690,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
1690
1690
  }
1691
1691
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
1692
1692
  const result = { errors: [] };
1693
- const processError = (error63, path55 = []) => {
1693
+ const processError = (error63, path60 = []) => {
1694
1694
  var _a3;
1695
1695
  for (const issue2 of error63.issues) {
1696
1696
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1697
- issue2.errors.map((issues) => processError({ issues }, [...path55, ...issue2.path]));
1697
+ issue2.errors.map((issues) => processError({ issues }, [...path60, ...issue2.path]));
1698
1698
  } else if (issue2.code === "invalid_key") {
1699
- processError({ issues: issue2.issues }, [...path55, ...issue2.path]);
1699
+ processError({ issues: issue2.issues }, [...path60, ...issue2.path]);
1700
1700
  } else if (issue2.code === "invalid_element") {
1701
- processError({ issues: issue2.issues }, [...path55, ...issue2.path]);
1701
+ processError({ issues: issue2.issues }, [...path60, ...issue2.path]);
1702
1702
  } else {
1703
- const fullpath = [...path55, ...issue2.path];
1703
+ const fullpath = [...path60, ...issue2.path];
1704
1704
  if (fullpath.length === 0) {
1705
1705
  result.errors.push(mapper(issue2));
1706
1706
  continue;
@@ -1739,8 +1739,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
1739
1739
  }
1740
1740
  function toDotPath(_path) {
1741
1741
  const segs = [];
1742
- const path55 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1743
- for (const seg of path55) {
1742
+ const path60 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1743
+ for (const seg of path60) {
1744
1744
  if (typeof seg === "number")
1745
1745
  segs.push(`[${seg}]`);
1746
1746
  else if (typeof seg === "symbol")
@@ -11017,8 +11017,8 @@ var init_pt = __esm({
11017
11017
  case "not_multiple_of":
11018
11018
  return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
11019
11019
  case "unrecognized_keys": {
11020
- const plural2 = issue2.keys.length > 1 ? "s" : "";
11021
- return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`;
11020
+ const plural5 = issue2.keys.length > 1 ? "s" : "";
11021
+ return `Chave${plural5} inv\xE1lida${plural5}: ${joinValues(issue2.keys, ", ")}`;
11022
11022
  }
11023
11023
  case "invalid_key":
11024
11024
  return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`;
@@ -11168,8 +11168,8 @@ var init_pt_BR = __esm({
11168
11168
  case "not_multiple_of":
11169
11169
  return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
11170
11170
  case "unrecognized_keys": {
11171
- const plural2 = issue2.keys.length > 1 ? "s" : "";
11172
- return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`;
11171
+ const plural5 = issue2.keys.length > 1 ? "s" : "";
11172
+ return `Chave${plural5} inv\xE1lida${plural5}: ${joinValues(issue2.keys, ", ")}`;
11173
11173
  }
11174
11174
  case "invalid_key":
11175
11175
  return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`;
@@ -19772,13 +19772,13 @@ function resolveRef(ref, ctx) {
19772
19772
  if (!ref.startsWith("#")) {
19773
19773
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19774
19774
  }
19775
- const path55 = ref.slice(1).split("/").filter(Boolean);
19776
- if (path55.length === 0) {
19775
+ const path60 = ref.slice(1).split("/").filter(Boolean);
19776
+ if (path60.length === 0) {
19777
19777
  return ctx.rootSchema;
19778
19778
  }
19779
19779
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19780
- if (path55[0] === defsKey) {
19781
- const key = path55[1] === void 0 ? void 0 : decodeJSONPointerSegment(path55[1]);
19780
+ if (path60[0] === defsKey) {
19781
+ const key = path60[1] === void 0 ? void 0 : decodeJSONPointerSegment(path60[1]);
19782
19782
  if (!key || !ctx.defs[key]) {
19783
19783
  throw new Error(`Reference not found: ${ref}`);
19784
19784
  }
@@ -21113,7 +21113,7 @@ var init_vocabulary = __esm({
21113
21113
  });
21114
21114
 
21115
21115
  // ../packages/contract/dist/chat.js
21116
- var CHAT_DEFAULT_LIMITS, ACCOUNT_CONNECTION_ASSISTANT_WRITE_SCOPES, REPOSITORY_READ_OPERATIONS, REPOSITORY_READ_DEFAULT_BOUNDS, PROJECT_RESOURCE_READ_CAPABILITY;
21116
+ var CHAT_DEFAULT_LIMITS, ACCOUNT_CONNECTION_ASSISTANT_WRITE_SCOPES, REPOSITORY_READ_OPERATIONS, REPOSITORY_READ_DEFAULT_BOUNDS, PROJECT_RESOURCE_READ_CAPABILITY, PROJECT_RESOURCE_WRITE_CAPABILITY, PROJECT_RESOURCE_SYNC_CAPABILITY, PROJECT_RESOURCE_BRANCH_CAPABILITY, PROJECT_RESOURCE_CONFLICT_CAPABILITY;
21117
21117
  var init_chat = __esm({
21118
21118
  "../packages/contract/dist/chat.js"() {
21119
21119
  "use strict";
@@ -21169,6 +21169,10 @@ var init_chat = __esm({
21169
21169
  concurrentReadsPerScope: 4
21170
21170
  };
21171
21171
  PROJECT_RESOURCE_READ_CAPABILITY = "projectResourceReads";
21172
+ PROJECT_RESOURCE_WRITE_CAPABILITY = "projectResourceWrites";
21173
+ PROJECT_RESOURCE_SYNC_CAPABILITY = "projectResourceSync";
21174
+ PROJECT_RESOURCE_BRANCH_CAPABILITY = "projectResourceBranches";
21175
+ PROJECT_RESOURCE_CONFLICT_CAPABILITY = "projectResourceConflicts";
21172
21176
  }
21173
21177
  });
21174
21178
 
@@ -21392,8 +21396,8 @@ function accessModeToResourcePathPermission({ accessMode, isPrimary = false }) {
21392
21396
  return "rw";
21393
21397
  return accessMode === "read" ? "ro" : "rw";
21394
21398
  }
21395
- function formatResourcePathWithPermission({ path: path55, accessMode, isPrimary = false }) {
21396
- const trimmed = path55.trim();
21399
+ function formatResourcePathWithPermission({ path: path60, accessMode, isPrimary = false }) {
21400
+ const trimmed = path60.trim();
21397
21401
  if (!trimmed)
21398
21402
  return "";
21399
21403
  const permission = accessModeToResourcePathPermission({ accessMode, isPrimary });
@@ -21407,11 +21411,11 @@ function formatProjectResourcePathsFromManifest(projectResources) {
21407
21411
  if (!entry || typeof entry !== "object")
21408
21412
  continue;
21409
21413
  const record2 = entry;
21410
- const path55 = typeof record2.path === "string" ? record2.path.trim() : "";
21411
- if (!path55)
21414
+ const path60 = typeof record2.path === "string" ? record2.path.trim() : "";
21415
+ if (!path60)
21412
21416
  continue;
21413
21417
  paths.push(formatResourcePathWithPermission({
21414
- path: path55,
21418
+ path: path60,
21415
21419
  accessMode: typeof record2.accessMode === "string" ? record2.accessMode : null,
21416
21420
  isPrimary: record2.isPrimary === true
21417
21421
  }));
@@ -27409,13 +27413,13 @@ function createBackendClient() {
27409
27413
  const clientDevice = clientDeviceIdentity();
27410
27414
  async function request({
27411
27415
  method,
27412
- path: path55,
27416
+ path: path60,
27413
27417
  body,
27414
27418
  extraHeaders,
27415
27419
  rawBody,
27416
27420
  responseType = "json"
27417
27421
  }) {
27418
- const url2 = `${baseUrl}${path55.startsWith("/") ? path55 : `/${path55}`}`;
27422
+ const url2 = `${baseUrl}${path60.startsWith("/") ? path60 : `/${path60}`}`;
27419
27423
  const auth = resolveAuthHeaders({ baseUrl });
27420
27424
  if (auth.storedCredentialBackendUrl) {
27421
27425
  throw new CliError({
@@ -27447,9 +27451,9 @@ Start the Desktop/local backend or run \`ovld config set cloud <url>\`.
27447
27451
  }
27448
27452
  const payload = response.ok && responseType === "bytes" ? Buffer.from(await response.arrayBuffer()) : await readResponseJson2(response);
27449
27453
  if (!response.ok) {
27450
- const invalidProtocolSession = path55.startsWith("/api/protocol/") && payload !== null && typeof payload === "object" && "code" in payload && payload.code === "invalid_session";
27454
+ const invalidProtocolSession = path60.startsWith("/api/protocol/") && payload !== null && typeof payload === "object" && "code" in payload && payload.code === "invalid_session";
27451
27455
  if (response.status === 401 && auth.headers.Authorization && !invalidProtocolSession && !isExecutionRequestAlreadyLinkedPayload(payload)) {
27452
- const detail = errorMessageFromJson2(payload) ?? `Backend request failed: ${method} ${path55} (${response.status})`;
27456
+ const detail = errorMessageFromJson2(payload) ?? `Backend request failed: ${method} ${path60} (${response.status})`;
27453
27457
  throw new CliError({
27454
27458
  status: response.status,
27455
27459
  message: `${detail}
@@ -27457,7 +27461,7 @@ Start the Desktop/local backend or run \`ovld config set cloud <url>\`.
27457
27461
  });
27458
27462
  }
27459
27463
  throw new CliError({
27460
- message: errorMessageFromJson2(payload) ?? `Backend request failed: ${method} ${path55} (${response.status})`,
27464
+ message: errorMessageFromJson2(payload) ?? `Backend request failed: ${method} ${path60} (${response.status})`,
27461
27465
  payload,
27462
27466
  status: response.status
27463
27467
  });
@@ -27467,14 +27471,14 @@ Start the Desktop/local backend or run \`ovld config set cloud <url>\`.
27467
27471
  return {
27468
27472
  baseUrl,
27469
27473
  health: () => request({ method: "GET", path: "/api/health" }),
27470
- get: (path55) => request({ method: "GET", path: path55 }),
27471
- getBytes: (path55) => request({ method: "GET", path: path55, responseType: "bytes" }),
27472
- post: ({ path: path55, body }) => request({ method: "POST", path: path55, body }),
27473
- patch: ({ path: path55, body }) => request({ method: "PATCH", path: path55, body }),
27474
- delete: (path55) => request({ method: "DELETE", path: path55 }),
27475
- postRaw: ({ path: path55, body, contentType, filename }) => request({
27474
+ get: (path60) => request({ method: "GET", path: path60 }),
27475
+ getBytes: (path60) => request({ method: "GET", path: path60, responseType: "bytes" }),
27476
+ post: ({ path: path60, body }) => request({ method: "POST", path: path60, body }),
27477
+ patch: ({ path: path60, body }) => request({ method: "PATCH", path: path60, body }),
27478
+ delete: (path60) => request({ method: "DELETE", path: path60 }),
27479
+ postRaw: ({ path: path60, body, contentType, filename }) => request({
27476
27480
  method: "POST",
27477
- path: path55,
27481
+ path: path60,
27478
27482
  rawBody: body,
27479
27483
  extraHeaders: {
27480
27484
  "Content-Type": contentType || "application/octet-stream",
@@ -31801,11 +31805,11 @@ function createChannelClient({
31801
31805
  token
31802
31806
  }) {
31803
31807
  const root = `${baseUrl.replace(/\/+$/, "")}/api/agent-session-channels/v1`;
31804
- async function request(method, path55, body, timeoutMs) {
31808
+ async function request(method, path60, body, timeoutMs) {
31805
31809
  const controller = new AbortController();
31806
31810
  const timer = setTimeout(() => controller.abort(), timeoutMs);
31807
31811
  try {
31808
- const response = await fetch(`${root}${path55}`, {
31812
+ const response = await fetch(`${root}${path60}`, {
31809
31813
  method,
31810
31814
  // The credential travels here and only here: an Authorization header on a request the
31811
31815
  // CLI itself constructs. Not in the URL, which lands in access logs; not in the body,
@@ -31831,8 +31835,8 @@ function createChannelClient({
31831
31835
  }
31832
31836
  }
31833
31837
  return {
31834
- post: (path55, body, options) => request("POST", path55, body ?? {}, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS),
31835
- get: (path55, options) => request("GET", path55, void 0, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS)
31838
+ post: (path60, body, options) => request("POST", path60, body ?? {}, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS),
31839
+ get: (path60, options) => request("GET", path60, void 0, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS)
31836
31840
  };
31837
31841
  }
31838
31842
  var DEFAULT_TIMEOUT_MS;
@@ -31931,9 +31935,9 @@ function reduceUrl(rawUrl) {
31931
31935
  try {
31932
31936
  const url2 = new URL(raw);
31933
31937
  const hadQuery = url2.search !== "" || url2.hash !== "";
31934
- const path55 = url2.pathname === "/" ? "" : url2.pathname;
31938
+ const path60 = url2.pathname === "/" ? "" : url2.pathname;
31935
31939
  return {
31936
- display: safeText(`${url2.protocol}//${url2.host}${path55}`).text,
31940
+ display: safeText(`${url2.protocol}//${url2.host}${path60}`).text,
31937
31941
  host: url2.host || null,
31938
31942
  scheme: url2.protocol.replace(/:$/, ""),
31939
31943
  hadQuery
@@ -32103,17 +32107,17 @@ function describeRead({ input: input2, projectRoot }) {
32103
32107
  const record2 = input2 && typeof input2 === "object" ? input2 : {};
32104
32108
  const raw = typeof record2.file_path === "string" && record2.file_path || typeof record2.filePath === "string" && record2.filePath || typeof record2.path === "string" && record2.path || typeof record2.notebook_path === "string" && record2.notebook_path || // Antigravity `view_file`.
32105
32109
  typeof record2.AbsolutePath === "string" && record2.AbsolutePath || null;
32106
- const path55 = reducePath(raw, projectRoot);
32110
+ const path60 = reducePath(raw, projectRoot);
32107
32111
  const markers = [
32108
- path55?.outsideProject && "outside-project-directory",
32109
- path55?.nonAscii && "non-ascii-path"
32112
+ path60?.outsideProject && "outside-project-directory",
32113
+ path60?.nonAscii && "non-ascii-path"
32110
32114
  ];
32111
- if (path55 && /(^|\/)(\.env|\.npmrc|\.netrc|id_rsa|id_ed25519|credentials)(\.|$)/.test(path55.display)) {
32115
+ if (path60 && /(^|\/)(\.env|\.npmrc|\.netrc|id_rsa|id_ed25519|credentials)(\.|$)/.test(path60.display)) {
32112
32116
  markers.push("secret-adjacent");
32113
32117
  }
32114
32118
  return {
32115
32119
  action: "Read a file",
32116
- subject: path55?.display ?? null,
32120
+ subject: path60?.display ?? null,
32117
32121
  detail: null,
32118
32122
  riskMarkers: normalizeMarkers(markers)
32119
32123
  };
@@ -32282,21 +32286,21 @@ function isOverwrite(record2) {
32282
32286
  }
32283
32287
  function describeWrite({ input: input2, projectRoot }) {
32284
32288
  const record2 = input2 && typeof input2 === "object" ? input2 : {};
32285
- const path55 = reducePath(readPath(record2), projectRoot);
32289
+ const path60 = reducePath(readPath(record2), projectRoot);
32286
32290
  const overwrite = isOverwrite(record2);
32287
32291
  const bytes = byteLength(readContent(record2));
32288
32292
  const markers = [
32289
32293
  overwrite && "overwrites-existing",
32290
- path55?.outsideProject && "outside-project-directory",
32291
- path55?.nonAscii && "non-ascii-path"
32294
+ path60?.outsideProject && "outside-project-directory",
32295
+ path60?.nonAscii && "non-ascii-path"
32292
32296
  ];
32293
- if (path55 && /(^|\/)(\.env|\.npmrc|\.netrc|id_rsa|id_ed25519|credentials)(\.|$)/.test(path55.display)) {
32297
+ if (path60 && /(^|\/)(\.env|\.npmrc|\.netrc|id_rsa|id_ed25519|credentials)(\.|$)/.test(path60.display)) {
32294
32298
  markers.push("secret-adjacent");
32295
32299
  }
32296
32300
  const detail = bytes === null ? overwrite ? "replacing existing text" : null : `${bytes} byte${bytes === 1 ? "" : "s"}${overwrite ? ", replacing existing text" : ""}`;
32297
32301
  return {
32298
32302
  action: overwrite ? "Overwrite a file" : "Write a file",
32299
- subject: path55?.display ?? null,
32303
+ subject: path60?.display ?? null,
32300
32304
  detail,
32301
32305
  riskMarkers: normalizeMarkers(markers)
32302
32306
  };
@@ -32516,16 +32520,16 @@ function readPath2(source, dotted) {
32516
32520
  return current;
32517
32521
  }
32518
32522
  function firstString(source, paths) {
32519
- for (const path55 of paths ?? []) {
32520
- const value2 = readPath2(source, path55);
32523
+ for (const path60 of paths ?? []) {
32524
+ const value2 = readPath2(source, path60);
32521
32525
  if (typeof value2 === "string" && value2.trim() !== "")
32522
32526
  return value2.trim();
32523
32527
  }
32524
32528
  return null;
32525
32529
  }
32526
32530
  function firstLiteralString(source, paths) {
32527
- for (const path55 of paths ?? []) {
32528
- const value2 = readPath2(source, path55);
32531
+ for (const path60 of paths ?? []) {
32532
+ const value2 = readPath2(source, path60);
32529
32533
  if (typeof value2 === "string" && value2.length > 0)
32530
32534
  return value2;
32531
32535
  }
@@ -32677,14 +32681,14 @@ function normalizeNativeEvent({ codec: codec2, payload, nativeEventName: nativeE
32677
32681
  }
32678
32682
  }
32679
32683
  if (rule.outcomePath) {
32680
- const outcome = readOutcome(readPath2(payload, rule.outcomePath), rule.outcomeExitCodePrefix);
32681
- if (outcome)
32682
- sealedInput.outcome = outcome;
32684
+ const outcome2 = readOutcome(readPath2(payload, rule.outcomePath), rule.outcomeExitCodePrefix);
32685
+ if (outcome2)
32686
+ sealedInput.outcome = outcome2;
32683
32687
  }
32684
32688
  if (rule.outcomeErrorPath) {
32685
- const outcome = readErrorMessageOutcome(readPath2(payload, rule.outcomeErrorPath));
32686
- if (outcome)
32687
- sealedInput.outcome = outcome;
32689
+ const outcome2 = readErrorMessageOutcome(readPath2(payload, rule.outcomeErrorPath));
32690
+ if (outcome2)
32691
+ sealedInput.outcome = outcome2;
32688
32692
  }
32689
32693
  if (rule.successOnly && !sealedInput.outcome)
32690
32694
  sealedInput.outcome = "ok";
@@ -33408,10 +33412,10 @@ async function injectClaimedInput({
33408
33412
  });
33409
33413
  return { outcome: "failed", path: "codex-app-server-turn-start" };
33410
33414
  }
33411
- const path55 = codexAppServerInjectPath({ activeTurnId: tracker.activeTurnId });
33412
- let usedPath = path55;
33415
+ const path60 = codexAppServerInjectPath({ activeTurnId: tracker.activeTurnId });
33416
+ let usedPath = path60;
33413
33417
  try {
33414
- if (path55 === "codex-app-server-steer") {
33418
+ if (path60 === "codex-app-server-steer") {
33415
33419
  try {
33416
33420
  await rpc.request("turn/steer", {
33417
33421
  threadId,
@@ -33581,9 +33585,9 @@ async function runAgentSessionInbox({
33581
33585
  const scope = resolveAgentSessionScope({ agent, env });
33582
33586
  if (!scope) return emptyResult("Empty");
33583
33587
  const payload = payloadRaw === void 0 ? parseNativePayload(readBoundedStdin()) : parseNativePayload(payloadRaw);
33584
- const path55 = resolveInjectPath({ agent, payload });
33585
- if (path55 === "unsupported") return emptyResult("Unsupported");
33586
- if (path55 === "codex-app-server-steer" || path55 === "codex-app-server-turn-start") {
33588
+ const path60 = resolveInjectPath({ agent, payload });
33589
+ if (path60 === "unsupported") return emptyResult("Unsupported");
33590
+ if (path60 === "codex-app-server-steer" || path60 === "codex-app-server-turn-start") {
33587
33591
  return emptyResult("Unsupported");
33588
33592
  }
33589
33593
  const baseUrl = env.OVERLORD_BACKEND_URL?.trim();
@@ -33601,7 +33605,7 @@ async function runAgentSessionInbox({
33601
33605
  );
33602
33606
  if (!claimed.ok) return emptyResult("Empty");
33603
33607
  if (claimed.value.input) {
33604
- return await emitClaimedInput({ agent, path: path55, input: claimed.value.input, client });
33608
+ return await emitClaimedInput({ agent, path: path60, input: claimed.value.input, client });
33605
33609
  }
33606
33610
  const remaining = deadline - now();
33607
33611
  if (remaining <= 0) return emptyResult("Empty");
@@ -33610,11 +33614,11 @@ async function runAgentSessionInbox({
33610
33614
  }
33611
33615
  async function emitClaimedInput({
33612
33616
  agent,
33613
- path: path55,
33617
+ path: path60,
33614
33618
  input: input2,
33615
33619
  client
33616
33620
  }) {
33617
- if (path55 === "claude-mid-turn") {
33621
+ if (path60 === "claude-mid-turn") {
33618
33622
  const emitted = await client.post(`/inputs/${input2.id}/emitted`, {
33619
33623
  leaseId: input2.leaseId,
33620
33624
  deliveryOutcome: "delivered"
@@ -33629,7 +33633,7 @@ async function emitClaimedInput({
33629
33633
  inputId: input2.id
33630
33634
  };
33631
33635
  }
33632
- if (path55 === "claude-turn-boundary") {
33636
+ if (path60 === "claude-turn-boundary") {
33633
33637
  const emitted = await client.post(`/inputs/${input2.id}/emitted`, {
33634
33638
  leaseId: input2.leaseId,
33635
33639
  deliveryOutcome: "delivered"
@@ -33644,7 +33648,7 @@ async function emitClaimedInput({
33644
33648
  inputId: input2.id
33645
33649
  };
33646
33650
  }
33647
- if (path55 === "cursor-turn-boundary") {
33651
+ if (path60 === "cursor-turn-boundary") {
33648
33652
  const emitted = await client.post(`/inputs/${input2.id}/emitted`, {
33649
33653
  leaseId: input2.leaseId,
33650
33654
  deliveryOutcome: "queued_turn_boundary"
@@ -33658,7 +33662,7 @@ async function emitClaimedInput({
33658
33662
  inputId: input2.id
33659
33663
  };
33660
33664
  }
33661
- if (path55 === "codex-turn-boundary") {
33665
+ if (path60 === "codex-turn-boundary") {
33662
33666
  const emitted = await client.post(`/inputs/${input2.id}/emitted`, {
33663
33667
  leaseId: input2.leaseId,
33664
33668
  deliveryOutcome: "delivered"
@@ -33673,7 +33677,7 @@ async function emitClaimedInput({
33673
33677
  inputId: input2.id
33674
33678
  };
33675
33679
  }
33676
- if (path55 === "antigravity-turn-boundary" || path55 === "antigravity-next-invocation") {
33680
+ if (path60 === "antigravity-turn-boundary" || path60 === "antigravity-next-invocation") {
33677
33681
  const emitted = await client.post(`/inputs/${input2.id}/emitted`, {
33678
33682
  leaseId: input2.leaseId,
33679
33683
  deliveryOutcome: "delivered"
@@ -33683,12 +33687,12 @@ async function emitClaimedInput({
33683
33687
  return {
33684
33688
  report: "Delivered",
33685
33689
  exitCode: 0,
33686
- stdout: path55 === "antigravity-turn-boundary" ? encodeAntigravityStopContinue(input2.body) : encodeAntigravityInjectUserMessage(input2.body),
33690
+ stdout: path60 === "antigravity-turn-boundary" ? encodeAntigravityStopContinue(input2.body) : encodeAntigravityInjectUserMessage(input2.body),
33687
33691
  stderr: "",
33688
33692
  inputId: input2.id
33689
33693
  };
33690
33694
  }
33691
- if (path55 === "pi-mid-turn") {
33695
+ if (path60 === "pi-mid-turn") {
33692
33696
  return {
33693
33697
  report: "Empty",
33694
33698
  exitCode: 0,
@@ -33797,8 +33801,8 @@ var init_inbox = __esm({
33797
33801
 
33798
33802
  // ../packages/core/dist/service/agent-session/pure/decision.js
33799
33803
  function firstValue(source, paths) {
33800
- for (const path55 of paths ?? []) {
33801
- const value2 = readPath2(source, path55);
33804
+ for (const path60 of paths ?? []) {
33805
+ const value2 = readPath2(source, path60);
33802
33806
  if (value2 !== void 0 && value2 !== null)
33803
33807
  return value2;
33804
33808
  }
@@ -34353,7 +34357,7 @@ function captureChangeFromPayload({
34353
34357
  });
34354
34358
  const normalized = payloadFailure ? null : normalizeForAdapter({ codec: codec2, payload: payloadForNormalize });
34355
34359
  const directPaths = normalized?.kind === "file.edited" && Array.isArray(normalized.payload.paths) ? normalized.payload.paths.filter((value2) => typeof value2 === "string") : [];
34356
- const outcome = normalized?.payload.outcome;
34360
+ const outcome2 = normalized?.payload.outcome;
34357
34361
  const confidentlyNonMutating = normalized?.kind === "tool.completed" && (normalized.payload.tool === "read" || normalized.payload.tool === "search" || normalized.payload.tool === "fetch");
34358
34362
  return withActiveObjectiveSession({
34359
34363
  workingDirectory,
@@ -34386,10 +34390,10 @@ function captureChangeFromPayload({
34386
34390
  });
34387
34391
  return { recorded: false, reason: "native event is not a declared file edit" };
34388
34392
  }
34389
- if (outcome === "blocked") {
34393
+ if (outcome2 === "blocked") {
34390
34394
  return { recorded: false, reason: "native edit was blocked" };
34391
34395
  }
34392
- if (outcome === "error" || outcome === "cancelled") {
34396
+ if (outcome2 === "error" || outcome2 === "cancelled") {
34393
34397
  recordChangeLedgerHealth({
34394
34398
  workingDirectory,
34395
34399
  objectiveId: session.objectiveId,
@@ -34398,10 +34402,10 @@ function captureChangeFromPayload({
34398
34402
  });
34399
34403
  return {
34400
34404
  recorded: false,
34401
- reason: `native edit ${outcome === "error" ? "failed" : "was cancelled"}`
34405
+ reason: `native edit ${outcome2 === "error" ? "failed" : "was cancelled"}`
34402
34406
  };
34403
34407
  }
34404
- if (outcome !== "ok") {
34408
+ if (outcome2 !== "ok") {
34405
34409
  recordChangeLedgerHealth({
34406
34410
  workingDirectory,
34407
34411
  objectiveId: session.objectiveId,
@@ -35335,7 +35339,7 @@ async function importSessionHistory({
35335
35339
  if (!tree.rootId) return result;
35336
35340
  const seenTurns = /* @__PURE__ */ new Set();
35337
35341
  const done = /* @__PURE__ */ new Set();
35338
- const listed = /* @__PURE__ */ new Set();
35342
+ const listed2 = /* @__PURE__ */ new Set();
35339
35343
  for (; ; ) {
35340
35344
  const next = tree.threads().find((node2) => !done.has(node2.id));
35341
35345
  if (!next || done.size >= MAX_TREE_THREADS || shouldStop()) break;
@@ -35358,8 +35362,8 @@ async function importSessionHistory({
35358
35362
  } catch {
35359
35363
  result.failedThreads += 1;
35360
35364
  }
35361
- if (!listed.has(next.id)) {
35362
- listed.add(next.id);
35365
+ if (!listed2.has(next.id)) {
35366
+ listed2.add(next.id);
35363
35367
  try {
35364
35368
  const children = await rpc.request("thread/list", {
35365
35369
  parentThreadId: next.id,
@@ -35508,19 +35512,19 @@ var init_threads = __esm({
35508
35512
  const id = str(record2?.id);
35509
35513
  if (!record2 || !id) return null;
35510
35514
  const known = this.nodes.get(id);
35511
- const spawn8 = threadSpawnSource(record2);
35512
- const nickname = str(record2.agentNickname) ?? str(spawn8?.agent_nickname);
35513
- const role = str(record2.agentRole) ?? str(spawn8?.agent_role);
35515
+ const spawn9 = threadSpawnSource(record2);
35516
+ const nickname = str(record2.agentNickname) ?? str(spawn9?.agent_nickname);
35517
+ const role = str(record2.agentRole) ?? str(spawn9?.agent_role);
35514
35518
  if (known) {
35515
35519
  known.nickname ??= nickname;
35516
35520
  known.role ??= role;
35517
- known.agentPath ??= str(spawn8?.agent_path);
35521
+ known.agentPath ??= str(spawn9?.agent_path);
35518
35522
  return known;
35519
35523
  }
35520
- const parentThreadId = str(record2.parentThreadId) ?? str(spawn8?.parent_thread_id);
35524
+ const parentThreadId = str(record2.parentThreadId) ?? str(spawn9?.parent_thread_id);
35521
35525
  const forkedFromId = str(record2.forkedFromId);
35522
35526
  const sessionId = str(record2.sessionId);
35523
- const depthValue = typeof spawn8?.depth === "number" ? spawn8.depth : null;
35527
+ const depthValue = typeof spawn9?.depth === "number" ? spawn9.depth : null;
35524
35528
  const parent = this.get(parentThreadId);
35525
35529
  if (parent) {
35526
35530
  return this.admit({
@@ -35528,7 +35532,7 @@ var init_threads = __esm({
35528
35532
  relation: "subagent",
35529
35533
  parentId: parent.id,
35530
35534
  depth: depthValue ?? parent.depth + 1,
35531
- agentPath: str(spawn8?.agent_path),
35535
+ agentPath: str(spawn9?.agent_path),
35532
35536
  nickname,
35533
35537
  role
35534
35538
  });
@@ -35551,7 +35555,7 @@ var init_threads = __esm({
35551
35555
  relation: "subagent",
35552
35556
  parentId: this.root,
35553
35557
  depth: depthValue ?? 1,
35554
- agentPath: str(spawn8?.agent_path),
35558
+ agentPath: str(spawn9?.agent_path),
35555
35559
  nickname,
35556
35560
  role
35557
35561
  });
@@ -36004,8 +36008,8 @@ async function drainInputs({
36004
36008
  return delivered;
36005
36009
  }
36006
36010
  if (!claimed.value.input) return delivered;
36007
- const outcome = await injectClaimedInput({ rpc, client, tracker, input: claimed.value.input });
36008
- if (outcome.outcome === "delivered") delivered += 1;
36011
+ const outcome2 = await injectClaimedInput({ rpc, client, tracker, input: claimed.value.input });
36012
+ if (outcome2.outcome === "delivered") delivered += 1;
36009
36013
  }
36010
36014
  return delivered;
36011
36015
  }
@@ -36697,10 +36701,10 @@ async function reconcileState({
36697
36701
  }) {
36698
36702
  let posted = 0;
36699
36703
  let duplicates = 0;
36700
- for (const path55 of ["/permission", "/question"]) {
36704
+ for (const path60 of ["/permission", "/question"]) {
36701
36705
  let entries;
36702
36706
  try {
36703
- const response = await doFetch(`${controlPlaneBaseUrl(port)}${path55}`, {
36707
+ const response = await doFetch(`${controlPlaneBaseUrl(port)}${path60}`, {
36704
36708
  headers: authHeaders(password)
36705
36709
  });
36706
36710
  if (!response.ok) continue;
@@ -36710,7 +36714,7 @@ async function reconcileState({
36710
36714
  continue;
36711
36715
  }
36712
36716
  for (const entry of entries) {
36713
- if (path55 === "/permission") {
36717
+ if (path60 === "/permission") {
36714
36718
  await syncOpenCodePermission({
36715
36719
  client,
36716
36720
  frame: { event: "permission.updated", data: JSON.stringify(entry) },
@@ -38544,17 +38548,17 @@ var require_visit = __commonJS({
38544
38548
  visit2.BREAK = BREAK;
38545
38549
  visit2.SKIP = SKIP;
38546
38550
  visit2.REMOVE = REMOVE;
38547
- function visit_(key, node2, visitor, path55) {
38548
- const ctrl = callVisitor(key, node2, visitor, path55);
38551
+ function visit_(key, node2, visitor, path60) {
38552
+ const ctrl = callVisitor(key, node2, visitor, path60);
38549
38553
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
38550
- replaceNode(key, path55, ctrl);
38551
- return visit_(key, ctrl, visitor, path55);
38554
+ replaceNode(key, path60, ctrl);
38555
+ return visit_(key, ctrl, visitor, path60);
38552
38556
  }
38553
38557
  if (typeof ctrl !== "symbol") {
38554
38558
  if (identity.isCollection(node2)) {
38555
- path55 = Object.freeze(path55.concat(node2));
38559
+ path60 = Object.freeze(path60.concat(node2));
38556
38560
  for (let i = 0; i < node2.items.length; ++i) {
38557
- const ci = visit_(i, node2.items[i], visitor, path55);
38561
+ const ci = visit_(i, node2.items[i], visitor, path60);
38558
38562
  if (typeof ci === "number")
38559
38563
  i = ci - 1;
38560
38564
  else if (ci === BREAK)
@@ -38565,13 +38569,13 @@ var require_visit = __commonJS({
38565
38569
  }
38566
38570
  }
38567
38571
  } else if (identity.isPair(node2)) {
38568
- path55 = Object.freeze(path55.concat(node2));
38569
- const ck = visit_("key", node2.key, visitor, path55);
38572
+ path60 = Object.freeze(path60.concat(node2));
38573
+ const ck = visit_("key", node2.key, visitor, path60);
38570
38574
  if (ck === BREAK)
38571
38575
  return BREAK;
38572
38576
  else if (ck === REMOVE)
38573
38577
  node2.key = null;
38574
- const cv = visit_("value", node2.value, visitor, path55);
38578
+ const cv = visit_("value", node2.value, visitor, path60);
38575
38579
  if (cv === BREAK)
38576
38580
  return BREAK;
38577
38581
  else if (cv === REMOVE)
@@ -38592,17 +38596,17 @@ var require_visit = __commonJS({
38592
38596
  visitAsync.BREAK = BREAK;
38593
38597
  visitAsync.SKIP = SKIP;
38594
38598
  visitAsync.REMOVE = REMOVE;
38595
- async function visitAsync_(key, node2, visitor, path55) {
38596
- const ctrl = await callVisitor(key, node2, visitor, path55);
38599
+ async function visitAsync_(key, node2, visitor, path60) {
38600
+ const ctrl = await callVisitor(key, node2, visitor, path60);
38597
38601
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
38598
- replaceNode(key, path55, ctrl);
38599
- return visitAsync_(key, ctrl, visitor, path55);
38602
+ replaceNode(key, path60, ctrl);
38603
+ return visitAsync_(key, ctrl, visitor, path60);
38600
38604
  }
38601
38605
  if (typeof ctrl !== "symbol") {
38602
38606
  if (identity.isCollection(node2)) {
38603
- path55 = Object.freeze(path55.concat(node2));
38607
+ path60 = Object.freeze(path60.concat(node2));
38604
38608
  for (let i = 0; i < node2.items.length; ++i) {
38605
- const ci = await visitAsync_(i, node2.items[i], visitor, path55);
38609
+ const ci = await visitAsync_(i, node2.items[i], visitor, path60);
38606
38610
  if (typeof ci === "number")
38607
38611
  i = ci - 1;
38608
38612
  else if (ci === BREAK)
@@ -38613,13 +38617,13 @@ var require_visit = __commonJS({
38613
38617
  }
38614
38618
  }
38615
38619
  } else if (identity.isPair(node2)) {
38616
- path55 = Object.freeze(path55.concat(node2));
38617
- const ck = await visitAsync_("key", node2.key, visitor, path55);
38620
+ path60 = Object.freeze(path60.concat(node2));
38621
+ const ck = await visitAsync_("key", node2.key, visitor, path60);
38618
38622
  if (ck === BREAK)
38619
38623
  return BREAK;
38620
38624
  else if (ck === REMOVE)
38621
38625
  node2.key = null;
38622
- const cv = await visitAsync_("value", node2.value, visitor, path55);
38626
+ const cv = await visitAsync_("value", node2.value, visitor, path60);
38623
38627
  if (cv === BREAK)
38624
38628
  return BREAK;
38625
38629
  else if (cv === REMOVE)
@@ -38646,23 +38650,23 @@ var require_visit = __commonJS({
38646
38650
  }
38647
38651
  return visitor;
38648
38652
  }
38649
- function callVisitor(key, node2, visitor, path55) {
38653
+ function callVisitor(key, node2, visitor, path60) {
38650
38654
  if (typeof visitor === "function")
38651
- return visitor(key, node2, path55);
38655
+ return visitor(key, node2, path60);
38652
38656
  if (identity.isMap(node2))
38653
- return visitor.Map?.(key, node2, path55);
38657
+ return visitor.Map?.(key, node2, path60);
38654
38658
  if (identity.isSeq(node2))
38655
- return visitor.Seq?.(key, node2, path55);
38659
+ return visitor.Seq?.(key, node2, path60);
38656
38660
  if (identity.isPair(node2))
38657
- return visitor.Pair?.(key, node2, path55);
38661
+ return visitor.Pair?.(key, node2, path60);
38658
38662
  if (identity.isScalar(node2))
38659
- return visitor.Scalar?.(key, node2, path55);
38663
+ return visitor.Scalar?.(key, node2, path60);
38660
38664
  if (identity.isAlias(node2))
38661
- return visitor.Alias?.(key, node2, path55);
38665
+ return visitor.Alias?.(key, node2, path60);
38662
38666
  return void 0;
38663
38667
  }
38664
- function replaceNode(key, path55, node2) {
38665
- const parent = path55[path55.length - 1];
38668
+ function replaceNode(key, path60, node2) {
38669
+ const parent = path60[path60.length - 1];
38666
38670
  if (identity.isCollection(parent)) {
38667
38671
  parent.items[key] = node2;
38668
38672
  } else if (identity.isPair(parent)) {
@@ -39272,10 +39276,10 @@ var require_Collection = __commonJS({
39272
39276
  var createNode = require_createNode();
39273
39277
  var identity = require_identity();
39274
39278
  var Node = require_Node();
39275
- function collectionFromPath(schema, path55, value2) {
39279
+ function collectionFromPath(schema, path60, value2) {
39276
39280
  let v = value2;
39277
- for (let i = path55.length - 1; i >= 0; --i) {
39278
- const k = path55[i];
39281
+ for (let i = path60.length - 1; i >= 0; --i) {
39282
+ const k = path60[i];
39279
39283
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
39280
39284
  const a = [];
39281
39285
  a[k] = v;
@@ -39294,7 +39298,7 @@ var require_Collection = __commonJS({
39294
39298
  sourceObjects: /* @__PURE__ */ new Map()
39295
39299
  });
39296
39300
  }
39297
- var isEmptyPath = (path55) => path55 == null || typeof path55 === "object" && !!path55[Symbol.iterator]().next().done;
39301
+ var isEmptyPath = (path60) => path60 == null || typeof path60 === "object" && !!path60[Symbol.iterator]().next().done;
39298
39302
  var Collection = class extends Node.NodeBase {
39299
39303
  constructor(type, schema) {
39300
39304
  super(type);
@@ -39324,11 +39328,11 @@ var require_Collection = __commonJS({
39324
39328
  * be a Pair instance or a `{ key, value }` object, which may not have a key
39325
39329
  * that already exists in the map.
39326
39330
  */
39327
- addIn(path55, value2) {
39328
- if (isEmptyPath(path55))
39331
+ addIn(path60, value2) {
39332
+ if (isEmptyPath(path60))
39329
39333
  this.add(value2);
39330
39334
  else {
39331
- const [key, ...rest] = path55;
39335
+ const [key, ...rest] = path60;
39332
39336
  const node2 = this.get(key, true);
39333
39337
  if (identity.isCollection(node2))
39334
39338
  node2.addIn(rest, value2);
@@ -39342,8 +39346,8 @@ var require_Collection = __commonJS({
39342
39346
  * Removes a value from the collection.
39343
39347
  * @returns `true` if the item was found and removed.
39344
39348
  */
39345
- deleteIn(path55) {
39346
- const [key, ...rest] = path55;
39349
+ deleteIn(path60) {
39350
+ const [key, ...rest] = path60;
39347
39351
  if (rest.length === 0)
39348
39352
  return this.delete(key);
39349
39353
  const node2 = this.get(key, true);
@@ -39357,8 +39361,8 @@ var require_Collection = __commonJS({
39357
39361
  * scalar values from their surrounding node; to disable set `keepScalar` to
39358
39362
  * `true` (collections are always returned intact).
39359
39363
  */
39360
- getIn(path55, keepScalar) {
39361
- const [key, ...rest] = path55;
39364
+ getIn(path60, keepScalar) {
39365
+ const [key, ...rest] = path60;
39362
39366
  const node2 = this.get(key, true);
39363
39367
  if (rest.length === 0)
39364
39368
  return !keepScalar && identity.isScalar(node2) ? node2.value : node2;
@@ -39376,8 +39380,8 @@ var require_Collection = __commonJS({
39376
39380
  /**
39377
39381
  * Checks if the collection includes a value with the key `key`.
39378
39382
  */
39379
- hasIn(path55) {
39380
- const [key, ...rest] = path55;
39383
+ hasIn(path60) {
39384
+ const [key, ...rest] = path60;
39381
39385
  if (rest.length === 0)
39382
39386
  return this.has(key);
39383
39387
  const node2 = this.get(key, true);
@@ -39387,8 +39391,8 @@ var require_Collection = __commonJS({
39387
39391
  * Sets a value in this collection. For `!!set`, `value` needs to be a
39388
39392
  * boolean to add/remove the item from the set.
39389
39393
  */
39390
- setIn(path55, value2) {
39391
- const [key, ...rest] = path55;
39394
+ setIn(path60, value2) {
39395
+ const [key, ...rest] = path60;
39392
39396
  if (rest.length === 0) {
39393
39397
  this.set(key, value2);
39394
39398
  } else {
@@ -41903,9 +41907,9 @@ var require_Document = __commonJS({
41903
41907
  this.contents.add(value2);
41904
41908
  }
41905
41909
  /** Adds a value to the document. */
41906
- addIn(path55, value2) {
41910
+ addIn(path60, value2) {
41907
41911
  if (assertCollection(this.contents))
41908
- this.contents.addIn(path55, value2);
41912
+ this.contents.addIn(path60, value2);
41909
41913
  }
41910
41914
  /**
41911
41915
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -41980,14 +41984,14 @@ var require_Document = __commonJS({
41980
41984
  * Removes a value from the document.
41981
41985
  * @returns `true` if the item was found and removed.
41982
41986
  */
41983
- deleteIn(path55) {
41984
- if (Collection.isEmptyPath(path55)) {
41987
+ deleteIn(path60) {
41988
+ if (Collection.isEmptyPath(path60)) {
41985
41989
  if (this.contents == null)
41986
41990
  return false;
41987
41991
  this.contents = null;
41988
41992
  return true;
41989
41993
  }
41990
- return assertCollection(this.contents) ? this.contents.deleteIn(path55) : false;
41994
+ return assertCollection(this.contents) ? this.contents.deleteIn(path60) : false;
41991
41995
  }
41992
41996
  /**
41993
41997
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -42002,10 +42006,10 @@ var require_Document = __commonJS({
42002
42006
  * scalar values from their surrounding node; to disable set `keepScalar` to
42003
42007
  * `true` (collections are always returned intact).
42004
42008
  */
42005
- getIn(path55, keepScalar) {
42006
- if (Collection.isEmptyPath(path55))
42009
+ getIn(path60, keepScalar) {
42010
+ if (Collection.isEmptyPath(path60))
42007
42011
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
42008
- return identity.isCollection(this.contents) ? this.contents.getIn(path55, keepScalar) : void 0;
42012
+ return identity.isCollection(this.contents) ? this.contents.getIn(path60, keepScalar) : void 0;
42009
42013
  }
42010
42014
  /**
42011
42015
  * Checks if the document includes a value with the key `key`.
@@ -42016,10 +42020,10 @@ var require_Document = __commonJS({
42016
42020
  /**
42017
42021
  * Checks if the document includes a value at `path`.
42018
42022
  */
42019
- hasIn(path55) {
42020
- if (Collection.isEmptyPath(path55))
42023
+ hasIn(path60) {
42024
+ if (Collection.isEmptyPath(path60))
42021
42025
  return this.contents !== void 0;
42022
- return identity.isCollection(this.contents) ? this.contents.hasIn(path55) : false;
42026
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path60) : false;
42023
42027
  }
42024
42028
  /**
42025
42029
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -42036,13 +42040,13 @@ var require_Document = __commonJS({
42036
42040
  * Sets a value in this document. For `!!set`, `value` needs to be a
42037
42041
  * boolean to add/remove the item from the set.
42038
42042
  */
42039
- setIn(path55, value2) {
42040
- if (Collection.isEmptyPath(path55)) {
42043
+ setIn(path60, value2) {
42044
+ if (Collection.isEmptyPath(path60)) {
42041
42045
  this.contents = value2;
42042
42046
  } else if (this.contents == null) {
42043
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path55), value2);
42047
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path60), value2);
42044
42048
  } else if (assertCollection(this.contents)) {
42045
- this.contents.setIn(path55, value2);
42049
+ this.contents.setIn(path60, value2);
42046
42050
  }
42047
42051
  }
42048
42052
  /**
@@ -43259,8 +43263,8 @@ var require_resolve_flow_scalar = __commonJS({
43259
43263
  };
43260
43264
  function parseCharCode(source, offset, length, onError) {
43261
43265
  const cc = source.substr(offset, length);
43262
- const ok2 = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
43263
- const code = ok2 ? parseInt(cc, 16) : NaN;
43266
+ const ok3 = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
43267
+ const code = ok3 ? parseInt(cc, 16) : NaN;
43264
43268
  try {
43265
43269
  return String.fromCodePoint(code);
43266
43270
  } catch {
@@ -44002,9 +44006,9 @@ var require_cst_visit = __commonJS({
44002
44006
  visit2.BREAK = BREAK;
44003
44007
  visit2.SKIP = SKIP;
44004
44008
  visit2.REMOVE = REMOVE;
44005
- visit2.itemAtPath = (cst, path55) => {
44009
+ visit2.itemAtPath = (cst, path60) => {
44006
44010
  let item = cst;
44007
- for (const [field, index] of path55) {
44011
+ for (const [field, index] of path60) {
44008
44012
  const tok = item?.[field];
44009
44013
  if (tok && "items" in tok) {
44010
44014
  item = tok.items[index];
@@ -44013,23 +44017,23 @@ var require_cst_visit = __commonJS({
44013
44017
  }
44014
44018
  return item;
44015
44019
  };
44016
- visit2.parentCollection = (cst, path55) => {
44017
- const parent = visit2.itemAtPath(cst, path55.slice(0, -1));
44018
- const field = path55[path55.length - 1][0];
44020
+ visit2.parentCollection = (cst, path60) => {
44021
+ const parent = visit2.itemAtPath(cst, path60.slice(0, -1));
44022
+ const field = path60[path60.length - 1][0];
44019
44023
  const coll = parent?.[field];
44020
44024
  if (coll && "items" in coll)
44021
44025
  return coll;
44022
44026
  throw new Error("Parent collection not found");
44023
44027
  };
44024
- function _visit(path55, item, visitor) {
44025
- let ctrl = visitor(item, path55);
44028
+ function _visit(path60, item, visitor) {
44029
+ let ctrl = visitor(item, path60);
44026
44030
  if (typeof ctrl === "symbol")
44027
44031
  return ctrl;
44028
44032
  for (const field of ["key", "value"]) {
44029
44033
  const token = item[field];
44030
44034
  if (token && "items" in token) {
44031
44035
  for (let i = 0; i < token.items.length; ++i) {
44032
- const ci = _visit(Object.freeze(path55.concat([[field, i]])), token.items[i], visitor);
44036
+ const ci = _visit(Object.freeze(path60.concat([[field, i]])), token.items[i], visitor);
44033
44037
  if (typeof ci === "number")
44034
44038
  i = ci - 1;
44035
44039
  else if (ci === BREAK)
@@ -44040,10 +44044,10 @@ var require_cst_visit = __commonJS({
44040
44044
  }
44041
44045
  }
44042
44046
  if (typeof ctrl === "function" && field === "key")
44043
- ctrl = ctrl(item, path55);
44047
+ ctrl = ctrl(item, path60);
44044
44048
  }
44045
44049
  }
44046
- return typeof ctrl === "function" ? ctrl(item, path55) : ctrl;
44050
+ return typeof ctrl === "function" ? ctrl(item, path60) : ctrl;
44047
44051
  }
44048
44052
  exports.visit = visit2;
44049
44053
  }
@@ -46922,7 +46926,7 @@ function runConversationOperation({ socket, operationId, text, idleBudgetMs, pre
46922
46926
  timers.push(timer);
46923
46927
  return timer;
46924
46928
  };
46925
- const finish = (outcome) => {
46929
+ const finish = (outcome2) => {
46926
46930
  if (settled)
46927
46931
  return;
46928
46932
  settled = true;
@@ -46931,7 +46935,7 @@ function runConversationOperation({ socket, operationId, text, idleBudgetMs, pre
46931
46935
  socket.close();
46932
46936
  } catch {
46933
46937
  }
46934
- resolve(outcome);
46938
+ resolve(outcome2);
46935
46939
  };
46936
46940
  const abort = (message) => {
46937
46941
  if (settled)
@@ -47188,10 +47192,10 @@ async function readLatchHostIdentity({ sharedRootId, sourceDirectory } = {}) {
47188
47192
  if (matches.length !== 1)
47189
47193
  return null;
47190
47194
  const [root] = matches;
47191
- const path55 = await realpath(sourceDirectory);
47192
- if (root.path !== path55 || typeof root.deviceId !== "string" || !Number.isSafeInteger(root.grantRevision) || root.grantRevision < 1)
47195
+ const path60 = await realpath(sourceDirectory);
47196
+ if (root.path !== path60 || typeof root.deviceId !== "string" || !Number.isSafeInteger(root.grantRevision) || root.grantRevision < 1)
47193
47197
  return null;
47194
- const directory = await stat(path55, { bigint: true });
47198
+ const directory = await stat(path60, { bigint: true });
47195
47199
  const identity = root.identity;
47196
47200
  if (!directory.isDirectory() || !Number.isSafeInteger(identity?.device) || !Number.isSafeInteger(identity?.inode) || directory.dev !== BigInt(identity.device) || directory.ino !== BigInt(identity.inode))
47197
47201
  return null;
@@ -47882,13 +47886,13 @@ var init_worktree_git = __esm({
47882
47886
 
47883
47887
  // ../packages/core/dist/service/local-target/branch-actions-git.js
47884
47888
  function resolveActionCheckout(input2) {
47885
- const path55 = resolveBranchCheckoutPath({
47889
+ const path60 = resolveBranchCheckoutPath({
47886
47890
  repoPath: input2.primaryRepoPath,
47887
47891
  branchName: input2.branchName,
47888
47892
  worktreePathHint: input2.worktreePath
47889
47893
  });
47890
- if (path55)
47891
- return { ok: true, path: path55 };
47894
+ if (path60)
47895
+ return { ok: true, path: path60 };
47892
47896
  return {
47893
47897
  ok: false,
47894
47898
  code: "BRANCH_NO_WORKTREE",
@@ -48344,8 +48348,8 @@ async function inspectRepositoryRoot(repoPath, deadline) {
48344
48348
  message: "The resource path is not a directory."
48345
48349
  };
48346
48350
  }
48347
- const inside = await gitLine(realRoot, ["rev-parse", "--is-inside-work-tree"], deadline);
48348
- if (inside !== "true") {
48351
+ const inside3 = await gitLine(realRoot, ["rev-parse", "--is-inside-work-tree"], deadline);
48352
+ if (inside3 !== "true") {
48349
48353
  return {
48350
48354
  ok: true,
48351
48355
  realRoot,
@@ -48757,7 +48761,7 @@ var init_repository_read_git = __esm({
48757
48761
  });
48758
48762
 
48759
48763
  // ../packages/core/dist/service/local-target/current-diff-git.js
48760
- function currentDiffArgs({ scope, base = "HEAD", pathspecs = [] }) {
48764
+ function currentDiffArgs({ scope, base = "HEAD", pathspecs: pathspecs2 = [] }) {
48761
48765
  const args = [
48762
48766
  "diff",
48763
48767
  "--no-ext-diff",
@@ -48770,7 +48774,7 @@ function currentDiffArgs({ scope, base = "HEAD", pathspecs = [] }) {
48770
48774
  args.push("--cached", base);
48771
48775
  else if (scope === "all")
48772
48776
  args.push(base);
48773
- args.push("--", ...pathspecs.length > 0 ? pathspecs.map((p) => `:(literal)${p}`) : ["."]);
48777
+ args.push("--", ...pathspecs2.length > 0 ? pathspecs2.map((p) => `:(literal)${p}`) : ["."]);
48774
48778
  return args;
48775
48779
  }
48776
48780
  function sectionPaths(section) {
@@ -48845,7 +48849,7 @@ async function readCurrentDiffGit(input2, signal) {
48845
48849
  data: null
48846
48850
  };
48847
48851
  }
48848
- const pathspecs = [];
48852
+ const pathspecs2 = [];
48849
48853
  for (const entry of requested) {
48850
48854
  const checked = normalizeRepositoryRelativePath(entry);
48851
48855
  if (!checked.ok) {
@@ -48857,7 +48861,7 @@ async function readCurrentDiffGit(input2, signal) {
48857
48861
  data: null
48858
48862
  };
48859
48863
  }
48860
- pathspecs.push(checked.relativePath || ".");
48864
+ pathspecs2.push(checked.relativePath || ".");
48861
48865
  }
48862
48866
  let against = "HEAD";
48863
48867
  if (scope !== "unstaged" && root.head === null) {
@@ -48870,7 +48874,7 @@ async function readCurrentDiffGit(input2, signal) {
48870
48874
  const maxBytes = clampBound(input2.maxBytes, REPOSITORY_READ_TARGET_BOUNDS.diffBytes);
48871
48875
  const run = await runInspectionGit({
48872
48876
  cwd: root.realRoot,
48873
- args: currentDiffArgs({ scope, base: against, pathspecs }),
48877
+ args: currentDiffArgs({ scope, base: against, pathspecs: pathspecs2 }),
48874
48878
  timeoutMs: deadline.remaining(),
48875
48879
  maxBytes,
48876
48880
  signal,
@@ -48968,12 +48972,1993 @@ var init_doctor_checks = __esm({
48968
48972
  }
48969
48973
  });
48970
48974
 
48975
+ // ../packages/core/dist/service/local-target/project-history-git.js
48976
+ import { homedir as homedir2 } from "node:os";
48977
+ import path41 from "node:path";
48978
+ function isSafeRefName(ref) {
48979
+ return /^[A-Za-z0-9][A-Za-z0-9._/-]{0,254}$/.test(ref) && !ref.includes("..") && !ref.includes("//") && !ref.endsWith("/") && !ref.endsWith(".lock");
48980
+ }
48981
+ function isCommitId(value2) {
48982
+ return /^[0-9a-f]{7,64}$/.test(value2);
48983
+ }
48984
+ function ok(root, data, truncated = false) {
48985
+ return {
48986
+ outcome: "ok",
48987
+ head: root.head,
48988
+ branch: root.branch,
48989
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
48990
+ truncated,
48991
+ data
48992
+ };
48993
+ }
48994
+ function outcome(root, kind, message) {
48995
+ return {
48996
+ outcome: kind,
48997
+ head: root.head,
48998
+ branch: root.branch,
48999
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
49000
+ truncated: false,
49001
+ message,
49002
+ data: null
49003
+ };
49004
+ }
49005
+ async function exactRoot(repoPath, deadline) {
49006
+ const root = await inspectRepositoryRoot(repoPath, deadline);
49007
+ if (!root.ok)
49008
+ return root;
49009
+ if (!root.isGitRepository || root.prefix !== "") {
49010
+ return {
49011
+ ok: false,
49012
+ code: "NOT_GIT_REPOSITORY",
49013
+ message: "The resource is not a Git checkout."
49014
+ };
49015
+ }
49016
+ return root;
49017
+ }
49018
+ async function git(root, args, deadline, maxBytes) {
49019
+ return runInspectionGit({
49020
+ cwd: root.realRoot,
49021
+ args,
49022
+ timeoutMs: deadline.remaining(),
49023
+ maxBytes,
49024
+ signal: deadline.signal,
49025
+ filterArgs: root.filterArgs
49026
+ });
49027
+ }
49028
+ function failed(message) {
49029
+ return { ok: false, code: "GIT_COMMAND_FAILED", message };
49030
+ }
49031
+ function parseDecorations(decorations) {
49032
+ const refs = [];
49033
+ for (const raw of decorations.split(", ")) {
49034
+ const item = raw.trim();
49035
+ if (!item)
49036
+ continue;
49037
+ if (item === "HEAD") {
49038
+ refs.push({ name: "HEAD", kind: "head" });
49039
+ } else if (item.startsWith("HEAD -> ")) {
49040
+ refs.push({ name: item.slice(8).replace(/^refs\/heads\//, ""), kind: "head" });
49041
+ } else if (item.startsWith("tag: ")) {
49042
+ refs.push({ name: item.slice(5).replace(/^refs\/tags\//, ""), kind: "tag" });
49043
+ } else if (item.startsWith("refs/heads/")) {
49044
+ refs.push({ name: item.slice(11), kind: "branch" });
49045
+ } else if (item.startsWith("refs/remotes/")) {
49046
+ const name = item.slice(13);
49047
+ if (!name.endsWith("/HEAD"))
49048
+ refs.push({ name, kind: "remote" });
49049
+ } else if (item.startsWith("refs/tags/")) {
49050
+ refs.push({ name: item.slice(10), kind: "tag" });
49051
+ }
49052
+ }
49053
+ return refs;
49054
+ }
49055
+ function parseSummary(fields) {
49056
+ const [sha, parents, authorName, authoredAt, subject, decorations] = fields;
49057
+ if (!sha || !/^[0-9a-f]{7,64}$/.test(sha))
49058
+ return null;
49059
+ return {
49060
+ sha,
49061
+ parents: parents ? parents.split(" ").filter(Boolean) : [],
49062
+ authorName: authorName ?? "",
49063
+ authoredAt: authoredAt ?? "",
49064
+ subject: subject ?? "",
49065
+ refs: parseDecorations(decorations ?? "")
49066
+ };
49067
+ }
49068
+ function parseCommitLog(output2) {
49069
+ const commits = [];
49070
+ for (const record2 of output2.split(RECORD)) {
49071
+ const summary = parseSummary(record2.replace(/^\n/, "").split(FIELD));
49072
+ if (summary)
49073
+ commits.push(summary);
49074
+ }
49075
+ return commits;
49076
+ }
49077
+ async function readCommitLogGit(input2, signal) {
49078
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
49079
+ const root = await exactRoot(input2.repoPath, deadline);
49080
+ if (!root.ok)
49081
+ return root;
49082
+ const ref = input2.ref ?? null;
49083
+ if (ref !== null && !isSafeRefName(ref))
49084
+ return outcome(root, "denied", "Unsupported ref name.");
49085
+ const offset = Math.max(0, Math.min(9999, Math.floor(input2.offset ?? 0)));
49086
+ if (ref === null && root.head === null) {
49087
+ return ok(root, { ref, commits: [], nextOffset: null });
49088
+ }
49089
+ const run = await git(root, [
49090
+ "log",
49091
+ "--no-color",
49092
+ "--decorate=full",
49093
+ `--format=${SUMMARY_FORMAT}%x1e`,
49094
+ `--max-count=${COMMIT_LOG_PAGE_SIZE + 1}`,
49095
+ `--skip=${offset}`,
49096
+ "--end-of-options",
49097
+ ref ?? "HEAD",
49098
+ "--"
49099
+ ], deadline, LOG_OUTPUT_BYTES);
49100
+ if (run.timedOut || run.aborted)
49101
+ return outcome(root, "timeout", "The read timed out on the target.");
49102
+ if (run.exitCode !== 0 && !run.truncated) {
49103
+ return ref === null ? failed("git log failed on the target.") : outcome(root, "not_found", "That branch no longer exists.");
49104
+ }
49105
+ let commits = parseCommitLog(run.stdout.toString("utf8"));
49106
+ if (run.truncated)
49107
+ commits = commits.slice(0, -1);
49108
+ const more = commits.length > COMMIT_LOG_PAGE_SIZE || run.truncated;
49109
+ commits = commits.slice(0, COMMIT_LOG_PAGE_SIZE);
49110
+ const nextOffset = more && offset + commits.length <= 9999 ? offset + commits.length : null;
49111
+ return ok(root, { ref, commits, nextOffset }, run.truncated);
49112
+ }
49113
+ function parseCommitFiles(numstat, nameStatus) {
49114
+ const statuses = /* @__PURE__ */ new Map();
49115
+ const parts = nameStatus.split("\0");
49116
+ for (let i = 0; i + 1 < parts.length; i += 2) {
49117
+ const status = parts[i];
49118
+ const file2 = parts[i + 1];
49119
+ if (status && file2)
49120
+ statuses.set(file2, status.charAt(0));
49121
+ }
49122
+ const files = [];
49123
+ for (const entry of numstat.split("\0")) {
49124
+ const match = /^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry);
49125
+ if (!match)
49126
+ continue;
49127
+ const file2 = match[3];
49128
+ files.push({
49129
+ path: file2,
49130
+ status: statuses.get(file2) ?? "M",
49131
+ additions: match[1] === "-" ? null : Number(match[1]),
49132
+ deletions: match[2] === "-" ? null : Number(match[2])
49133
+ });
49134
+ }
49135
+ return files;
49136
+ }
49137
+ async function readCommitGit(input2, signal) {
49138
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
49139
+ const root = await exactRoot(input2.repoPath, deadline);
49140
+ if (!root.ok)
49141
+ return root;
49142
+ if (!isCommitId(input2.commit))
49143
+ return outcome(root, "denied", "Unsupported commit ID.");
49144
+ const meta3 = await git(root, [
49145
+ "show",
49146
+ "-s",
49147
+ "--no-color",
49148
+ "--decorate=full",
49149
+ `--format=${SUMMARY_FORMAT}%x1f%b`,
49150
+ "--end-of-options",
49151
+ `${input2.commit}^{commit}`,
49152
+ "--"
49153
+ ], deadline, 64 * 1024);
49154
+ if (meta3.timedOut || meta3.aborted)
49155
+ return outcome(root, "timeout", "The read timed out on the target.");
49156
+ if (meta3.exitCode !== 0)
49157
+ return outcome(root, "not_found", "That commit is not in this repository.");
49158
+ const fields = meta3.stdout.toString("utf8").replace(/\n$/, "").split(FIELD);
49159
+ const commit = parseSummary(fields);
49160
+ if (!commit)
49161
+ return failed("Could not read the commit.");
49162
+ const body = fields.slice(6).join(FIELD).trimEnd();
49163
+ let base = commit.parents[0];
49164
+ if (!base) {
49165
+ const tree = await git(root, ["hash-object", "-t", "tree", "--stdin"], deadline, 256);
49166
+ base = tree.exitCode === 0 ? tree.stdout.toString("utf8").trim() : void 0;
49167
+ }
49168
+ if (!base)
49169
+ return failed("Could not resolve the diff base.");
49170
+ const range = ["--end-of-options", base, commit.sha, "--"];
49171
+ const common = [
49172
+ "--no-ext-diff",
49173
+ "--no-textconv",
49174
+ "--no-color",
49175
+ "--ignore-submodules=all",
49176
+ "--no-renames"
49177
+ ];
49178
+ const [numstat, nameStatus, patch] = await Promise.all([
49179
+ git(root, ["diff", ...common, "--numstat", "-z", ...range], deadline, LIST_OUTPUT_BYTES),
49180
+ git(root, ["diff", ...common, "--name-status", "-z", ...range], deadline, LIST_OUTPUT_BYTES),
49181
+ git(root, ["diff", ...common, ...range], deadline, REPOSITORY_READ_TARGET_BOUNDS.diffBytes)
49182
+ ]);
49183
+ for (const run of [numstat, nameStatus, patch]) {
49184
+ if (run.timedOut || run.aborted)
49185
+ return outcome(root, "timeout", "The read timed out on the target.");
49186
+ if (run.exitCode !== 0 && !run.truncated)
49187
+ return failed("git diff failed on the target.");
49188
+ }
49189
+ const allFiles = parseCommitFiles(numstat.stdout.toString("utf8"), nameStatus.stdout.toString("utf8"));
49190
+ const files = allFiles.slice(0, COMMIT_FILES_LIMIT);
49191
+ const filtered = withholdSensitiveDiffSections(patch.stdout.toString("utf8"));
49192
+ return ok(root, { commit, body, files, diff: filtered.diff, excludedPaths: filtered.excludedPaths }, patch.truncated || numstat.truncated || allFiles.length > files.length);
49193
+ }
49194
+ function parseTrack(track) {
49195
+ if (track === "gone")
49196
+ return { ahead: null, behind: null };
49197
+ const ahead = /ahead (\d+)/.exec(track);
49198
+ const behind = /behind (\d+)/.exec(track);
49199
+ return { ahead: ahead ? Number(ahead[1]) : 0, behind: behind ? Number(behind[1]) : 0 };
49200
+ }
49201
+ async function readBranchesGit(input2, signal) {
49202
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
49203
+ const root = await exactRoot(input2.repoPath, deadline);
49204
+ if (!root.ok)
49205
+ return root;
49206
+ const format = [
49207
+ "%(refname)",
49208
+ "%(objectname)",
49209
+ "%(HEAD)",
49210
+ "%(upstream:short)",
49211
+ "%(upstream:track,nobracket)",
49212
+ "%(committerdate:iso-strict)",
49213
+ "%(contents:subject)",
49214
+ "%(worktreepath)"
49215
+ ].join("%1f");
49216
+ const run = await git(root, [
49217
+ "for-each-ref",
49218
+ `--format=${format}`,
49219
+ "--sort=-committerdate",
49220
+ `--count=${BRANCH_LIMIT + 1}`,
49221
+ "refs/heads",
49222
+ "refs/remotes"
49223
+ ], deadline, LIST_OUTPUT_BYTES);
49224
+ if (run.timedOut || run.aborted)
49225
+ return outcome(root, "timeout", "The read timed out on the target.");
49226
+ if (run.exitCode !== 0 && !run.truncated)
49227
+ return failed("git for-each-ref failed on the target.");
49228
+ const mergedRun = root.head ? await git(root, ["for-each-ref", "--format=%(refname)", "--merged=HEAD", "refs/heads"], deadline, LIST_OUTPUT_BYTES) : null;
49229
+ const merged = mergedRun && mergedRun.exitCode === 0 && !mergedRun.truncated ? new Set(mergedRun.stdout.toString("utf8").split("\n").filter(Boolean)) : null;
49230
+ const branches = [];
49231
+ let truncated = run.truncated;
49232
+ for (const line of run.stdout.toString("utf8").split("\n")) {
49233
+ const [refname, head, mark, upstream, track, date5, subject, worktreePath] = line.split(FIELD);
49234
+ if (!refname || !head)
49235
+ continue;
49236
+ const local = refname.startsWith("refs/heads/");
49237
+ const name = refname.replace(/^refs\/(heads|remotes)\//, "");
49238
+ if (!local && name.endsWith("/HEAD"))
49239
+ continue;
49240
+ if (branches.length === BRANCH_LIMIT) {
49241
+ truncated = true;
49242
+ break;
49243
+ }
49244
+ const counts = local && upstream ? parseTrack(track ?? "") : { ahead: null, behind: null };
49245
+ const current = mark === "*";
49246
+ branches.push({
49247
+ name,
49248
+ kind: local ? "local" : "remote",
49249
+ head,
49250
+ current,
49251
+ upstream: local && upstream ? upstream : null,
49252
+ ...counts,
49253
+ lastCommitAt: date5 || null,
49254
+ subject: subject ?? "",
49255
+ checkedOutElsewhere: !current && !!worktreePath && resolveRealPath(worktreePath) !== root.realRoot,
49256
+ ...local && merged ? { merged: merged.has(refname) } : {}
49257
+ });
49258
+ }
49259
+ return ok(root, { branches }, truncated);
49260
+ }
49261
+ function worktreeLocation(worktreePath, mainPath, home = homedir2()) {
49262
+ const relativeToMain = path41.relative(mainPath, worktreePath);
49263
+ if (relativeToMain === "")
49264
+ return ".";
49265
+ if (!relativeToMain.startsWith("..") && !path41.isAbsolute(relativeToMain))
49266
+ return relativeToMain;
49267
+ const relativeToHome = path41.relative(home, worktreePath);
49268
+ if (relativeToHome && !relativeToHome.startsWith("..") && !path41.isAbsolute(relativeToHome)) {
49269
+ return `~/${relativeToHome}`;
49270
+ }
49271
+ return path41.basename(worktreePath);
49272
+ }
49273
+ function parseWorktreeList(output2, realRoot, realpath2 = resolveRealPath) {
49274
+ const blocks = output2.split(/\n\n+/).filter((block) => block.trim());
49275
+ const worktrees = [];
49276
+ let mainPath = null;
49277
+ for (const block of blocks) {
49278
+ const lines2 = block.split("\n");
49279
+ const pathLine = lines2.find((line) => line.startsWith("worktree "));
49280
+ if (!pathLine)
49281
+ continue;
49282
+ const worktreePath = pathLine.slice(9);
49283
+ if (lines2.includes("bare")) {
49284
+ mainPath ??= worktreePath;
49285
+ continue;
49286
+ }
49287
+ const isMain = mainPath === null;
49288
+ mainPath ??= worktreePath;
49289
+ const head = lines2.find((line) => line.startsWith("HEAD "))?.slice(5) ?? null;
49290
+ const branch = lines2.find((line) => line.startsWith("branch "))?.slice(7) ?? null;
49291
+ worktrees.push({
49292
+ name: isMain ? "Main worktree" : path41.basename(worktreePath),
49293
+ location: worktreeLocation(worktreePath, mainPath),
49294
+ isMain,
49295
+ isCurrent: realpath2(worktreePath) === realRoot,
49296
+ head,
49297
+ branch: branch ? branch.replace(/^refs\/heads\//, "") : null,
49298
+ detached: lines2.includes("detached"),
49299
+ locked: lines2.some((line) => line === "locked" || line.startsWith("locked ")),
49300
+ prunable: lines2.some((line) => line === "prunable" || line.startsWith("prunable "))
49301
+ });
49302
+ if (worktrees.length === WORKTREE_LIMIT)
49303
+ break;
49304
+ }
49305
+ return worktrees;
49306
+ }
49307
+ async function readWorktreesGit(input2, signal) {
49308
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
49309
+ const root = await exactRoot(input2.repoPath, deadline);
49310
+ if (!root.ok)
49311
+ return root;
49312
+ const run = await git(root, ["worktree", "list", "--porcelain"], deadline, LIST_OUTPUT_BYTES);
49313
+ if (run.timedOut || run.aborted)
49314
+ return outcome(root, "timeout", "The read timed out on the target.");
49315
+ if (run.exitCode !== 0 && !run.truncated)
49316
+ return failed("git worktree list failed on the target.");
49317
+ const worktrees = parseWorktreeList(run.stdout.toString("utf8"), root.realRoot);
49318
+ return ok(root, { worktrees }, run.truncated || worktrees.length === WORKTREE_LIMIT);
49319
+ }
49320
+ var COMMIT_LOG_PAGE_SIZE, COMMIT_FILES_LIMIT, BRANCH_LIMIT, WORKTREE_LIMIT, LOG_OUTPUT_BYTES, LIST_OUTPUT_BYTES, FIELD, RECORD, SUMMARY_FORMAT;
49321
+ var init_project_history_git = __esm({
49322
+ "../packages/core/dist/service/local-target/project-history-git.js"() {
49323
+ "use strict";
49324
+ init_current_diff_git();
49325
+ init_git_run();
49326
+ init_repository_read_git();
49327
+ init_worktree_git();
49328
+ COMMIT_LOG_PAGE_SIZE = 50;
49329
+ COMMIT_FILES_LIMIT = 500;
49330
+ BRANCH_LIMIT = 500;
49331
+ WORKTREE_LIMIT = 200;
49332
+ LOG_OUTPUT_BYTES = 256 * 1024;
49333
+ LIST_OUTPUT_BYTES = 512 * 1024;
49334
+ FIELD = "";
49335
+ RECORD = "";
49336
+ SUMMARY_FORMAT = ["%H", "%P", "%an", "%aI", "%s", "%D"].join("%x1f");
49337
+ }
49338
+ });
49339
+
49340
+ // ../packages/core/dist/service/local-target/project-resource-write-git.js
49341
+ import { spawn as spawn8 } from "node:child_process";
49342
+ import { lstatSync as lstatSync6, realpathSync as realpathSync11, unlinkSync as unlinkSync5 } from "node:fs";
49343
+ import path42 from "node:path";
49344
+ function exactWritePath(value2, { folder = false } = {}) {
49345
+ const bare = folder && value2.endsWith("/") ? value2.slice(0, -1) : value2;
49346
+ const checked = normalizeRepositoryRelativePath(bare);
49347
+ if (!checked.ok || !checked.relativePath || checked.relativePath !== bare)
49348
+ return null;
49349
+ return value2;
49350
+ }
49351
+ function invalidWriteEntries(entries) {
49352
+ const seen = /* @__PURE__ */ new Set();
49353
+ for (const entry of entries) {
49354
+ const untracked = entry.index === "?" || entry.worktree === "?";
49355
+ if (!STATUS_CODES.has(entry.index) || !STATUS_CODES.has(entry.worktree)) {
49356
+ return "Use the index and worktree status columns from Git status.";
49357
+ }
49358
+ if (untracked && (entry.index !== "?" || entry.worktree !== "?" || entry.originalPath)) {
49359
+ return "An untracked entry has the status ?? and no original path.";
49360
+ }
49361
+ if (!exactWritePath(entry.path, { folder: untracked })) {
49362
+ return "Use exact resource-relative paths.";
49363
+ }
49364
+ if (entry.originalPath !== null && !exactWritePath(entry.originalPath)) {
49365
+ return "Use exact resource-relative paths.";
49366
+ }
49367
+ if (seen.has(entry.path))
49368
+ return "Each path may appear once.";
49369
+ seen.add(entry.path);
49370
+ }
49371
+ return null;
49372
+ }
49373
+ function currentEntries(status) {
49374
+ const entries = /* @__PURE__ */ new Map();
49375
+ for (const entry of [...status.staged, ...status.unstaged]) {
49376
+ entries.set(entry.path, {
49377
+ index: entry.index,
49378
+ worktree: entry.worktree,
49379
+ originalPath: entry.originalPath
49380
+ });
49381
+ }
49382
+ for (const untracked of status.untracked) {
49383
+ entries.set(untracked, { index: "?", worktree: "?", originalPath: null });
49384
+ }
49385
+ return entries;
49386
+ }
49387
+ function sameHead(expected, current) {
49388
+ if (expected === null || current === null)
49389
+ return expected === current;
49390
+ return current === expected || expected.length >= 7 && current.startsWith(expected);
49391
+ }
49392
+ function pathspecs(entries) {
49393
+ const specs = /* @__PURE__ */ new Set();
49394
+ for (const entry of entries) {
49395
+ specs.add(entry.path);
49396
+ if (entry.originalPath)
49397
+ specs.add(entry.originalPath);
49398
+ }
49399
+ return [...specs];
49400
+ }
49401
+ function writeGitEnv() {
49402
+ const env = inspectionGitEnv();
49403
+ delete env.GIT_OPTIONAL_LOCKS;
49404
+ delete env.GIT_NO_LAZY_FETCH;
49405
+ env.GIT_EDITOR = "true";
49406
+ env.GIT_SEQUENCE_EDITOR = "true";
49407
+ env.GIT_MERGE_AUTOEDIT = "no";
49408
+ return env;
49409
+ }
49410
+ function runWriteGit(cwd, args, timeoutMs, extraConfig = []) {
49411
+ return new Promise((resolve) => {
49412
+ let stdout = "";
49413
+ let stderr = "";
49414
+ let timedOut = false;
49415
+ const child = spawn8("git", [...WRITE_GIT_CONFIG_ARGS, ...extraConfig, ...args], {
49416
+ cwd,
49417
+ env: writeGitEnv(),
49418
+ stdio: ["ignore", "pipe", "pipe"],
49419
+ shell: false,
49420
+ windowsHide: true
49421
+ });
49422
+ const timer = setTimeout(() => {
49423
+ timedOut = true;
49424
+ if (child.exitCode === null)
49425
+ child.kill("SIGKILL");
49426
+ }, Math.max(1, timeoutMs));
49427
+ child.stdout.on("data", (chunk) => {
49428
+ if (stdout.length < 16 * 1024)
49429
+ stdout += chunk.toString("utf8");
49430
+ });
49431
+ child.stderr.on("data", (chunk) => {
49432
+ if (stderr.length < 8 * 1024)
49433
+ stderr += chunk.toString("utf8");
49434
+ });
49435
+ const done = (exitCode) => {
49436
+ clearTimeout(timer);
49437
+ resolve({ exitCode, stdout, stderr, timedOut });
49438
+ };
49439
+ child.on("error", () => done(null));
49440
+ child.on("close", (code) => done(code));
49441
+ });
49442
+ }
49443
+ function excerpt(stderr, root) {
49444
+ const text = stderr.split(root).join(".").trim();
49445
+ if (!text)
49446
+ return null;
49447
+ return text.length > MESSAGE_EXCERPT_CHARS ? `${text.slice(0, MESSAGE_EXCERPT_CHARS)}\u2026` : text;
49448
+ }
49449
+ function failureMessage(run, root, fallback) {
49450
+ if (/index\.lock/.test(run.stderr)) {
49451
+ return "Another Git process is using this checkout. Try again when it finishes.";
49452
+ }
49453
+ const detail = excerpt(run.stderr, root);
49454
+ return detail ? `${fallback}
49455
+ ${detail}` : fallback;
49456
+ }
49457
+ async function readStatus(root, specs, deadline) {
49458
+ const run = await runInspectionGit({
49459
+ cwd: root,
49460
+ args: [
49461
+ "--literal-pathspecs",
49462
+ "status",
49463
+ "--porcelain=v2",
49464
+ "--branch",
49465
+ "-z",
49466
+ "--untracked-files=normal",
49467
+ "--ignore-submodules=all",
49468
+ "--",
49469
+ ...specs ?? ["."]
49470
+ ],
49471
+ timeoutMs: deadline.remaining(),
49472
+ maxBytes: STATUS_OUTPUT_BYTES,
49473
+ signal: deadline.signal
49474
+ });
49475
+ if (run.exitCode !== 0)
49476
+ return null;
49477
+ const parsed = parseStatusV2(run.stdout, STATUS_ENTRY_LIMIT, "");
49478
+ return { data: parsed.data, truncated: parsed.truncated || run.truncated };
49479
+ }
49480
+ async function readHead(root, deadline) {
49481
+ const line = async (args) => {
49482
+ const run = await runInspectionGit({
49483
+ cwd: root,
49484
+ args,
49485
+ timeoutMs: deadline.remaining(),
49486
+ maxBytes: 4096,
49487
+ signal: deadline.signal
49488
+ });
49489
+ const text = run.exitCode === 0 ? run.stdout.toString("utf8").trim() : "";
49490
+ return text || null;
49491
+ };
49492
+ const [head, branch] = await Promise.all([
49493
+ line(["rev-parse", "--verify", "--quiet", "HEAD"]),
49494
+ line(["branch", "--show-current"])
49495
+ ]);
49496
+ return { head, branch };
49497
+ }
49498
+ function removeUntrackedFile(root, relativePath) {
49499
+ const absolute = path42.resolve(root, relativePath);
49500
+ let parent;
49501
+ try {
49502
+ parent = realpathSync11(path42.dirname(absolute));
49503
+ } catch {
49504
+ return "denied";
49505
+ }
49506
+ if (parent !== root && !parent.startsWith(root + path42.sep))
49507
+ return "denied";
49508
+ const target = path42.join(parent, path42.basename(absolute));
49509
+ let stat2;
49510
+ try {
49511
+ stat2 = lstatSync6(target);
49512
+ } catch {
49513
+ return "denied";
49514
+ }
49515
+ if (!stat2.isFile() && !stat2.isSymbolicLink())
49516
+ return "rejected";
49517
+ unlinkSync5(target);
49518
+ return "ok";
49519
+ }
49520
+ async function writeProjectResourceGit(input2) {
49521
+ const deadline = new ReadDeadline(PROJECT_RESOURCE_WRITE_TARGET_BUDGET_MS);
49522
+ const root = await inspectRepositoryRoot(input2.repoPath, deadline);
49523
+ if (!root.ok)
49524
+ return root;
49525
+ if (!root.isGitRepository || root.prefix !== "") {
49526
+ return {
49527
+ ok: false,
49528
+ code: "NOT_GIT_REPOSITORY",
49529
+ message: "The resource is not a Git checkout."
49530
+ };
49531
+ }
49532
+ const cwd = root.realRoot;
49533
+ const answer = (outcome2, message, at = root, commit2 = null) => ({
49534
+ outcome: outcome2,
49535
+ message,
49536
+ head: at.head,
49537
+ branch: at.branch,
49538
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
49539
+ commit: commit2
49540
+ });
49541
+ const invalid = invalidWriteEntries(input2.entries);
49542
+ if (invalid)
49543
+ return answer("rejected", invalid);
49544
+ const commit = input2.operation === "commit";
49545
+ const status = await readStatus(cwd, commit ? null : pathspecs(input2.entries), deadline);
49546
+ if (!status)
49547
+ return answer("failed", "Git status could not be read on the target.");
49548
+ const head = status.data.head;
49549
+ if (!sameHead(input2.expectedHead, head)) {
49550
+ return answer("precondition_failed", "HEAD moved since you reviewed these changes. Review the refreshed status.");
49551
+ }
49552
+ if (status.data.conflicted.length > 0) {
49553
+ return answer("rejected", "Resolve the merge conflicts before this change.");
49554
+ }
49555
+ if (commit && input2.entries.some((entry) => entry.index === "." || entry.index === "?")) {
49556
+ return answer("rejected", "Only staged files can be committed.");
49557
+ }
49558
+ const current = currentEntries(status.data);
49559
+ const changed = input2.entries.some((entry) => {
49560
+ const now = current.get(entry.path);
49561
+ return !now || now.index !== entry.index || // A commit records the index only; later worktree edits stay uncommitted.
49562
+ !commit && now.worktree !== entry.worktree || now.originalPath !== entry.originalPath;
49563
+ });
49564
+ if (changed) {
49565
+ return answer("precondition_failed", "These files changed since you reviewed them. Review the refreshed status.");
49566
+ }
49567
+ let run = null;
49568
+ let fallback = "Git refused the change.";
49569
+ switch (input2.operation) {
49570
+ case "stage": {
49571
+ if (input2.entries.some((entry) => entry.worktree === ".")) {
49572
+ return answer("rejected", "Only files with unstaged changes can be staged.");
49573
+ }
49574
+ run = await runWriteGit(cwd, ["add", "-A", "--", ...pathspecs(input2.entries)], deadline.remaining());
49575
+ fallback = "Git could not stage these files.";
49576
+ break;
49577
+ }
49578
+ case "unstage": {
49579
+ if (input2.entries.some((entry) => entry.index === "." || entry.index === "?")) {
49580
+ return answer("rejected", "Only staged files can be unstaged.");
49581
+ }
49582
+ run = await runWriteGit(cwd, head === null ? ["rm", "--cached", "-r", "-q", "--", ...pathspecs(input2.entries)] : ["restore", "--staged", "--", ...pathspecs(input2.entries)], deadline.remaining());
49583
+ fallback = "Git could not unstage these files.";
49584
+ break;
49585
+ }
49586
+ case "discard": {
49587
+ const untracked = input2.entries.filter((entry) => entry.worktree === "?");
49588
+ const tracked = input2.entries.filter((entry) => entry.worktree !== "?");
49589
+ if (tracked.some((entry) => entry.worktree === ".")) {
49590
+ return answer("rejected", "Only files with unstaged changes can be discarded.");
49591
+ }
49592
+ if (untracked.length > 0 && input2.confirmUntracked !== true) {
49593
+ return answer("rejected", "Confirm deleting untracked files before discarding them.");
49594
+ }
49595
+ if (untracked.some((entry) => entry.path.endsWith("/"))) {
49596
+ return answer("rejected", "Untracked folders cannot be discarded here. Delete the folder yourself.");
49597
+ }
49598
+ if (tracked.length > 0) {
49599
+ run = await runWriteGit(cwd, ["restore", "--worktree", "--", ...tracked.map((entry) => entry.path)], deadline.remaining());
49600
+ fallback = "Git could not discard these changes.";
49601
+ if (run.exitCode !== 0)
49602
+ break;
49603
+ }
49604
+ for (const entry of untracked) {
49605
+ const removed = removeUntrackedFile(cwd, entry.path);
49606
+ if (removed !== "ok") {
49607
+ return answer(removed, removed === "denied" ? "The runner could not safely delete this path." : "Only untracked files and links can be discarded here.", await readHead(cwd, deadline));
49608
+ }
49609
+ }
49610
+ break;
49611
+ }
49612
+ case "commit": {
49613
+ if (status.truncated) {
49614
+ return answer("rejected", "Too many changed files to verify the staged set.");
49615
+ }
49616
+ const staged = status.data.staged;
49617
+ if (staged.length !== input2.entries.length) {
49618
+ return answer("precondition_failed", "The staged files changed since you reviewed them. Review the refreshed status.");
49619
+ }
49620
+ if (input2.subject.includes("\n") || !input2.subject.trim()) {
49621
+ return answer("rejected", "The commit subject must be one non-empty line.");
49622
+ }
49623
+ const description = input2.description?.trim();
49624
+ run = await runWriteGit(cwd, [
49625
+ "commit",
49626
+ "--quiet",
49627
+ "-m",
49628
+ input2.subject.trim(),
49629
+ ...description ? ["-m", description] : []
49630
+ ], deadline.remaining());
49631
+ fallback = "Git or a commit hook refused the commit.";
49632
+ break;
49633
+ }
49634
+ }
49635
+ if (run?.timedOut) {
49636
+ return {
49637
+ ok: false,
49638
+ code: "LOCAL_TARGET_TIMEOUT",
49639
+ message: "The write timed out on the target. Refresh status before trying again."
49640
+ };
49641
+ }
49642
+ const after = await readHead(cwd, deadline);
49643
+ if (run && run.exitCode !== 0)
49644
+ return answer("failed", failureMessage(run, cwd, fallback), after);
49645
+ if (input2.operation === "commit") {
49646
+ if (!after.head || after.head === head) {
49647
+ return answer("failed", "Git did not record a new commit.", after);
49648
+ }
49649
+ return answer("ok", null, after, { sha: after.head, subject: input2.subject.trim() });
49650
+ }
49651
+ return answer("ok", null, after);
49652
+ }
49653
+ var PROJECT_RESOURCE_WRITE_TARGET_BUDGET_MS, STATUS_ENTRY_LIMIT, STATUS_OUTPUT_BYTES, MESSAGE_EXCERPT_CHARS, STATUS_CODES, WRITE_GIT_CONFIG_ARGS;
49654
+ var init_project_resource_write_git = __esm({
49655
+ "../packages/core/dist/service/local-target/project-resource-write-git.js"() {
49656
+ "use strict";
49657
+ init_git_run();
49658
+ init_repository_paths();
49659
+ init_repository_read_git();
49660
+ PROJECT_RESOURCE_WRITE_TARGET_BUDGET_MS = 45e3;
49661
+ STATUS_ENTRY_LIMIT = 2e3;
49662
+ STATUS_OUTPUT_BYTES = 1024 * 1024;
49663
+ MESSAGE_EXCERPT_CHARS = 600;
49664
+ STATUS_CODES = /* @__PURE__ */ new Set([".", "M", "T", "A", "D", "R", "C", "U", "?"]);
49665
+ WRITE_GIT_CONFIG_ARGS = [
49666
+ "-c",
49667
+ "core.quotePath=false",
49668
+ "-c",
49669
+ "color.ui=false",
49670
+ "-c",
49671
+ "maintenance.auto=false",
49672
+ "-c",
49673
+ "gc.auto=0",
49674
+ "--no-pager",
49675
+ "--literal-pathspecs"
49676
+ ];
49677
+ }
49678
+ });
49679
+
49680
+ // ../packages/core/dist/service/local-target/project-resource-sync-git.js
49681
+ import { realpathSync as realpathSync12, statSync as statSync9 } from "node:fs";
49682
+ import path43 from "node:path";
49683
+ function isSafeRemoteName(name) {
49684
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(name) && !name.endsWith(".lock");
49685
+ }
49686
+ function isRemoteBranchRef(ref) {
49687
+ return ref.startsWith("refs/heads/") && isSafeRefName(ref.slice("refs/heads/".length));
49688
+ }
49689
+ async function exactRoot2(repoPath, deadline) {
49690
+ const root = await inspectRepositoryRoot(repoPath, deadline);
49691
+ if (!root.ok)
49692
+ return root;
49693
+ if (!root.isGitRepository || root.prefix !== "") {
49694
+ return {
49695
+ ok: false,
49696
+ code: "NOT_GIT_REPOSITORY",
49697
+ message: "The resource is not a Git checkout."
49698
+ };
49699
+ }
49700
+ return root;
49701
+ }
49702
+ async function gitText(cwd, args, deadline, maxBytes = 64 * 1024) {
49703
+ const run = await runInspectionGit({
49704
+ cwd,
49705
+ args,
49706
+ timeoutMs: deadline.remaining(),
49707
+ maxBytes,
49708
+ signal: deadline.signal
49709
+ });
49710
+ return run.exitCode === 0 && !run.truncated ? run.stdout.toString("utf8") : null;
49711
+ }
49712
+ async function readRemotes(cwd, deadline) {
49713
+ const text = await gitText(cwd, ["remote"], deadline);
49714
+ return (text ?? "").split("\n").map((line) => line.trim()).filter(isSafeRemoteName).slice(0, REMOTE_LIMIT);
49715
+ }
49716
+ async function readUpstream(cwd, branch, deadline) {
49717
+ if (!branch || !isSafeRefName(branch))
49718
+ return null;
49719
+ const text = await gitText(cwd, [
49720
+ "for-each-ref",
49721
+ "--format=%(upstream)%1f%(upstream:remotename)%1f%(upstream:remoteref)%1f%(upstream:short)",
49722
+ `refs/heads/${branch}`
49723
+ ], deadline);
49724
+ const [trackingRef, remote, remoteRef, name] = (text ?? "").trim().split("");
49725
+ if (!trackingRef?.startsWith("refs/remotes/") || !remote || !isSafeRemoteName(remote) || !remoteRef || !isRemoteBranchRef(remoteRef)) {
49726
+ return null;
49727
+ }
49728
+ const head = await gitText(cwd, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${trackingRef}^{commit}`], deadline);
49729
+ return {
49730
+ name: name || trackingRef.slice("refs/remotes/".length),
49731
+ remote,
49732
+ remoteRef,
49733
+ trackingRef,
49734
+ head: head?.trim() || null
49735
+ };
49736
+ }
49737
+ async function readCommitRange(cwd, range, deadline) {
49738
+ const text = await gitText(cwd, [
49739
+ "log",
49740
+ "--no-color",
49741
+ "--decorate=full",
49742
+ `--format=${SUMMARY_FORMAT2}%x1e`,
49743
+ `--max-count=${COMMIT_LIST_LIMIT + 1}`,
49744
+ "--end-of-options",
49745
+ range,
49746
+ "--"
49747
+ ], deadline, 256 * 1024);
49748
+ const commits = text === null ? [] : parseCommitLog(text);
49749
+ return {
49750
+ commits: commits.slice(0, COMMIT_LIST_LIMIT),
49751
+ truncated: commits.length > COMMIT_LIST_LIMIT
49752
+ };
49753
+ }
49754
+ async function countRange(cwd, a, b, deadline) {
49755
+ const text = await gitText(cwd, ["rev-list", "--left-right", "--count", "--end-of-options", `${a}...${b}`, "--"], deadline);
49756
+ const [ahead, behind] = (text ?? "").trim().split(/\s+/).map(Number);
49757
+ return Number.isInteger(ahead) && Number.isInteger(behind) ? { ahead, behind } : { ahead: null, behind: null };
49758
+ }
49759
+ async function gitPathExists(cwd, name, deadline) {
49760
+ const relative = (await gitText(cwd, ["rev-parse", "--git-path", name], deadline))?.trim();
49761
+ if (!relative)
49762
+ return null;
49763
+ try {
49764
+ return statSync9(path43.resolve(cwd, relative));
49765
+ } catch {
49766
+ return null;
49767
+ }
49768
+ }
49769
+ async function operationInProgress(cwd, deadline) {
49770
+ const checks = [
49771
+ ["rebase-merge", "rebase"],
49772
+ ["rebase-apply", "rebase"],
49773
+ ["MERGE_HEAD", "merge"],
49774
+ ["CHERRY_PICK_HEAD", "cherry_pick"],
49775
+ ["REVERT_HEAD", "revert"]
49776
+ ];
49777
+ for (const [name, kind] of checks) {
49778
+ if (await gitPathExists(cwd, name, deadline))
49779
+ return kind;
49780
+ }
49781
+ return null;
49782
+ }
49783
+ function dirtyPaths(status) {
49784
+ const paths = /* @__PURE__ */ new Set();
49785
+ if (!status)
49786
+ return paths;
49787
+ for (const entry of [...status.data.staged, ...status.data.unstaged, ...status.data.conflicted]) {
49788
+ paths.add(entry.path);
49789
+ if (entry.originalPath)
49790
+ paths.add(entry.originalPath);
49791
+ }
49792
+ return paths;
49793
+ }
49794
+ function resolveDir(dir) {
49795
+ try {
49796
+ return realpathSync12(dir);
49797
+ } catch {
49798
+ return path43.resolve(dir);
49799
+ }
49800
+ }
49801
+ async function readSyncStatusGit(input2, signal) {
49802
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
49803
+ const root = await exactRoot2(input2.repoPath, deadline);
49804
+ if (!root.ok)
49805
+ return root;
49806
+ const cwd = root.realRoot;
49807
+ const [remotes, upstream, status, inProgress, fetchHead, dirs] = await Promise.all([
49808
+ readRemotes(cwd, deadline),
49809
+ readUpstream(cwd, root.branch, deadline),
49810
+ readStatus(cwd, null, deadline),
49811
+ operationInProgress(cwd, deadline),
49812
+ gitPathExists(cwd, "FETCH_HEAD", deadline),
49813
+ gitText(cwd, ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"], deadline)
49814
+ ]);
49815
+ const [gitDir, commonDir] = (dirs ?? "").trim().split("\n");
49816
+ let ahead = null;
49817
+ let behind = null;
49818
+ let outgoing = { commits: [], truncated: false };
49819
+ let incoming = { commits: [], truncated: false };
49820
+ if (upstream?.head && root.head) {
49821
+ ({ ahead, behind } = await countRange(cwd, "HEAD", upstream.head, deadline));
49822
+ [outgoing, incoming] = await Promise.all([
49823
+ readCommitRange(cwd, `${upstream.head}..HEAD`, deadline),
49824
+ readCommitRange(cwd, `HEAD..${upstream.head}`, deadline)
49825
+ ]);
49826
+ }
49827
+ const uncommitted = status ? (/* @__PURE__ */ new Set([...dirtyPaths(status), ...status.data.untracked])).size : 0;
49828
+ return {
49829
+ outcome: "ok",
49830
+ head: root.head,
49831
+ branch: root.branch,
49832
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
49833
+ truncated: Boolean(status?.truncated),
49834
+ data: {
49835
+ branch: root.branch,
49836
+ head: root.head,
49837
+ worktree: {
49838
+ name: path43.basename(cwd),
49839
+ isMain: Boolean(gitDir) && resolveDir(gitDir) === resolveDir(commonDir ?? "")
49840
+ },
49841
+ upstream,
49842
+ remotes,
49843
+ ahead,
49844
+ behind,
49845
+ fastForward: behind === null ? null : behind === 0,
49846
+ outgoing: outgoing.commits,
49847
+ outgoingTruncated: outgoing.truncated,
49848
+ incoming: incoming.commits,
49849
+ incomingTruncated: incoming.truncated,
49850
+ lastFetchedAt: fetchHead ? fetchHead.mtime.toISOString() : null,
49851
+ uncommittedCount: uncommitted,
49852
+ operationInProgress: inProgress
49853
+ }
49854
+ };
49855
+ }
49856
+ async function changedNames(cwd, a, b, deadline) {
49857
+ const text = await gitText(cwd, ["diff", "--no-renames", "--name-only", "-z", "--end-of-options", a, b, "--"], deadline, 1024 * 1024);
49858
+ if (text === null)
49859
+ return null;
49860
+ return new Set(text.split("\0").filter(Boolean));
49861
+ }
49862
+ function agentConflict(paths, agentPaths) {
49863
+ const hits = agentPaths.filter((entry) => paths.has(entry.path));
49864
+ if (hits.length === 0)
49865
+ return null;
49866
+ const shown = hits.slice(0, AGENT_PATHS_SHOWN).map((entry) => `${entry.path} (${entry.owner})`).join(", ");
49867
+ const more = hits.length > AGENT_PATHS_SHOWN ? ` and ${hits.length - AGENT_PATHS_SHOWN} more` : "";
49868
+ return `Stopped before touching files an agent is editing: ${shown}${more}. Nothing was changed.`;
49869
+ }
49870
+ function plural2(count, word) {
49871
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
49872
+ }
49873
+ async function syncProjectResourceGit(input2) {
49874
+ const deadline = new ReadDeadline(PROJECT_RESOURCE_SYNC_TARGET_BUDGET_MS);
49875
+ const root = await exactRoot2(input2.repoPath, deadline);
49876
+ if (!root.ok)
49877
+ return root;
49878
+ const cwd = root.realRoot;
49879
+ const answer = (outcome2, message, at = root) => ({
49880
+ outcome: outcome2,
49881
+ message,
49882
+ head: at.head,
49883
+ branch: at.branch,
49884
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
49885
+ commit: null
49886
+ });
49887
+ const timedOut = () => ({
49888
+ ok: false,
49889
+ code: "LOCAL_TARGET_TIMEOUT",
49890
+ message: "The operation timed out on the target. Refresh status before trying again."
49891
+ });
49892
+ const remotes = await readRemotes(cwd, deadline);
49893
+ const upstream = await readUpstream(cwd, root.branch, deadline);
49894
+ if (input2.operation === "fetch") {
49895
+ const remote = upstream?.remote ?? (remotes.includes("origin") ? "origin" : remotes.length === 1 ? remotes[0] : null);
49896
+ if (!remote)
49897
+ return answer("rejected", "This checkout has no remote to fetch from.");
49898
+ const run2 = await runWriteGit(cwd, ["fetch", "--quiet", "--no-recurse-submodules", "--end-of-options", remote], deadline.remaining(), NETWORK_CONFIG);
49899
+ if (run2.timedOut)
49900
+ return timedOut();
49901
+ if (run2.exitCode !== 0)
49902
+ return answer("failed", networkFailure(run2, cwd, `fetch ${remote}`));
49903
+ return answer("ok", `Fetched ${remote}.`, await readHead(cwd, deadline));
49904
+ }
49905
+ if (root.branch !== input2.branch) {
49906
+ return answer("precondition_failed", "The checked-out branch changed since you reviewed it. Review the refreshed status.");
49907
+ }
49908
+ if (!sameHead(input2.expectedHead, root.head)) {
49909
+ return answer("precondition_failed", "HEAD moved since you reviewed it. Review the refreshed status.");
49910
+ }
49911
+ if (!upstream) {
49912
+ return answer("rejected", `${input2.branch} has no upstream branch on a remote.`);
49913
+ }
49914
+ const inProgress = await operationInProgress(cwd, deadline);
49915
+ if (inProgress) {
49916
+ return answer("rejected", `A ${inProgress.replace("_", "-")} is in progress. Finish or abort it first.`);
49917
+ }
49918
+ if (input2.operation === "push") {
49919
+ if (input2.remote !== upstream.remote || input2.remoteRef !== upstream.remoteRef || !remotes.includes(input2.remote)) {
49920
+ return answer("precondition_failed", `${input2.branch} no longer pushes to ${input2.remote} ${input2.remoteRef}. Review again.`);
49921
+ }
49922
+ if (upstream.head !== input2.expectedRemoteHead) {
49923
+ return answer("precondition_failed", `${upstream.name} moved since you reviewed this push. Review the refreshed commits.`);
49924
+ }
49925
+ const ancestor = await runInspectionGit({
49926
+ cwd,
49927
+ args: ["merge-base", "--is-ancestor", "--end-of-options", input2.expectedRemoteHead, "HEAD"],
49928
+ timeoutMs: deadline.remaining(),
49929
+ maxBytes: 1024,
49930
+ signal: deadline.signal
49931
+ });
49932
+ if (ancestor.exitCode !== 0) {
49933
+ return answer("rejected", `This is not a fast-forward of ${upstream.name}. Pull its commits first.`);
49934
+ }
49935
+ const head = root.head;
49936
+ const run2 = await runWriteGit(cwd, [
49937
+ "push",
49938
+ "--porcelain",
49939
+ "--no-progress",
49940
+ `--force-with-lease=${input2.remoteRef}:${input2.expectedRemoteHead}`,
49941
+ "--end-of-options",
49942
+ input2.remote,
49943
+ `${head}:${input2.remoteRef}`
49944
+ ], deadline.remaining(), NETWORK_CONFIG);
49945
+ if (run2.timedOut)
49946
+ return timedOut();
49947
+ const after2 = await readHead(cwd, deadline);
49948
+ if (run2.exitCode !== 0) {
49949
+ if (/\[rejected\]\s*\(stale info\)/.test(run2.stdout)) {
49950
+ return answer("precondition_failed", `${upstream.name} moved on the remote since your last fetch. Fetch and review again. Nothing was sent.`, after2);
49951
+ }
49952
+ if (/\[rejected\]/.test(run2.stdout)) {
49953
+ return answer("rejected", `The remote refused a non-fast-forward update. Fetch and pull first. Nothing was sent.`, after2);
49954
+ }
49955
+ return answer("failed", networkFailure(run2, cwd, `push to ${upstream.name}`), after2);
49956
+ }
49957
+ return answer("ok", `${upstream.name} is now at ${head.slice(0, 8)}.`, after2);
49958
+ }
49959
+ if (!upstream.head || upstream.head !== input2.expectedUpstreamHead) {
49960
+ return answer("precondition_failed", `${upstream.name} changed since you reviewed the incoming commits. Review again.`);
49961
+ }
49962
+ const counts = await countRange(cwd, "HEAD", upstream.head, deadline);
49963
+ if (counts.behind === 0)
49964
+ return answer("ok", `${input2.branch} already has every commit.`);
49965
+ const status = await readStatus(cwd, null, deadline);
49966
+ if (!status)
49967
+ return answer("failed", "Git status could not be read on the target.");
49968
+ if (status.data.conflicted.length > 0) {
49969
+ return answer("rejected", "Resolve the merge conflicts before pulling.");
49970
+ }
49971
+ const base = (await gitText(cwd, ["merge-base", "--end-of-options", "HEAD", upstream.head], deadline))?.trim();
49972
+ if (!base)
49973
+ return answer("failed", "Git could not find a common ancestor with the remote.");
49974
+ const incoming = await changedNames(cwd, base, upstream.head, deadline);
49975
+ const outgoing = input2.mode === "rebase" ? await changedNames(cwd, base, "HEAD", deadline) : /* @__PURE__ */ new Set();
49976
+ if (!incoming || !outgoing)
49977
+ return answer("failed", "Git could not list the incoming changes.");
49978
+ const dirty = dirtyPaths(status);
49979
+ const touched = /* @__PURE__ */ new Set([...incoming, ...outgoing]);
49980
+ if (input2.mode === "rebase")
49981
+ for (const entry of dirty)
49982
+ touched.add(entry);
49983
+ const agentStop = agentConflict(touched, input2.agentPaths ?? []);
49984
+ if (agentStop)
49985
+ return answer("rejected", agentStop);
49986
+ const overlap = [...incoming].filter((entry) => dirty.has(entry));
49987
+ if (input2.mode === "merge" && overlap.length > 0) {
49988
+ return answer("rejected", `The incoming commits change ${plural2(overlap.length, "file")} with uncommitted changes (${overlap.slice(0, AGENT_PATHS_SHOWN).join(", ")}). Commit or discard them first. Nothing was changed.`);
49989
+ }
49990
+ let run;
49991
+ if (input2.mode === "merge") {
49992
+ run = await runWriteGit(cwd, counts.ahead === 0 ? ["merge", "--ff-only", "--no-stat", "--end-of-options", upstream.head] : [
49993
+ "merge",
49994
+ "--no-stat",
49995
+ "--no-edit",
49996
+ "-m",
49997
+ `Merge ${upstream.name} into ${input2.branch}`,
49998
+ "--end-of-options",
49999
+ upstream.head
50000
+ ], deadline.remaining());
50001
+ } else {
50002
+ run = await runWriteGit(cwd, [
50003
+ "rebase",
50004
+ "--no-autosquash",
50005
+ ...dirty.size > 0 ? ["--autostash"] : ["--no-autostash"],
50006
+ "--end-of-options",
50007
+ upstream.head
50008
+ ], deadline.remaining());
50009
+ }
50010
+ if (run.timedOut)
50011
+ return timedOut();
50012
+ const after = await readHead(cwd, deadline);
50013
+ if (run.exitCode !== 0) {
50014
+ const stopped = await operationInProgress(cwd, deadline);
50015
+ if (stopped) {
50016
+ return answer("failed", `The ${stopped} stopped with conflicts. Resolve them in your editor, then continue or abort the ${stopped}.`, after);
50017
+ }
50018
+ return answer("failed", failureText(run, cwd, "Git could not pull these commits."), after);
50019
+ }
50020
+ const verb = input2.mode === "rebase" ? "Rebased onto" : "Merged";
50021
+ return answer("ok", `${verb} ${plural2(counts.behind ?? 0, "commit")} from ${upstream.name}.${dirty.size > 0 ? " Uncommitted changes were kept." : ""}`, after);
50022
+ }
50023
+ function failureText(run, root, fallback) {
50024
+ if (/index\.lock/.test(run.stderr)) {
50025
+ return "Another Git process is using this checkout. Try again when it finishes.";
50026
+ }
50027
+ const detail = excerpt(run.stderr || run.stdout, root);
50028
+ return detail ? `${fallback}
50029
+ ${detail}` : fallback;
50030
+ }
50031
+ function networkFailure(run, root, action) {
50032
+ const text = `${run.stderr}
50033
+ ${run.stdout}`;
50034
+ if (/terminal prompts disabled|could not read Username|Authentication failed|Permission denied \(publickey/i.test(text)) {
50035
+ return `Git on this machine has no usable credentials to ${action}. Sign in to the remote on that machine; Overlord never handles Git credentials.`;
50036
+ }
50037
+ if (/Could not resolve host|unable to access|Connection (timed out|refused)|Network is unreachable/i.test(text)) {
50038
+ return `The remote could not be reached to ${action}.`;
50039
+ }
50040
+ return failureText(run, root, `Git could not ${action}.`);
50041
+ }
50042
+ function isSyncInput(input2) {
50043
+ return SYNC_OPERATIONS.has(input2.operation);
50044
+ }
50045
+ var SYNC_OPERATIONS, PROJECT_RESOURCE_SYNC_TARGET_BUDGET_MS, COMMIT_LIST_LIMIT, REMOTE_LIMIT, AGENT_PATHS_SHOWN, SUMMARY_FORMAT2, NETWORK_CONFIG;
50046
+ var init_project_resource_sync_git = __esm({
50047
+ "../packages/core/dist/service/local-target/project-resource-sync-git.js"() {
50048
+ "use strict";
50049
+ init_git_run();
50050
+ init_project_history_git();
50051
+ init_project_resource_write_git();
50052
+ init_repository_read_git();
50053
+ SYNC_OPERATIONS = /* @__PURE__ */ new Set([
50054
+ "fetch",
50055
+ "pull",
50056
+ "push"
50057
+ ]);
50058
+ PROJECT_RESOURCE_SYNC_TARGET_BUDGET_MS = 11e4;
50059
+ COMMIT_LIST_LIMIT = 50;
50060
+ REMOTE_LIMIT = 50;
50061
+ AGENT_PATHS_SHOWN = 5;
50062
+ SUMMARY_FORMAT2 = ["%H", "%P", "%an", "%aI", "%s", "%D"].join("%x1f");
50063
+ NETWORK_CONFIG = [
50064
+ "-c",
50065
+ "credential.interactive=false",
50066
+ "-c",
50067
+ "fetch.recurseSubmodules=false"
50068
+ ];
50069
+ }
50070
+ });
50071
+
50072
+ // ../packages/core/dist/service/local-target/project-resource-branch-git.js
50073
+ import { lstatSync as lstatSync7 } from "node:fs";
50074
+ import path44 from "node:path";
50075
+ function isWorktreeFolderName(name) {
50076
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name) && !name.endsWith(".lock");
50077
+ }
50078
+ function parseWorktreeRecords(output2) {
50079
+ const records = [];
50080
+ for (const block of output2.split(/\n\n+/)) {
50081
+ const lines2 = block.split("\n");
50082
+ const pathLine = lines2.find((line) => line.startsWith("worktree "));
50083
+ if (!pathLine || lines2.includes("bare"))
50084
+ continue;
50085
+ const branch = lines2.find((line) => line.startsWith("branch "))?.slice(7) ?? null;
50086
+ records.push({
50087
+ path: pathLine.slice(9),
50088
+ head: lines2.find((line) => line.startsWith("HEAD "))?.slice(5) ?? null,
50089
+ branch: branch ? branch.replace(/^refs\/heads\//, "") : null,
50090
+ isMain: records.length === 0,
50091
+ locked: lines2.some((line) => line === "locked" || line.startsWith("locked ")),
50092
+ prunable: lines2.some((line) => line === "prunable" || line.startsWith("prunable "))
50093
+ });
50094
+ }
50095
+ return records;
50096
+ }
50097
+ async function listWorktrees(cwd, deadline) {
50098
+ const text = await gitText(cwd, ["worktree", "list", "--porcelain"], deadline, 512 * 1024);
50099
+ return text === null ? [] : parseWorktreeRecords(text);
50100
+ }
50101
+ function inside(parent, child) {
50102
+ const relative = path44.relative(parent, child);
50103
+ return relative === "" || !relative.startsWith("..") && !path44.isAbsolute(relative);
50104
+ }
50105
+ function agentOwnersByWorktree(worktrees, agents, checkout, realpath2 = resolveRealPath) {
50106
+ const resolved = worktrees.map((worktree) => realpath2(worktree.path));
50107
+ const owners = /* @__PURE__ */ new Map();
50108
+ const add = (key, owner) => {
50109
+ const list = owners.get(key) ?? [];
50110
+ if (!list.includes(owner))
50111
+ list.push(owner);
50112
+ owners.set(key, list);
50113
+ };
50114
+ for (const agent of agents) {
50115
+ if (agent.path === null) {
50116
+ add(checkout, agent.owner);
50117
+ continue;
50118
+ }
50119
+ const where = realpath2(agent.path);
50120
+ let best = null;
50121
+ for (const candidate of resolved) {
50122
+ if (inside(candidate, where) && (best === null || candidate.length > best.length)) {
50123
+ best = candidate;
50124
+ }
50125
+ }
50126
+ if (best)
50127
+ add(best, agent.owner);
50128
+ }
50129
+ return owners;
50130
+ }
50131
+ function ownerText(owners) {
50132
+ const shown = owners.slice(0, OWNERS_SHOWN).join(", ");
50133
+ return owners.length > OWNERS_SHOWN ? `${shown} and ${owners.length - OWNERS_SHOWN} more` : shown;
50134
+ }
50135
+ async function branchTip(cwd, branch, deadline) {
50136
+ return (await gitText(cwd, ["rev-parse", "--verify", "--quiet", "--end-of-options", `refs/heads/${branch}^{commit}`], deadline))?.trim() || null;
50137
+ }
50138
+ async function commitExists(cwd, sha, deadline) {
50139
+ const text = await gitText(cwd, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${sha}^{commit}`], deadline);
50140
+ return text?.trim() || null;
50141
+ }
50142
+ async function validBranchName(cwd, name, deadline) {
50143
+ if (!isSafeRefName(name))
50144
+ return false;
50145
+ const run = await runInspectionGit({
50146
+ cwd,
50147
+ args: ["check-ref-format", "--branch", name],
50148
+ timeoutMs: deadline.remaining(),
50149
+ maxBytes: 4096,
50150
+ signal: deadline.signal
50151
+ });
50152
+ return run.exitCode === 0;
50153
+ }
50154
+ async function isAncestor(cwd, commit, of, deadline) {
50155
+ const run = await runInspectionGit({
50156
+ cwd,
50157
+ args: ["merge-base", "--is-ancestor", "--end-of-options", commit, of],
50158
+ timeoutMs: deadline.remaining(),
50159
+ maxBytes: 1024,
50160
+ signal: deadline.signal
50161
+ });
50162
+ return run.exitCode === 0;
50163
+ }
50164
+ function pathExists(value2) {
50165
+ try {
50166
+ lstatSync7(value2);
50167
+ return true;
50168
+ } catch {
50169
+ return false;
50170
+ }
50171
+ }
50172
+ function plural3(count, word) {
50173
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
50174
+ }
50175
+ function short(sha) {
50176
+ return sha ? sha.slice(0, 8) : "unknown";
50177
+ }
50178
+ function defaultRemote(remotes) {
50179
+ if (remotes.includes("origin"))
50180
+ return "origin";
50181
+ return remotes.length === 1 ? remotes[0] : null;
50182
+ }
50183
+ async function readPublishReviewGit(input2, signal) {
50184
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
50185
+ const root = await exactRoot2(input2.repoPath, deadline);
50186
+ if (!root.ok)
50187
+ return root;
50188
+ const cwd = root.realRoot;
50189
+ const base = { head: root.head, branch: root.branch, observedAt: (/* @__PURE__ */ new Date()).toISOString() };
50190
+ if (!isSafeRefName(input2.branch)) {
50191
+ return {
50192
+ ...base,
50193
+ outcome: "not_found",
50194
+ truncated: false,
50195
+ message: "No such branch.",
50196
+ data: null
50197
+ };
50198
+ }
50199
+ const head = await branchTip(cwd, input2.branch, deadline);
50200
+ if (!head) {
50201
+ return {
50202
+ ...base,
50203
+ outcome: "not_found",
50204
+ truncated: false,
50205
+ message: `${input2.branch} is not a local branch.`,
50206
+ data: null
50207
+ };
50208
+ }
50209
+ const [remotes, upstreamText, worktrees, fetchHead] = await Promise.all([
50210
+ readRemotes(cwd, deadline),
50211
+ gitText(cwd, ["for-each-ref", "--format=%(upstream:short)", `refs/heads/${input2.branch}`], deadline),
50212
+ listWorktrees(cwd, deadline),
50213
+ gitPathExists(cwd, "FETCH_HEAD", deadline)
50214
+ ]);
50215
+ const remote = defaultRemote(remotes);
50216
+ const tracking = remote ? await gitText(cwd, [
50217
+ "rev-parse",
50218
+ "--verify",
50219
+ "--quiet",
50220
+ "--end-of-options",
50221
+ `refs/remotes/${remote}/${input2.branch}`
50222
+ ], deadline) : null;
50223
+ const log = await gitText(cwd, [
50224
+ "log",
50225
+ "--no-color",
50226
+ "--decorate=full",
50227
+ `--format=${SUMMARY_FORMAT2}%x1e`,
50228
+ `--max-count=${PUBLISH_COMMIT_LIMIT + 1}`,
50229
+ // `head` is the full commit ID rev-parse returned, never an option.
50230
+ head,
50231
+ ...remote ? ["--not", `--remotes=${remote}`] : [],
50232
+ "--"
50233
+ ], deadline, 256 * 1024);
50234
+ const commits = log === null ? [] : parseCommitLog(log);
50235
+ const holder = worktrees.find((worktree) => worktree.branch === input2.branch);
50236
+ return {
50237
+ ...base,
50238
+ outcome: "ok",
50239
+ truncated: false,
50240
+ data: {
50241
+ branch: input2.branch,
50242
+ head,
50243
+ upstream: upstreamText?.trim() || null,
50244
+ remotes,
50245
+ remote,
50246
+ remoteBranchExists: Boolean(tracking?.trim()),
50247
+ commits: commits.slice(0, PUBLISH_COMMIT_LIMIT),
50248
+ commitsTruncated: commits.length > PUBLISH_COMMIT_LIMIT,
50249
+ worktree: holder ? holder.isMain ? "main worktree" : path44.basename(holder.path) : null,
50250
+ lastFetchedAt: fetchHead ? fetchHead.mtime.toISOString() : null
50251
+ }
50252
+ };
50253
+ }
50254
+ function isBranchInput(input2) {
50255
+ return BRANCH_OPERATIONS.has(input2.operation);
50256
+ }
50257
+ async function branchProjectResourceGit(input2) {
50258
+ const deadline = new ReadDeadline(input2.operation === "branch_publish" ? PROJECT_RESOURCE_BRANCH_TARGET_BUDGET_MS : PROJECT_RESOURCE_WRITE_TARGET_BUDGET_MS);
50259
+ const root = await exactRoot2(input2.repoPath, deadline);
50260
+ if (!root.ok)
50261
+ return root;
50262
+ const cwd = root.realRoot;
50263
+ const answer = (outcome2, message, at = root) => ({
50264
+ outcome: outcome2,
50265
+ message,
50266
+ head: at.head,
50267
+ branch: at.branch,
50268
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
50269
+ commit: null
50270
+ });
50271
+ const timedOut = () => ({
50272
+ ok: false,
50273
+ code: "LOCAL_TARGET_TIMEOUT",
50274
+ message: "The operation timed out on the target. Refresh before trying again."
50275
+ });
50276
+ const worktrees = await listWorktrees(cwd, deadline);
50277
+ const agents = input2.agentWorktrees ?? [];
50278
+ const owners = agentOwnersByWorktree(worktrees, agents, cwd);
50279
+ const worktreeName = (record2) => record2.isMain ? "the main worktree" : `worktree ${path44.basename(record2.path)}`;
50280
+ switch (input2.operation) {
50281
+ case "branch_create": {
50282
+ if (!await validBranchName(cwd, input2.name, deadline)) {
50283
+ return answer("rejected", `${input2.name} is not a valid branch name.`);
50284
+ }
50285
+ if (await branchTip(cwd, input2.name, deadline)) {
50286
+ return answer("rejected", `A branch named ${input2.name} already exists.`);
50287
+ }
50288
+ const start = await commitExists(cwd, input2.startPoint, deadline);
50289
+ if (!start)
50290
+ return answer("rejected", "That commit is not in this repository.");
50291
+ const run = await runWriteGit(cwd, [
50292
+ "update-ref",
50293
+ "-m",
50294
+ `branch: Created from ${start}`,
50295
+ `refs/heads/${input2.name}`,
50296
+ start,
50297
+ ""
50298
+ ], deadline.remaining());
50299
+ if (run.timedOut)
50300
+ return timedOut();
50301
+ if (run.exitCode !== 0) {
50302
+ return answer("failed", failureText(run, cwd, `Git could not create ${input2.name}.`));
50303
+ }
50304
+ return answer("ok", `Created ${input2.name} at ${short(start)}.`);
50305
+ }
50306
+ case "branch_switch": {
50307
+ if (root.branch !== input2.expectedBranch || !sameHead(input2.expectedHead, root.head)) {
50308
+ return answer("precondition_failed", "The checkout changed since you reviewed it. Review the refreshed branches.");
50309
+ }
50310
+ if (input2.branch === root.branch)
50311
+ return answer("ok", `Already on ${input2.branch}.`);
50312
+ if (!isSafeRefName(input2.branch) || !await branchTip(cwd, input2.branch, deadline)) {
50313
+ return answer("rejected", `${input2.branch} is not a local branch.`);
50314
+ }
50315
+ const using = owners.get(cwd);
50316
+ if (using?.length) {
50317
+ return answer("rejected", `An agent session (${ownerText(using)}) is using this worktree. Switching would move it, so nothing was changed.`);
50318
+ }
50319
+ const inProgress = await operationInProgress(cwd, deadline);
50320
+ if (inProgress) {
50321
+ return answer("rejected", `A ${inProgress.replace("_", "-")} is in progress. Finish or abort it first.`);
50322
+ }
50323
+ const holder = worktrees.find((worktree) => worktree.branch === input2.branch && resolveRealPath(worktree.path) !== cwd);
50324
+ if (holder) {
50325
+ return answer("rejected", `${input2.branch} is checked out in ${worktreeName(holder)}. A branch can be checked out in one worktree at a time.`);
50326
+ }
50327
+ const status = await readStatus(cwd, null, deadline);
50328
+ if (!status)
50329
+ return answer("failed", "Git status could not be read on the target.");
50330
+ if (status.data.conflicted.length > 0) {
50331
+ return answer("rejected", "Resolve the merge conflicts before switching.");
50332
+ }
50333
+ const tracked = new Set([...status.data.staged, ...status.data.unstaged].map((entry) => entry.path)).size;
50334
+ if (tracked > 0 && !input2.keepChanges) {
50335
+ return answer("rejected", `This worktree has ${plural3(tracked, "uncommitted change")}. Commit or discard ${tracked === 1 ? "it" : "them"}, or choose to bring ${tracked === 1 ? "it" : "them"} to ${input2.branch}.`);
50336
+ }
50337
+ const run = await runWriteGit(cwd, ["switch", "--no-guess", "--end-of-options", input2.branch], deadline.remaining());
50338
+ if (run.timedOut)
50339
+ return timedOut();
50340
+ const after = await readHead(cwd, deadline);
50341
+ if (run.exitCode !== 0) {
50342
+ if (/would be overwritten|untracked working tree files/i.test(run.stderr)) {
50343
+ return answer("rejected", `Your uncommitted or untracked files conflict with ${input2.branch}. Nothing was changed.`, after);
50344
+ }
50345
+ return answer("failed", failureText(run, cwd, `Git could not switch to ${input2.branch}.`), after);
50346
+ }
50347
+ return answer("ok", `Switched to ${input2.branch}.${tracked > 0 ? " Uncommitted changes came along." : ""}`, after);
50348
+ }
50349
+ case "branch_publish": {
50350
+ if (!isSafeRefName(input2.branch))
50351
+ return answer("rejected", "Use a plain branch name.");
50352
+ if (!isSafeRemoteName(input2.remote))
50353
+ return answer("rejected", "Use a plain remote name.");
50354
+ const remotes = await readRemotes(cwd, deadline);
50355
+ if (!remotes.includes(input2.remote)) {
50356
+ return answer("precondition_failed", `This checkout has no remote named ${input2.remote}.`);
50357
+ }
50358
+ const tip = await branchTip(cwd, input2.branch, deadline);
50359
+ if (!tip)
50360
+ return answer("rejected", `${input2.branch} is not a local branch.`);
50361
+ if (tip !== input2.expectedHead) {
50362
+ return answer("precondition_failed", `${input2.branch} moved since you reviewed it. Review the refreshed commits.`);
50363
+ }
50364
+ const upstream = (await gitText(cwd, ["for-each-ref", "--format=%(upstream:short)", `refs/heads/${input2.branch}`], deadline))?.trim();
50365
+ if (upstream) {
50366
+ return answer("rejected", `${input2.branch} already tracks ${upstream}. Push it instead.`);
50367
+ }
50368
+ const remoteRef = `refs/heads/${input2.branch}`;
50369
+ const run = await runWriteGit(cwd, [
50370
+ "push",
50371
+ "--porcelain",
50372
+ "--no-progress",
50373
+ `--force-with-lease=${remoteRef}:`,
50374
+ "--end-of-options",
50375
+ input2.remote,
50376
+ `${tip}:${remoteRef}`
50377
+ ], deadline.remaining(), NETWORK_CONFIG);
50378
+ if (run.timedOut)
50379
+ return timedOut();
50380
+ if (run.exitCode !== 0) {
50381
+ if (/\[rejected\]/.test(run.stdout)) {
50382
+ return answer("rejected", `${input2.remote} already has a branch named ${input2.branch}. Nothing was sent.`);
50383
+ }
50384
+ return answer("failed", networkFailure(run, cwd, `publish to ${input2.remote}`));
50385
+ }
50386
+ const configure = async (key, value2) => runWriteGit(cwd, ["config", "--local", `branch.${input2.branch}.${key}`, value2], deadline.remaining());
50387
+ const setRemote = await configure("remote", input2.remote);
50388
+ const setMerge = setRemote.exitCode === 0 ? await configure("merge", remoteRef) : setRemote;
50389
+ if (setMerge.exitCode !== 0) {
50390
+ return answer("failed", `Published ${input2.branch} to ${input2.remote}, but Git could not record it as the upstream.`);
50391
+ }
50392
+ return answer("ok", `Published ${input2.branch} to ${input2.remote}/${input2.branch} at ${short(tip)} and set it as the upstream.`);
50393
+ }
50394
+ case "branch_delete": {
50395
+ if (!isSafeRefName(input2.branch))
50396
+ return answer("rejected", "Use a plain branch name.");
50397
+ const tip = await branchTip(cwd, input2.branch, deadline);
50398
+ if (!tip)
50399
+ return answer("precondition_failed", `${input2.branch} no longer exists.`);
50400
+ if (tip !== input2.expectedHead) {
50401
+ return answer("precondition_failed", `${input2.branch} moved since you reviewed it. Nothing was deleted.`);
50402
+ }
50403
+ if (input2.branch === root.branch) {
50404
+ return answer("rejected", `${input2.branch} is checked out here. Switch away from it first.`);
50405
+ }
50406
+ const holder = worktrees.find((worktree) => worktree.branch === input2.branch);
50407
+ if (holder) {
50408
+ return answer("rejected", holder.prunable ? `${input2.branch} belongs to a missing worktree record. Prune that record first.` : `${input2.branch} is checked out in ${worktreeName(holder)}.`);
50409
+ }
50410
+ const agentOwners = agents.filter((agent) => agent.branch === input2.branch).map((agent) => agent.owner);
50411
+ if (agentOwners.length > 0) {
50412
+ return answer("rejected", `An agent session (${ownerText(agentOwners)}) is working on ${input2.branch}. Nothing was deleted.`);
50413
+ }
50414
+ if (input2.allowUnmerged !== true) {
50415
+ const upstream = (await gitText(cwd, ["for-each-ref", "--format=%(upstream)", `refs/heads/${input2.branch}`], deadline))?.trim();
50416
+ const merged = root.head !== null && await isAncestor(cwd, tip, "HEAD", deadline) || Boolean(upstream) && await isAncestor(cwd, tip, upstream, deadline);
50417
+ if (!merged) {
50418
+ return answer("rejected", `${input2.branch} has commits that are not in ${root.branch ?? "HEAD"} or its upstream. Nothing was deleted.`);
50419
+ }
50420
+ }
50421
+ const run = await runWriteGit(cwd, ["update-ref", "-m", "branch: deleted", "-d", `refs/heads/${input2.branch}`, tip], deadline.remaining());
50422
+ if (run.timedOut)
50423
+ return timedOut();
50424
+ if (run.exitCode !== 0) {
50425
+ return answer("failed", failureText(run, cwd, `Git could not delete ${input2.branch}.`));
50426
+ }
50427
+ await runWriteGit(cwd, ["config", "--local", "--remove-section", `branch.${input2.branch}`], deadline.remaining());
50428
+ return answer("ok", `Deleted ${input2.branch} (was ${short(tip)}). To restore it, create a branch at ${short(tip)}.`);
50429
+ }
50430
+ case "worktree_create": {
50431
+ if (!isWorktreeFolderName(input2.name)) {
50432
+ return answer("rejected", "Use a folder name of letters, digits, `.`, `_` and `-`.");
50433
+ }
50434
+ const main = worktrees.find((worktree) => worktree.isMain);
50435
+ if (!main)
50436
+ return answer("failed", "Git could not list the worktrees on the target.");
50437
+ const location = path44.join(path44.dirname(main.path), `${path44.basename(main.path)}-worktrees`, input2.name);
50438
+ if (pathExists(location)) {
50439
+ return answer("rejected", `A folder named ${input2.name} already exists there.`);
50440
+ }
50441
+ let args;
50442
+ if (input2.newBranch) {
50443
+ if (!await validBranchName(cwd, input2.branch, deadline)) {
50444
+ return answer("rejected", `${input2.branch} is not a valid branch name.`);
50445
+ }
50446
+ if (await branchTip(cwd, input2.branch, deadline)) {
50447
+ return answer("rejected", `A branch named ${input2.branch} already exists.`);
50448
+ }
50449
+ const start = input2.startPoint ? await commitExists(cwd, input2.startPoint, deadline) : null;
50450
+ if (!start)
50451
+ return answer("rejected", "Choose a commit to start the new branch from.");
50452
+ args = ["worktree", "add", "--no-track", "-b", input2.branch, "--", location, start];
50453
+ } else {
50454
+ if (!isSafeRefName(input2.branch) || !await branchTip(cwd, input2.branch, deadline)) {
50455
+ return answer("rejected", `${input2.branch} is not a local branch.`);
50456
+ }
50457
+ const holder = worktrees.find((worktree) => worktree.branch === input2.branch);
50458
+ if (holder) {
50459
+ return answer("rejected", `${input2.branch} is already checked out in ${worktreeName(holder)}.`);
50460
+ }
50461
+ args = ["worktree", "add", "--", location, input2.branch];
50462
+ }
50463
+ const run = await runWriteGit(cwd, args, deadline.remaining());
50464
+ if (run.timedOut)
50465
+ return timedOut();
50466
+ if (run.exitCode !== 0) {
50467
+ return answer("failed", failureText(run, cwd, "Git could not add the worktree."));
50468
+ }
50469
+ return answer("ok", `Added worktree ${input2.name} at ${worktreeLocation(location, main.path)} on ${input2.branch}.`);
50470
+ }
50471
+ case "worktree_prune": {
50472
+ const main = worktrees.find((worktree) => worktree.isMain);
50473
+ const record2 = main ? worktrees.find((worktree) => worktreeLocation(worktree.path, main.path) === input2.location) : void 0;
50474
+ if (!record2 || !main) {
50475
+ return answer("precondition_failed", "That worktree is no longer listed. Review the refreshed worktrees.");
50476
+ }
50477
+ if (record2.isMain || resolveRealPath(record2.path) === cwd) {
50478
+ return answer("rejected", "The main worktree and this checkout cannot be pruned.");
50479
+ }
50480
+ if (pathExists(record2.path)) {
50481
+ return answer("rejected", "The worktree folder still exists. Only records of missing folders are pruned here.");
50482
+ }
50483
+ if (record2.locked) {
50484
+ return answer("rejected", "This worktree record is locked. Unlock it on the machine first.");
50485
+ }
50486
+ const using = owners.get(resolveRealPath(record2.path));
50487
+ if (using?.length) {
50488
+ return answer("rejected", `An agent session (${ownerText(using)}) is using this worktree. Nothing was pruned.`);
50489
+ }
50490
+ const run = await runWriteGit(cwd, ["worktree", "remove", "--", record2.path], deadline.remaining());
50491
+ if (run.timedOut)
50492
+ return timedOut();
50493
+ if (run.exitCode !== 0) {
50494
+ return answer("failed", failureText(run, cwd, "Git could not prune the worktree record."));
50495
+ }
50496
+ return answer("ok", `Removed the record of ${path44.basename(record2.path)}.`);
50497
+ }
50498
+ }
50499
+ }
50500
+ var BRANCH_OPERATIONS, PROJECT_RESOURCE_BRANCH_TARGET_BUDGET_MS, PUBLISH_COMMIT_LIMIT, OWNERS_SHOWN;
50501
+ var init_project_resource_branch_git = __esm({
50502
+ "../packages/core/dist/service/local-target/project-resource-branch-git.js"() {
50503
+ "use strict";
50504
+ init_git_run();
50505
+ init_project_history_git();
50506
+ init_project_resource_sync_git();
50507
+ init_project_resource_write_git();
50508
+ init_repository_read_git();
50509
+ init_worktree_git();
50510
+ BRANCH_OPERATIONS = /* @__PURE__ */ new Set([
50511
+ "branch_create",
50512
+ "branch_switch",
50513
+ "branch_publish",
50514
+ "branch_delete",
50515
+ "worktree_create",
50516
+ "worktree_prune"
50517
+ ]);
50518
+ PROJECT_RESOURCE_BRANCH_TARGET_BUDGET_MS = 11e4;
50519
+ PUBLISH_COMMIT_LIMIT = 50;
50520
+ OWNERS_SHOWN = 3;
50521
+ }
50522
+ });
50523
+
50524
+ // ../packages/core/dist/service/local-target/project-resource-conflict-git.js
50525
+ import { closeSync as closeSync4, lstatSync as lstatSync8, openSync as openSync4, readFileSync as readFileSync25, readSync as readSync3, realpathSync as realpathSync13 } from "node:fs";
50526
+ import path45 from "node:path";
50527
+ function isConflictInput(input2) {
50528
+ return CONFLICT_OPERATIONS.has(input2.operation);
50529
+ }
50530
+ async function gitDirText(cwd, name, deadline) {
50531
+ const relative = (await gitText(cwd, ["rev-parse", "--git-path", name], deadline))?.trim();
50532
+ if (!relative)
50533
+ return null;
50534
+ try {
50535
+ const file2 = path45.resolve(cwd, relative);
50536
+ if (!lstatSync8(file2).isFile())
50537
+ return null;
50538
+ return readFileSync25(file2, "utf8").slice(0, 4096);
50539
+ } catch {
50540
+ return null;
50541
+ }
50542
+ }
50543
+ async function gitDirLine(cwd, name, deadline) {
50544
+ const text = await gitDirText(cwd, name, deadline);
50545
+ const line = text?.split("\n")[0]?.trim();
50546
+ return line || null;
50547
+ }
50548
+ async function commitSubject(cwd, sha, deadline) {
50549
+ const text = await gitText(cwd, ["log", "-1", "--no-color", "--format=%s", "--end-of-options", sha, "--"], deadline);
50550
+ return text?.trim().slice(0, MESSAGE_CHARS) || null;
50551
+ }
50552
+ function hasConflictMarkers(root, relativePath) {
50553
+ const checked = exactWritePath(relativePath);
50554
+ if (!checked)
50555
+ return false;
50556
+ const absolute = path45.resolve(root, relativePath);
50557
+ let parent;
50558
+ try {
50559
+ parent = realpathSync13(path45.dirname(absolute));
50560
+ } catch {
50561
+ return false;
50562
+ }
50563
+ if (parent !== root && !parent.startsWith(root + path45.sep))
50564
+ return false;
50565
+ const target = path45.join(parent, path45.basename(absolute));
50566
+ let fd = null;
50567
+ try {
50568
+ const stat2 = lstatSync8(target);
50569
+ if (!stat2.isFile() || stat2.size > MARKER_SCAN_BYTES)
50570
+ return false;
50571
+ fd = openSync4(target, "r");
50572
+ const buffer = Buffer.alloc(stat2.size);
50573
+ const read = readSync3(fd, buffer, 0, stat2.size, 0);
50574
+ return CONFLICT_MARKER.test(buffer.subarray(0, read).toString("utf8"));
50575
+ } catch {
50576
+ return false;
50577
+ } finally {
50578
+ if (fd !== null)
50579
+ closeSync4(fd);
50580
+ }
50581
+ }
50582
+ function mergeLabel(message) {
50583
+ if (!message)
50584
+ return null;
50585
+ const branch = /^Merge (?:remote-tracking )?branch '([^']+)'/.exec(message);
50586
+ if (branch)
50587
+ return branch[1];
50588
+ const ours = /^Merge (\S+) into \S+/.exec(message);
50589
+ return ours ? ours[1] : null;
50590
+ }
50591
+ function shaOrNull(value2) {
50592
+ return value2 && /^[0-9a-f]{40,64}$/.test(value2) ? value2 : null;
50593
+ }
50594
+ function plural4(count, word) {
50595
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
50596
+ }
50597
+ function listed(paths) {
50598
+ const shown = paths.slice(0, PATHS_SHOWN).join(", ");
50599
+ return paths.length > PATHS_SHOWN ? `${shown} and ${paths.length - PATHS_SHOWN} more` : shown;
50600
+ }
50601
+ async function readConflictStateGit(input2, signal) {
50602
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
50603
+ const root = await exactRoot2(input2.repoPath, deadline);
50604
+ if (!root.ok)
50605
+ return root;
50606
+ const cwd = root.realRoot;
50607
+ const [operation, status] = await Promise.all([
50608
+ operationInProgress(cwd, deadline),
50609
+ readStatus(cwd, null, deadline)
50610
+ ]);
50611
+ const base = { head: root.head, branch: root.branch, observedAt: (/* @__PURE__ */ new Date()).toISOString() };
50612
+ if (!status) {
50613
+ return { ...base, outcome: "unavailable", truncated: false, data: null };
50614
+ }
50615
+ const conflicted = status.data.conflicted.slice(0, CONFLICT_LIST_LIMIT).map((entry) => ({
50616
+ path: entry.path,
50617
+ index: entry.index,
50618
+ worktree: entry.worktree,
50619
+ markers: hasConflictMarkers(cwd, entry.path)
50620
+ }));
50621
+ let branch = root.branch;
50622
+ let incoming = null;
50623
+ let onto = null;
50624
+ let step = null;
50625
+ let message = null;
50626
+ switch (operation) {
50627
+ case "merge": {
50628
+ message = (await gitDirLine(cwd, "MERGE_MSG", deadline))?.slice(0, MESSAGE_CHARS) ?? null;
50629
+ const sha = shaOrNull(await gitDirLine(cwd, "MERGE_HEAD", deadline));
50630
+ incoming = sha ? { sha, label: mergeLabel(message) } : null;
50631
+ break;
50632
+ }
50633
+ case "cherry_pick":
50634
+ case "revert": {
50635
+ message = (await gitDirLine(cwd, "MERGE_MSG", deadline))?.slice(0, MESSAGE_CHARS) ?? null;
50636
+ const sha = shaOrNull(await gitDirLine(cwd, operation === "revert" ? "REVERT_HEAD" : "CHERRY_PICK_HEAD", deadline));
50637
+ incoming = sha ? { sha, label: null } : null;
50638
+ break;
50639
+ }
50640
+ case "rebase": {
50641
+ const dir = await gitDirLine(cwd, "rebase-merge/head-name", deadline) ? "rebase-merge" : "rebase-apply";
50642
+ const headName = await gitDirLine(cwd, `${dir}/head-name`, deadline);
50643
+ const name = headName?.startsWith("refs/heads/") ? headName.slice(11) : null;
50644
+ branch = name && isSafeRefName(name) ? name : null;
50645
+ onto = shaOrNull(await gitDirLine(cwd, `${dir}/onto`, deadline));
50646
+ const [current, total] = await Promise.all([
50647
+ gitDirLine(cwd, dir === "rebase-merge" ? `${dir}/msgnum` : `${dir}/next`, deadline),
50648
+ gitDirLine(cwd, dir === "rebase-merge" ? `${dir}/end` : `${dir}/last`, deadline)
50649
+ ]);
50650
+ if (current && total && /^\d+$/.test(current) && /^\d+$/.test(total)) {
50651
+ step = { current: Number(current), total: Number(total) };
50652
+ }
50653
+ const sha = shaOrNull(await gitDirLine(cwd, "REBASE_HEAD", deadline));
50654
+ if (sha) {
50655
+ incoming = { sha, label: null };
50656
+ message = await commitSubject(cwd, sha, deadline);
50657
+ }
50658
+ break;
50659
+ }
50660
+ default:
50661
+ break;
50662
+ }
50663
+ return {
50664
+ ...base,
50665
+ outcome: "ok",
50666
+ truncated: status.truncated || status.data.conflicted.length > CONFLICT_LIST_LIMIT,
50667
+ data: {
50668
+ operation,
50669
+ branch,
50670
+ head: root.head,
50671
+ incoming,
50672
+ onto,
50673
+ step,
50674
+ message,
50675
+ conflicted,
50676
+ conflictedTruncated: status.data.conflicted.length > CONFLICT_LIST_LIMIT,
50677
+ stagedCount: status.data.staged.length
50678
+ }
50679
+ };
50680
+ }
50681
+ async function conflictProjectResourceGit(input2) {
50682
+ const deadline = new ReadDeadline(PROJECT_RESOURCE_WRITE_TARGET_BUDGET_MS);
50683
+ const root = await exactRoot2(input2.repoPath, deadline);
50684
+ if (!root.ok)
50685
+ return root;
50686
+ const cwd = root.realRoot;
50687
+ const answer = (outcome2, message, at = root, commit = null) => ({
50688
+ outcome: outcome2,
50689
+ message,
50690
+ head: at.head,
50691
+ branch: at.branch,
50692
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
50693
+ commit
50694
+ });
50695
+ const timedOut = () => ({
50696
+ ok: false,
50697
+ code: "LOCAL_TARGET_TIMEOUT",
50698
+ message: "The operation timed out on the target. Refresh before trying again."
50699
+ });
50700
+ const operation = await operationInProgress(cwd, deadline);
50701
+ if (!operation) {
50702
+ return answer("rejected", "No merge, rebase, cherry-pick or revert is in progress.");
50703
+ }
50704
+ if (!sameHead(input2.expectedHead, root.head)) {
50705
+ return answer("precondition_failed", "HEAD moved since you reviewed the conflict. Review the refreshed state.");
50706
+ }
50707
+ const label = LABELS[operation];
50708
+ if (input2.operation === "conflict_resolve") {
50709
+ const paths = input2.entries.map((entry) => entry.path);
50710
+ if (paths.some((entry) => !exactWritePath(entry)) || new Set(paths).size !== paths.length) {
50711
+ return answer("rejected", "Use exact resource-relative paths, each once.");
50712
+ }
50713
+ const status2 = await readStatus(cwd, paths, deadline);
50714
+ if (!status2)
50715
+ return answer("failed", "Git status could not be read on the target.");
50716
+ const current = new Map(status2.data.conflicted.map((entry) => [entry.path, entry]));
50717
+ const changed = input2.entries.some((entry) => {
50718
+ const now = current.get(entry.path);
50719
+ return !now || now.index !== entry.index || now.worktree !== entry.worktree;
50720
+ });
50721
+ if (changed) {
50722
+ return answer("precondition_failed", "These files are no longer conflicted as you reviewed them. Review the refreshed state.");
50723
+ }
50724
+ const marked = paths.filter((entry) => hasConflictMarkers(cwd, entry));
50725
+ if (marked.length > 0 && input2.allowMarkers !== true) {
50726
+ return answer("rejected", `${listed(marked)} still ${marked.length === 1 ? "has" : "have"} conflict markers. Edit ${marked.length === 1 ? "it" : "them"} first, or confirm staging as is.`);
50727
+ }
50728
+ const run2 = await runWriteGit(cwd, ["add", "-A", "--", ...paths], deadline.remaining());
50729
+ if (run2.timedOut)
50730
+ return timedOut();
50731
+ const after2 = await readHead(cwd, deadline);
50732
+ if (run2.exitCode !== 0) {
50733
+ return answer("failed", failureText(run2, cwd, "Git could not mark these files resolved."), after2);
50734
+ }
50735
+ return answer("ok", `Marked ${plural4(paths.length, "file")} resolved.`, after2);
50736
+ }
50737
+ if (operation !== input2.expectedOperation) {
50738
+ return answer("precondition_failed", `A ${label} is in progress, not the ${LABELS[input2.expectedOperation]} you reviewed. Review the refreshed state.`);
50739
+ }
50740
+ const worktrees = parseWorktreeRecords(await gitText(cwd, ["worktree", "list", "--porcelain"], deadline, 512 * 1024) ?? "");
50741
+ const using = agentOwnersByWorktree(worktrees, input2.agentWorktrees ?? [], cwd).get(cwd);
50742
+ if (using?.length) {
50743
+ return answer("rejected", `An agent session (${using.slice(0, 3).join(", ")}${using.length > 3 ? ` and ${using.length - 3} more` : ""}) is working in this checkout. ${input2.operation === "conflict_abort" ? "Aborting" : "Continuing"} would change files under it, so nothing was changed.`);
50744
+ }
50745
+ if (input2.operation === "conflict_abort") {
50746
+ const run2 = await runWriteGit(cwd, [GIT_COMMAND[operation], "--abort"], deadline.remaining());
50747
+ if (run2.timedOut)
50748
+ return timedOut();
50749
+ const after2 = await readHead(cwd, deadline);
50750
+ if (run2.exitCode !== 0) {
50751
+ return answer("failed", failureText(run2, cwd, `Git could not abort the ${label}.`), after2);
50752
+ }
50753
+ return answer("ok", `Aborted the ${label}. The checkout is back where it started.`, after2);
50754
+ }
50755
+ const status = await readStatus(cwd, null, deadline);
50756
+ if (!status)
50757
+ return answer("failed", "Git status could not be read on the target.");
50758
+ if (status.data.conflicted.length > 0) {
50759
+ return answer("rejected", `${plural4(status.data.conflicted.length, "file")} still ${status.data.conflicted.length === 1 ? "has" : "have"} conflicts. Mark every conflict resolved first.`);
50760
+ }
50761
+ const args = operation === "merge" ? ["commit", "--no-edit", "--quiet"] : [GIT_COMMAND[operation], "--continue"];
50762
+ const run = await runWriteGit(cwd, args, deadline.remaining());
50763
+ if (run.timedOut)
50764
+ return timedOut();
50765
+ const after = await readHead(cwd, deadline);
50766
+ if (run.exitCode !== 0) {
50767
+ const still = await operationInProgress(cwd, deadline);
50768
+ const now = still ? await readStatus(cwd, null, deadline) : null;
50769
+ if (still && now && now.data.conflicted.length > 0) {
50770
+ return answer("ok", `The ${LABELS[still]} continued and stopped at another conflict in ${plural4(now.data.conflicted.length, "file")}.`, after);
50771
+ }
50772
+ return answer("failed", failureText(run, cwd, `Git could not continue the ${label}.`), after);
50773
+ }
50774
+ if (operation === "merge") {
50775
+ if (!after.head || after.head === root.head) {
50776
+ return answer("failed", "Git did not record the merge commit.", after);
50777
+ }
50778
+ const subject = await commitSubject(cwd, after.head, deadline) ?? "Merge";
50779
+ return answer("ok", `Committed the merge ${after.head.slice(0, 8)}.`, after, {
50780
+ sha: after.head,
50781
+ subject
50782
+ });
50783
+ }
50784
+ return answer("ok", `Finished the ${label}.`, after);
50785
+ }
50786
+ function inside2(parent, child) {
50787
+ const relative = path45.relative(parent, child);
50788
+ return relative === "" || !relative.startsWith("..") && !path45.isAbsolute(relative);
50789
+ }
50790
+ function worktreeOf(worktrees, dir, realpath2 = resolveRealPath) {
50791
+ const where = realpath2(dir);
50792
+ let best = null;
50793
+ for (const worktree of worktrees) {
50794
+ const candidate = realpath2(worktree.path);
50795
+ if (inside2(candidate, where) && (best === null || candidate.length > best.length)) {
50796
+ best = candidate;
50797
+ }
50798
+ }
50799
+ return best;
50800
+ }
50801
+ function addOwner(map2, key, owner) {
50802
+ const list = map2.get(key) ?? [];
50803
+ if (list.length < OWNERS_PER_ITEM && !list.some((entry) => entry.objectiveId === owner.objectiveId)) {
50804
+ list.push(owner);
50805
+ }
50806
+ map2.set(key, list);
50807
+ }
50808
+ async function branchCreation(cwd, branch, deadline) {
50809
+ const text = await gitText(cwd, [
50810
+ "log",
50811
+ "--walk-reflogs",
50812
+ "--no-color",
50813
+ "--format=%H%x1f%gs",
50814
+ "--end-of-options",
50815
+ `refs/heads/${branch}`
50816
+ ], deadline, 1024 * 1024);
50817
+ const lines2 = (text ?? "").trim().split("\n").filter(Boolean);
50818
+ const [sha, subject] = (lines2.at(-1) ?? "").split("");
50819
+ if (!sha || !subject || !/^branch: Created from /.test(subject))
50820
+ return null;
50821
+ return shaOrNull(sha);
50822
+ }
50823
+ async function readChangeAttributionGit(input2, signal) {
50824
+ const deadline = new ReadDeadline(REPOSITORY_READ_TARGET_BOUNDS.commandTimeoutMs, signal);
50825
+ const root = await exactRoot2(input2.repoPath, deadline);
50826
+ if (!root.ok)
50827
+ return root;
50828
+ const cwd = root.realRoot;
50829
+ const candidates = input2.attribution ?? { ledger: [], branches: [] };
50830
+ const fileOwners = /* @__PURE__ */ new Map();
50831
+ const commitOwners = /* @__PURE__ */ new Map();
50832
+ const requestedPaths = new Set(input2.paths.filter((entry) => exactWritePath(entry, { folder: true })));
50833
+ if (requestedPaths.size > 0 && candidates.ledger.length > 0) {
50834
+ const [status, worktreeText, headTime] = await Promise.all([
50835
+ readStatus(cwd, null, deadline),
50836
+ gitText(cwd, ["worktree", "list", "--porcelain"], deadline, 512 * 1024),
50837
+ gitText(cwd, ["log", "-1", "--no-color", "--format=%ct", "HEAD", "--"], deadline)
50838
+ ]);
50839
+ const changed = /* @__PURE__ */ new Set();
50840
+ if (status) {
50841
+ for (const entry of [
50842
+ ...status.data.staged,
50843
+ ...status.data.unstaged,
50844
+ ...status.data.conflicted
50845
+ ]) {
50846
+ changed.add(entry.path);
50847
+ }
50848
+ for (const entry of status.data.untracked)
50849
+ changed.add(entry);
50850
+ }
50851
+ const worktrees = parseWorktreeRecords(worktreeText ?? "");
50852
+ const onlyWorktree = worktrees.length <= 1;
50853
+ const headSeconds = Number((headTime ?? "").trim()) || 0;
50854
+ for (const candidate of candidates.ledger) {
50855
+ if (!requestedPaths.has(candidate.path) || !changed.has(candidate.path))
50856
+ continue;
50857
+ const observed = Date.parse(candidate.observedAt);
50858
+ if (!Number.isFinite(observed) || observed < headSeconds * 1e3)
50859
+ continue;
50860
+ const here = candidate.workingDirectory === null ? onlyWorktree : worktreeOf(worktrees, candidate.workingDirectory) === cwd;
50861
+ if (!here)
50862
+ continue;
50863
+ addOwner(fileOwners, candidate.path, { ...candidate.owner, evidence: "change_ledger" });
50864
+ }
50865
+ }
50866
+ const requestedCommits = new Set(input2.commits.filter((sha) => isCommitId(sha) && sha.length >= 40));
50867
+ if (requestedCommits.size > 0 && candidates.branches.length > 0) {
50868
+ const byBranch = /* @__PURE__ */ new Map();
50869
+ for (const candidate of candidates.branches) {
50870
+ if (!isSafeRefName(candidate.branch))
50871
+ continue;
50872
+ const list = byBranch.get(candidate.branch) ?? [];
50873
+ list.push(candidate);
50874
+ byBranch.set(candidate.branch, list);
50875
+ }
50876
+ for (const [branch, owners] of byBranch) {
50877
+ if (deadline.remaining() <= 1)
50878
+ break;
50879
+ const tip = (await gitText(cwd, ["rev-parse", "--verify", "--quiet", "--end-of-options", `refs/heads/${branch}^{commit}`], deadline))?.trim();
50880
+ if (!tip)
50881
+ continue;
50882
+ const creation = await branchCreation(cwd, branch, deadline);
50883
+ if (!creation || creation === tip)
50884
+ continue;
50885
+ const text = await gitText(cwd, [
50886
+ "log",
50887
+ "--no-color",
50888
+ "--format=%H%x1f%ct",
50889
+ `--max-count=${BRANCH_COMMIT_LIMIT}`,
50890
+ "--end-of-options",
50891
+ tip,
50892
+ `^${creation}`,
50893
+ "--"
50894
+ ], deadline, 1024 * 1024);
50895
+ const ordered = [...owners].sort((a, b) => Date.parse(b.since) - Date.parse(a.since));
50896
+ for (const line of (text ?? "").split("\n")) {
50897
+ const [sha, seconds] = line.split("");
50898
+ if (!sha || !requestedCommits.has(sha))
50899
+ continue;
50900
+ const at = Number(seconds) * 1e3;
50901
+ const owner = ordered.find((candidate) => Date.parse(candidate.since) <= at);
50902
+ if (owner)
50903
+ addOwner(commitOwners, sha, { ...owner.owner, evidence: "mission_branch" });
50904
+ }
50905
+ }
50906
+ }
50907
+ return {
50908
+ outcome: "ok",
50909
+ head: root.head,
50910
+ branch: root.branch,
50911
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
50912
+ truncated: false,
50913
+ data: {
50914
+ files: [...fileOwners].map(([filePath, owners]) => ({ path: filePath, owners })),
50915
+ commits: [...commitOwners].map(([sha, owners]) => ({ sha, owners }))
50916
+ }
50917
+ };
50918
+ }
50919
+ var CONFLICT_OPERATIONS, CONFLICT_LIST_LIMIT, MARKER_SCAN_BYTES, MESSAGE_CHARS, PATHS_SHOWN, OWNERS_PER_ITEM, BRANCH_COMMIT_LIMIT, CONFLICT_MARKER, GIT_COMMAND, LABELS;
50920
+ var init_project_resource_conflict_git = __esm({
50921
+ "../packages/core/dist/service/local-target/project-resource-conflict-git.js"() {
50922
+ "use strict";
50923
+ init_project_history_git();
50924
+ init_project_resource_branch_git();
50925
+ init_project_resource_sync_git();
50926
+ init_project_resource_write_git();
50927
+ init_repository_read_git();
50928
+ init_worktree_git();
50929
+ CONFLICT_OPERATIONS = /* @__PURE__ */ new Set([
50930
+ "conflict_resolve",
50931
+ "conflict_abort",
50932
+ "conflict_continue"
50933
+ ]);
50934
+ CONFLICT_LIST_LIMIT = 500;
50935
+ MARKER_SCAN_BYTES = 2 * 1024 * 1024;
50936
+ MESSAGE_CHARS = 200;
50937
+ PATHS_SHOWN = 5;
50938
+ OWNERS_PER_ITEM = 10;
50939
+ BRANCH_COMMIT_LIMIT = 2e3;
50940
+ CONFLICT_MARKER = /^(?:<{7}|>{7})(?: |$)/m;
50941
+ GIT_COMMAND = {
50942
+ merge: "merge",
50943
+ rebase: "rebase",
50944
+ cherry_pick: "cherry-pick",
50945
+ revert: "revert"
50946
+ };
50947
+ LABELS = {
50948
+ merge: "merge",
50949
+ rebase: "rebase",
50950
+ cherry_pick: "cherry-pick",
50951
+ revert: "revert"
50952
+ };
50953
+ }
50954
+ });
50955
+
48971
50956
  // ../packages/core/dist/service/local-target/project-resource-read.js
48972
50957
  import { opendirSync as opendirSync2 } from "node:fs";
48973
- import path41 from "node:path";
48974
- function readResult(outcome, data = null, truncated = false) {
50958
+ import path46 from "node:path";
50959
+ function readResult(outcome2, data = null, truncated = false) {
48975
50960
  return {
48976
- outcome,
50961
+ outcome: outcome2,
48977
50962
  data,
48978
50963
  truncated,
48979
50964
  head: null,
@@ -49007,7 +50992,7 @@ function listDirectory(input2) {
49007
50992
  index += 1;
49008
50993
  if (index <= offset)
49009
50994
  continue;
49010
- const relativePath = path41.posix.join(folder.relativePath, entry.name);
50995
+ const relativePath = path46.posix.join(folder.relativePath, entry.name);
49011
50996
  const checked = normalizeRepositoryRelativePath(relativePath);
49012
50997
  if (!entry.isFile() && !entry.isDirectory() || !checked.ok || checked.relativePath !== relativePath || isSensitiveRepositoryPath(relativePath, extra) || relativePath.toLowerCase() === ".overlord/tmp")
49013
50998
  continue;
@@ -49049,6 +51034,22 @@ async function readProjectResource(input2) {
49049
51034
  return readRepositoryFileGit({ ...input2, filesystemOnly: true });
49050
51035
  case "list_directory":
49051
51036
  return listDirectory(input2);
51037
+ case "log":
51038
+ return readCommitLogGit(input2);
51039
+ case "commit":
51040
+ return readCommitGit(input2);
51041
+ case "branches":
51042
+ return readBranchesGit(input2);
51043
+ case "worktrees":
51044
+ return readWorktreesGit(input2);
51045
+ case "sync_status":
51046
+ return readSyncStatusGit(input2);
51047
+ case "publish_review":
51048
+ return readPublishReviewGit(input2);
51049
+ case "conflict_state":
51050
+ return readConflictStateGit(input2);
51051
+ case "change_attribution":
51052
+ return readChangeAttributionGit(input2);
49052
51053
  default:
49053
51054
  return readResult("unavailable");
49054
51055
  }
@@ -49058,6 +51059,10 @@ var init_project_resource_read = __esm({
49058
51059
  "../packages/core/dist/service/local-target/project-resource-read.js"() {
49059
51060
  "use strict";
49060
51061
  init_current_diff_git();
51062
+ init_project_history_git();
51063
+ init_project_resource_branch_git();
51064
+ init_project_resource_conflict_git();
51065
+ init_project_resource_sync_git();
49061
51066
  init_repository_paths();
49062
51067
  init_repository_read_git();
49063
51068
  DIRECTORY_PAGE_SIZE = 100;
@@ -49066,7 +51071,7 @@ var init_project_resource_read = __esm({
49066
51071
  });
49067
51072
 
49068
51073
  // ../packages/core/dist/service/local-target/result.js
49069
- function ok(target, value2) {
51074
+ function ok2(target, value2) {
49070
51075
  return { ok: true, value: value2, target };
49071
51076
  }
49072
51077
  function fail(target, code, message, details) {
@@ -49121,7 +51126,11 @@ var init_in_process_provider = __esm({
49121
51126
  init_doctor_checks();
49122
51127
  init_git_run();
49123
51128
  init_project_metadata();
51129
+ init_project_resource_branch_git();
51130
+ init_project_resource_conflict_git();
49124
51131
  init_project_resource_read();
51132
+ init_project_resource_sync_git();
51133
+ init_project_resource_write_git();
49125
51134
  init_repository_paths();
49126
51135
  init_repository_read_git();
49127
51136
  init_result();
@@ -49131,6 +51140,26 @@ var init_in_process_provider = __esm({
49131
51140
  readProjectResource(input2) {
49132
51141
  return this.#read(readProjectResource(input2));
49133
51142
  }
51143
+ writeProjectResource(input2) {
51144
+ if (isBranchInput(input2)) {
51145
+ return this.#read(branchProjectResourceGit(input2));
51146
+ }
51147
+ if (isSyncInput(input2)) {
51148
+ return this.#read(syncProjectResourceGit(input2));
51149
+ }
51150
+ if (isConflictInput(input2)) {
51151
+ return this.#read(conflictProjectResourceGit(input2));
51152
+ }
51153
+ switch (input2.operation) {
51154
+ case "stage":
51155
+ case "unstage":
51156
+ case "discard":
51157
+ case "commit":
51158
+ return this.#read(writeProjectResourceGit(input2));
51159
+ default:
51160
+ return Promise.resolve(fail(this.target, "LOCAL_TARGET_UNSUPPORTED", "This runner cannot make that change."));
51161
+ }
51162
+ }
49134
51163
  constructor(target) {
49135
51164
  this.target = target;
49136
51165
  }
@@ -49144,7 +51173,7 @@ var init_in_process_provider = __esm({
49144
51173
  async observeResource(input2) {
49145
51174
  const observedAt = (/* @__PURE__ */ new Date()).toISOString();
49146
51175
  const state = existsSync34(input2.path) ? "available" : "missing";
49147
- return ok(this.target, { state, observedAt });
51176
+ return ok2(this.target, { state, observedAt });
49148
51177
  }
49149
51178
  /**
49150
51179
  * Write the linked checkout's `.overlord/project.json` on this machine (WS-D 2).
@@ -49155,7 +51184,7 @@ var init_in_process_provider = __esm({
49155
51184
  async writeProjectMetadata(input2) {
49156
51185
  try {
49157
51186
  const metadataPath = writeProjectJson(input2);
49158
- return ok(this.target, { path: metadataPath, written: true });
51187
+ return ok2(this.target, { path: metadataPath, written: true });
49159
51188
  } catch (error62) {
49160
51189
  return fail(this.target, "TARGET_OPERATION_FAILED", `Failed to write project metadata: ${error62 instanceof Error ? error62.message : String(error62)}`);
49161
51190
  }
@@ -49168,7 +51197,7 @@ var init_in_process_provider = __esm({
49168
51197
  const prefix = scope.ok && scope.relativePath ? `${scope.relativePath}/` : "";
49169
51198
  const scoped = prefix ? tree.entries.filter((entry) => entry.path.startsWith(prefix) || entry.path === prefix.slice(0, -1)) : tree.entries;
49170
51199
  const limit = typeof input2.maxEntries === "number" && input2.maxEntries > 0 ? Math.floor(input2.maxEntries) : scoped.length;
49171
- return ok(this.target, {
51200
+ return ok2(this.target, {
49172
51201
  rootPath: tree.rootPath,
49173
51202
  gitRoot: tree.gitRoot,
49174
51203
  branch: tree.branch,
@@ -49190,7 +51219,7 @@ var init_in_process_provider = __esm({
49190
51219
  const local = runGit2(input2.repoPath, ["branch", "--format=%(refname:short)"]);
49191
51220
  const remote = runGit2(input2.repoPath, ["branch", "-r", "--format=%(refname:short)"]);
49192
51221
  const current = runGit2(input2.repoPath, ["branch", "--show-current"]) || null;
49193
- return ok(this.target, {
51222
+ return ok2(this.target, {
49194
51223
  local: local.split("\n").map(normalizeBranchRef).filter((name) => name && !name.includes("->") && name !== "HEAD"),
49195
51224
  remote: remote.split("\n").map(normalizeBranchRef).filter((name) => name && !name.includes("->") && name !== "HEAD"),
49196
51225
  current
@@ -49203,7 +51232,7 @@ var init_in_process_provider = __esm({
49203
51232
  async listWorktrees(input2) {
49204
51233
  try {
49205
51234
  const worktrees = collectManagedWorktrees(input2);
49206
- return ok(this.target, { worktrees });
51235
+ return ok2(this.target, { worktrees });
49207
51236
  } catch (error62) {
49208
51237
  return fail(this.target, "GIT_COMMAND_FAILED", error62 instanceof Error ? error62.message : "Could not list worktrees.");
49209
51238
  }
@@ -49218,14 +51247,14 @@ var init_in_process_provider = __esm({
49218
51247
  if (!input2.force && result.skipped.some((s) => s.reason === "uncommitted changes")) {
49219
51248
  return fail(this.target, "GIT_COMMAND_FAILED", `The worktree has uncommitted changes \u2014 removing it would lose work: ${input2.path}`, { branchActionCode: "WORKTREE_DIRTY", detail: "Re-run with force to remove it anyway." });
49220
51249
  }
49221
- return ok(this.target, result);
51250
+ return ok2(this.target, result);
49222
51251
  } catch (error62) {
49223
51252
  return fail(this.target, "GIT_COMMAND_FAILED", error62 instanceof Error ? error62.message : "Could not remove worktree.");
49224
51253
  }
49225
51254
  }
49226
51255
  async purgeMergedWorktrees(input2) {
49227
51256
  try {
49228
- return ok(this.target, purgeManagedWorktrees({ entries: mergedWorktreeEntries(input2) }));
51257
+ return ok2(this.target, purgeManagedWorktrees({ entries: mergedWorktreeEntries(input2) }));
49229
51258
  } catch (error62) {
49230
51259
  return fail(this.target, "GIT_COMMAND_FAILED", error62 instanceof Error ? error62.message : "Could not purge worktrees.");
49231
51260
  }
@@ -49233,7 +51262,7 @@ var init_in_process_provider = __esm({
49233
51262
  async performBranchAction(input2) {
49234
51263
  const result = performBranchActionGit(input2);
49235
51264
  if (result.ok)
49236
- return ok(this.target, { summary: result.summary });
51265
+ return ok2(this.target, { summary: result.summary });
49237
51266
  return fail(this.target, "GIT_COMMAND_FAILED", result.message, {
49238
51267
  branchActionCode: result.code,
49239
51268
  detail: result.detail
@@ -49248,7 +51277,7 @@ var init_in_process_provider = __esm({
49248
51277
  detail: result.detail
49249
51278
  });
49250
51279
  }
49251
- return ok(this.target, { diff: result.diff });
51280
+ return ok2(this.target, { diff: result.diff });
49252
51281
  }
49253
51282
  // ---- agent-facing repository reads (coo:1108.zg8m) --------------------
49254
51283
  /** Map a target-side read to the capability envelope; failures stay typed. */
@@ -49258,7 +51287,7 @@ var init_in_process_provider = __esm({
49258
51287
  if (failure2 && failure2.ok === false) {
49259
51288
  return fail(this.target, failure2.code, failure2.message);
49260
51289
  }
49261
- return ok(this.target, result);
51290
+ return ok2(this.target, result);
49262
51291
  }, () => fail(this.target, "TARGET_OPERATION_FAILED", "The repository read failed on the target."));
49263
51292
  }
49264
51293
  readCurrentDiff(input2) {
@@ -49295,7 +51324,7 @@ var init_in_process_provider = __esm({
49295
51324
  cacheFilePath: defaultLatchDiscoveryCachePath(),
49296
51325
  force: input2.force === true
49297
51326
  });
49298
- return ok(this.target, result);
51327
+ return ok2(this.target, result);
49299
51328
  } catch (error62) {
49300
51329
  return fail(this.target, "TARGET_OPERATION_FAILED", error62 instanceof Error ? error62.message : "Latch discovery failed on this device.");
49301
51330
  }
@@ -49303,12 +51332,12 @@ var init_in_process_provider = __esm({
49303
51332
  async readLatchHostIdentity(input2) {
49304
51333
  const identity = await readLatchHostIdentity(input2);
49305
51334
  if (identity)
49306
- return ok(this.target, identity);
51335
+ return ok2(this.target, identity);
49307
51336
  return fail(this.target, "TARGET_OPERATION_FAILED", "Latch Remote Link has no identity on this runner.");
49308
51337
  }
49309
51338
  async inspectLatchSession(input2) {
49310
51339
  try {
49311
- return ok(this.target, await inspectLatchSession(input2));
51340
+ return ok2(this.target, await inspectLatchSession(input2));
49312
51341
  } catch (error62) {
49313
51342
  return failLatchCommand({
49314
51343
  target: this.target,
@@ -49319,7 +51348,7 @@ var init_in_process_provider = __esm({
49319
51348
  }
49320
51349
  async openLatchSession(input2) {
49321
51350
  try {
49322
- return ok(this.target, await openLatchSession(input2));
51351
+ return ok2(this.target, await openLatchSession(input2));
49323
51352
  } catch (error62) {
49324
51353
  return failLatchCommand({
49325
51354
  target: this.target,
@@ -49330,7 +51359,7 @@ var init_in_process_provider = __esm({
49330
51359
  }
49331
51360
  async stopLatchSession(input2) {
49332
51361
  try {
49333
- return ok(this.target, await stopLatchSession(input2));
51362
+ return ok2(this.target, await stopLatchSession(input2));
49334
51363
  } catch (error62) {
49335
51364
  return failLatchCommand({
49336
51365
  target: this.target,
@@ -49348,7 +51377,7 @@ var init_in_process_provider = __esm({
49348
51377
  */
49349
51378
  async sendLatchMessage(input2) {
49350
51379
  try {
49351
- return ok(this.target, await sendLatchMessage({
51380
+ return ok2(this.target, await sendLatchMessage({
49352
51381
  providerSessionId: input2.providerSessionId,
49353
51382
  operationId: input2.operationId,
49354
51383
  text: input2.text,
@@ -49365,7 +51394,7 @@ var init_in_process_provider = __esm({
49365
51394
  }
49366
51395
  }
49367
51396
  async doctor() {
49368
- return ok(this.target, { checks: runLocalTargetDoctorChecks() });
51397
+ return ok2(this.target, { checks: runLocalTargetDoctorChecks() });
49369
51398
  }
49370
51399
  // ---- not yet routed (CLI-owned or future WS-D paths) -----------------
49371
51400
  prepareBranch(_input) {
@@ -49414,6 +51443,7 @@ var init_types2 = __esm({
49414
51443
  "readCurrentDiff",
49415
51444
  "readGitStatus",
49416
51445
  "readProjectResource",
51446
+ "writeProjectResource",
49417
51447
  "readRepositoryFile",
49418
51448
  "searchRepositoryText",
49419
51449
  "generateCommitMessageFromLocalDiff",
@@ -52952,7 +54982,7 @@ var require_split2 = __commonJS({
52952
54982
  var require_helper = __commonJS({
52953
54983
  "../node_modules/pgpass/lib/helper.js"(exports, module) {
52954
54984
  "use strict";
52955
- var path55 = __require("path");
54985
+ var path60 = __require("path");
52956
54986
  var Stream = __require("stream").Stream;
52957
54987
  var split = require_split2();
52958
54988
  var util = __require("util");
@@ -52991,7 +55021,7 @@ var require_helper = __commonJS({
52991
55021
  };
52992
55022
  module.exports.getFileName = function(rawEnv) {
52993
55023
  var env = rawEnv || process.env;
52994
- var file2 = env.PGPASSFILE || (isWin ? path55.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path55.join(env.HOME || "./", ".pgpass"));
55024
+ var file2 = env.PGPASSFILE || (isWin ? path60.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path60.join(env.HOME || "./", ".pgpass"));
52995
55025
  return file2;
52996
55026
  };
52997
55027
  module.exports.usePgPass = function(stats, fname) {
@@ -53123,7 +55153,7 @@ var require_helper = __commonJS({
53123
55153
  var require_lib = __commonJS({
53124
55154
  "../node_modules/pgpass/lib/index.js"(exports, module) {
53125
55155
  "use strict";
53126
- var path55 = __require("path");
55156
+ var path60 = __require("path");
53127
55157
  var fs = __require("fs");
53128
55158
  var helper = require_helper();
53129
55159
  module.exports = function(connInfo, cb) {
@@ -55155,7 +57185,7 @@ async function executeLocalTargetMutation({ mutation, provider = inProcessProvid
55155
57185
  return fail(provider.target, "LOCAL_TARGET_UNSUPPORTED", `The runner does not execute the capability "${String(capability)}".`);
55156
57186
  }
55157
57187
  let input2 = INPUT_PRE_HOOKS[capability]?.(mutation.input) ?? mutation.input;
55158
- if (capability === "readProjectResource" && !mutation.resourceKey) {
57188
+ if ((capability === "readProjectResource" || capability === "writeProjectResource") && !mutation.resourceKey) {
55159
57189
  return fail(provider.target, "RESOURCE_MISSING", "A project resource binding is required.");
55160
57190
  }
55161
57191
  if (mutation.resourceKey) {
@@ -55207,6 +57237,7 @@ var init_local_target_mutation_runner = __esm({
55207
57237
  projects: [{ primaryRepoPath: dir }]
55208
57238
  }),
55209
57239
  readProjectResource: (input2, dir) => ({ ...input2, repoPath: dir }),
57240
+ writeProjectResource: (input2, dir) => ({ ...input2, repoPath: dir }),
55210
57241
  readGitStatus: (input2, dir) => ({ ...input2, repoPath: dir }),
55211
57242
  readCurrentDiff: (input2, dir) => ({ ...input2, repoPath: dir }),
55212
57243
  readRepositoryFile: (input2, dir) => ({ ...input2, repoPath: dir }),
@@ -55273,7 +57304,7 @@ var init_objective_summary_placement = __esm({
55273
57304
  });
55274
57305
 
55275
57306
  // ../packages/core/dist/service/project-resource-key.js
55276
- import path42 from "node:path";
57307
+ import path47 from "node:path";
55277
57308
  function deriveProjectResourceKey({ resourceKey, label, directoryPath }) {
55278
57309
  const explicit = resourceKey?.trim();
55279
57310
  if (explicit)
@@ -55281,7 +57312,7 @@ function deriveProjectResourceKey({ resourceKey, label, directoryPath }) {
55281
57312
  const labelKey = label?.trim();
55282
57313
  if (labelKey)
55283
57314
  return slugify2(labelKey);
55284
- return slugify2(path42.basename(path42.resolve(directoryPath)));
57315
+ return slugify2(path47.basename(path47.resolve(directoryPath)));
55285
57316
  }
55286
57317
  var init_project_resource_key = __esm({
55287
57318
  "../packages/core/dist/service/project-resource-key.js"() {
@@ -55291,7 +57322,7 @@ var init_project_resource_key = __esm({
55291
57322
  });
55292
57323
 
55293
57324
  // src/branch-planning.ts
55294
- import path43 from "node:path";
57325
+ import path48 from "node:path";
55295
57326
  function stripCombiningMarks(value2) {
55296
57327
  return value2.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
55297
57328
  }
@@ -55324,7 +57355,7 @@ function missionWorktreePath({
55324
57355
  branch
55325
57356
  }) {
55326
57357
  const key = resourceKey.trim() || "project";
55327
- return path43.join(worktreeRoot, projectSlug || "project", key, branchLeaf(branch));
57358
+ return path48.join(worktreeRoot, projectSlug || "project", key, branchLeaf(branch));
55328
57359
  }
55329
57360
  function normalizeRemoteRef(ref) {
55330
57361
  return ref.replace(/^origin\//, "").replace(/^refs\/heads\//, "").replace(/^refs\/remotes\/origin\//, "");
@@ -55439,8 +57470,8 @@ var init_branch_planning = __esm({
55439
57470
 
55440
57471
  // src/branch-preparation.ts
55441
57472
  import { execFileSync as execFileSync6 } from "node:child_process";
55442
- import { existsSync as existsSync35, mkdirSync as mkdirSync13, statSync as statSync9 } from "node:fs";
55443
- import path44 from "node:path";
57473
+ import { existsSync as existsSync35, mkdirSync as mkdirSync13, statSync as statSync10 } from "node:fs";
57474
+ import path49 from "node:path";
55444
57475
  function runGit3(cwd, args, options = {}) {
55445
57476
  try {
55446
57477
  return execFileSync6("git", args, {
@@ -55461,7 +57492,7 @@ function lines(value2) {
55461
57492
  function resolveGitRoot2(workingDirectory) {
55462
57493
  const root = runGit3(workingDirectory, ["rev-parse", "--show-toplevel"]);
55463
57494
  if (!root) throw new Error(`${workingDirectory} is not inside a git repository.`);
55464
- return path44.resolve(root);
57495
+ return path49.resolve(root);
55465
57496
  }
55466
57497
  function repoDefaultBranch(gitRoot) {
55467
57498
  const symbolic = runGit3(gitRoot, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
@@ -55562,8 +57593,8 @@ function repoRefs(gitRoot, base) {
55562
57593
  };
55563
57594
  }
55564
57595
  function worktreeBranch(worktreePath) {
55565
- const inside = runGit3(worktreePath, ["rev-parse", "--is-inside-work-tree"], { optional: true });
55566
- if (inside !== "true") return null;
57596
+ const inside3 = runGit3(worktreePath, ["rev-parse", "--is-inside-work-tree"], { optional: true });
57597
+ if (inside3 !== "true") return null;
55567
57598
  const branch = runGit3(worktreePath, ["branch", "--show-current"], { optional: true });
55568
57599
  return branch || null;
55569
57600
  }
@@ -55621,9 +57652,9 @@ function ensureBranchRef(gitRoot, decision) {
55621
57652
  }
55622
57653
  function ensureWorktree(gitRoot, decision) {
55623
57654
  ensureBranchRef(gitRoot, decision);
55624
- mkdirSync13(path44.dirname(decision.worktreePath), { recursive: true });
57655
+ mkdirSync13(path49.dirname(decision.worktreePath), { recursive: true });
55625
57656
  if (existsSync35(decision.worktreePath)) {
55626
- if (!statSync9(decision.worktreePath).isDirectory()) {
57657
+ if (!statSync10(decision.worktreePath).isDirectory()) {
55627
57658
  throw new Error(`Worktree path exists and is not a directory: ${decision.worktreePath}`);
55628
57659
  }
55629
57660
  const existingBranch = worktreeBranch(decision.worktreePath);
@@ -55820,7 +57851,7 @@ var init_branch_preparation = __esm({
55820
57851
  });
55821
57852
 
55822
57853
  // src/discover-project-local.ts
55823
- import path45 from "node:path";
57854
+ import path50 from "node:path";
55824
57855
  async function resolvePreferredExecutionTargetId({
55825
57856
  backend,
55826
57857
  workspaceId
@@ -55839,14 +57870,14 @@ function discoverProjectJsonFromFilesystem({
55839
57870
  workingDirectory,
55840
57871
  preferredExecutionTargetId
55841
57872
  }) {
55842
- let current = path45.resolve(workingDirectory);
57873
+ let current = path50.resolve(workingDirectory);
55843
57874
  while (true) {
55844
- const projectJsonPath = path45.join(current, ".overlord", "project.json");
57875
+ const projectJsonPath = path50.join(current, ".overlord", "project.json");
55845
57876
  const links = readProjectJsonLinks(projectJsonPath, { preferredExecutionTargetId });
55846
57877
  if (links.length > 0) {
55847
57878
  return { resourcePath: current, links };
55848
57879
  }
55849
- const parent = path45.dirname(current);
57880
+ const parent = path50.dirname(current);
55850
57881
  if (parent === current) break;
55851
57882
  current = parent;
55852
57883
  }
@@ -55973,7 +58004,7 @@ async function discoverProjectOnClient({
55973
58004
  const resolvedLocal = localWithTarget ?? local;
55974
58005
  if (!resolvedLocal) {
55975
58006
  throw new CliError({
55976
- message: `No linked Overlord project found for ${path45.resolve(workingDirectory)}. Run \`ovld add-cwd\` or \`ovld create-project\`.`
58007
+ message: `No linked Overlord project found for ${path50.resolve(workingDirectory)}. Run \`ovld add-cwd\` or \`ovld create-project\`.`
55977
58008
  });
55978
58009
  }
55979
58010
  const selectedLink = selectPrimaryProjectLink(resolvedLocal.links);
@@ -55993,7 +58024,7 @@ async function discoverProjectOnClient({
55993
58024
  }
55994
58025
  if (!chosenProject || !chosenLink) {
55995
58026
  throw new CliError({
55996
- message: `No linked Overlord project found for ${path45.resolve(workingDirectory)}. Run \`ovld add-cwd\` or \`ovld create-project\`.`
58027
+ message: `No linked Overlord project found for ${path50.resolve(workingDirectory)}. Run \`ovld add-cwd\` or \`ovld create-project\`.`
55997
58028
  });
55998
58029
  }
55999
58030
  const accessible = resolvedLocal.links.length > 1 ? await listAccessibleProjects({ backend }) : [chosenProject];
@@ -56023,8 +58054,8 @@ var init_discover_project_local = __esm({
56023
58054
 
56024
58055
  // src/hook-event.ts
56025
58056
  import { createHash as createHash17 } from "node:crypto";
56026
- import { statSync as statSync10 } from "node:fs";
56027
- import path46 from "node:path";
58057
+ import { statSync as statSync11 } from "node:fs";
58058
+ import path51 from "node:path";
56028
58059
  function isNativeHookType(value2) {
56029
58060
  return value2 !== null && NATIVE_HOOK_TYPES.includes(value2);
56030
58061
  }
@@ -56058,9 +58089,9 @@ function isPerInvocationPromptEvent(rule) {
56058
58089
  function payloadWorkingDirectory(codec2, payload) {
56059
58090
  for (const rootPath of codec2.projectRootPaths ?? []) {
56060
58091
  const value2 = readPath2(payload, rootPath);
56061
- if (typeof value2 !== "string" || !path46.isAbsolute(value2) || value2.length > 4096) continue;
58092
+ if (typeof value2 !== "string" || !path51.isAbsolute(value2) || value2.length > 4096) continue;
56062
58093
  try {
56063
- if (statSync10(value2).isDirectory()) return path46.resolve(value2);
58094
+ if (statSync11(value2).isDirectory()) return path51.resolve(value2);
56064
58095
  } catch {
56065
58096
  }
56066
58097
  }
@@ -56305,9 +58336,9 @@ var init_launch_process = __esm({
56305
58336
  });
56306
58337
 
56307
58338
  // src/claude-decision-hook.ts
56308
- import { existsSync as existsSync36, readFileSync as readFileSync25 } from "node:fs";
58339
+ import { existsSync as existsSync36, readFileSync as readFileSync26 } from "node:fs";
56309
58340
  import os9 from "node:os";
56310
- import path47 from "node:path";
58341
+ import path52 from "node:path";
56311
58342
  function claudeDecisionHookSettings() {
56312
58343
  return {
56313
58344
  hooks: {
@@ -56344,7 +58375,7 @@ function claudeConfigDir({
56344
58375
  home = os9.homedir()
56345
58376
  } = {}) {
56346
58377
  const override = env.CLAUDE_CONFIG_DIR?.trim();
56347
- return override ? path47.resolve(override) : path47.join(home, ".claude");
58378
+ return override ? path52.resolve(override) : path52.join(home, ".claude");
56348
58379
  }
56349
58380
  function claudeDecisionHookAvailability({
56350
58381
  configDir,
@@ -56359,17 +58390,17 @@ function claudeDecisionHookAvailability({
56359
58390
  let installPath = null;
56360
58391
  try {
56361
58392
  const state = JSON.parse(
56362
- readFileSync25(path47.join(ovldHome, ".ovld", "connectors", "claude.json"), "utf8")
58393
+ readFileSync26(path52.join(ovldHome, ".ovld", "connectors", "claude.json"), "utf8")
56363
58394
  );
56364
58395
  installPath = typeof state.installPath === "string" ? state.installPath : null;
56365
58396
  } catch {
56366
58397
  installPath = null;
56367
58398
  }
56368
- const mcpConfigPath = installPath ? path47.join(installPath, ".mcp.json") : null;
58399
+ const mcpConfigPath = installPath ? path52.join(installPath, ".mcp.json") : null;
56369
58400
  let declaresServer = false;
56370
58401
  if (mcpConfigPath && existsSync36(mcpConfigPath)) {
56371
58402
  try {
56372
- const config2 = JSON.parse(readFileSync25(mcpConfigPath, "utf8"));
58403
+ const config2 = JSON.parse(readFileSync26(mcpConfigPath, "utf8"));
56373
58404
  declaresServer = Boolean(config2.mcpServers?.["overlord-hooks"]);
56374
58405
  } catch {
56375
58406
  declaresServer = false;
@@ -56423,10 +58454,10 @@ function primaryResourcePath(projectResources) {
56423
58454
  for (const entry of projectResources) {
56424
58455
  if (!entry || typeof entry !== "object") continue;
56425
58456
  const record2 = entry;
56426
- const path55 = typeof record2.path === "string" ? record2.path.trim() : "";
56427
- if (!path55) continue;
56428
- if (record2.isPrimary === true) return path55;
56429
- if (record2.isCurrent === true && !currentPath) currentPath = path55;
58457
+ const path60 = typeof record2.path === "string" ? record2.path.trim() : "";
58458
+ if (!path60) continue;
58459
+ if (record2.isPrimary === true) return path60;
58460
+ if (record2.isCurrent === true && !currentPath) currentPath = path60;
56430
58461
  }
56431
58462
  return currentPath;
56432
58463
  }
@@ -56471,7 +58502,7 @@ var init_pre_launch = __esm({
56471
58502
  // src/launch.ts
56472
58503
  import { spawnSync as spawnSync9 } from "node:child_process";
56473
58504
  import { chmodSync as chmodSync8, writeFileSync as writeFileSync14 } from "node:fs";
56474
- import path48 from "node:path";
58505
+ import path53 from "node:path";
56475
58506
  async function defaultCodexLiveModels({ cwd }) {
56476
58507
  const codex = resolveCodexBinary();
56477
58508
  if (!codex) return null;
@@ -56702,7 +58733,7 @@ function launchScriptPath({
56702
58733
  executionRequestId
56703
58734
  }) {
56704
58735
  const requestPart = executionRequestId ? safeLaunchScriptPart(executionRequestId) : `${process.pid}`;
56705
- return path48.join(tmpDir, `launch-${safeLaunchScriptPart(displayId)}-${requestPart}.sh`);
58736
+ return path53.join(tmpDir, `launch-${safeLaunchScriptPart(displayId)}-${requestPart}.sh`);
56706
58737
  }
56707
58738
  async function buildLaunchPlan({
56708
58739
  runtime,
@@ -56718,8 +58749,8 @@ async function buildLaunchPlan({
56718
58749
  const tmpDir = ensureProjectTmpDir(options.workingDirectory);
56719
58750
  ensureHarnessTmpDir(options.workingDirectory);
56720
58751
  const contextFileStem = context.objectiveDisplayId ? `objective-${context.objectiveDisplayId.replace(/[^a-zA-Z0-9_-]/g, "-")}` : `mission-${context.displayId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
56721
- const contextFile = path48.join(tmpDir, `${contextFileStem}.md`);
56722
- const sessionScratchDir = path48.join(
58752
+ const contextFile = path53.join(tmpDir, `${contextFileStem}.md`);
58753
+ const sessionScratchDir = path53.join(
56723
58754
  projectTmpSessionsDir(options.workingDirectory),
56724
58755
  sessionScratchName({
56725
58756
  missionDisplayId: context.displayId,
@@ -56850,7 +58881,7 @@ async function buildLaunchPlan({
56850
58881
  })
56851
58882
  ]
56852
58883
  },
56853
- logFile: path48.join(sessionScratchDir, "codex-app-server.log"),
58884
+ logFile: path53.join(sessionScratchDir, "codex-app-server.log"),
56854
58885
  preLaunchCommands,
56855
58886
  threadSettings
56856
58887
  };
@@ -57130,8 +59161,8 @@ var init_launch3 = __esm({
57130
59161
  });
57131
59162
 
57132
59163
  // src/launch-bootstrap.ts
57133
- import { existsSync as existsSync37, readdirSync as readdirSync7, readFileSync as readFileSync26, statSync as statSync11 } from "node:fs";
57134
- import path49 from "node:path";
59164
+ import { existsSync as existsSync37, readdirSync as readdirSync7, readFileSync as readFileSync27, statSync as statSync12 } from "node:fs";
59165
+ import path54 from "node:path";
57135
59166
  function firstCapture(match) {
57136
59167
  if (!match) return null;
57137
59168
  const value2 = match[1] ?? match[2] ?? match[3] ?? null;
@@ -57159,9 +59190,9 @@ function recoverLaunchBootstrapFromProjectTmp({
57159
59190
  try {
57160
59191
  for (const name of readdirSync7(tmpDir)) {
57161
59192
  if (!name.startsWith(prefix) || !name.endsWith(".sh")) continue;
57162
- const filePath = path49.join(tmpDir, name);
59193
+ const filePath = path54.join(tmpDir, name);
57163
59194
  try {
57164
- const mtimeMs = statSync11(filePath).mtimeMs;
59195
+ const mtimeMs = statSync12(filePath).mtimeMs;
57165
59196
  if (!newest || mtimeMs > newest.mtimeMs) {
57166
59197
  newest = { path: filePath, mtimeMs };
57167
59198
  }
@@ -57174,7 +59205,7 @@ function recoverLaunchBootstrapFromProjectTmp({
57174
59205
  if (!newest) return empty;
57175
59206
  let contents = "";
57176
59207
  try {
57177
- contents = readFileSync26(newest.path, "utf8");
59208
+ contents = readFileSync27(newest.path, "utf8");
57178
59209
  } catch {
57179
59210
  return empty;
57180
59211
  }
@@ -57312,13 +59343,13 @@ import {
57312
59343
  existsSync as existsSync38,
57313
59344
  mkdirSync as mkdirSync14,
57314
59345
  readdirSync as readdirSync8,
57315
- readFileSync as readFileSync27,
59346
+ readFileSync as readFileSync28,
57316
59347
  renameSync as renameSync6,
57317
59348
  rmSync as rmSync11,
57318
- statSync as statSync12,
59349
+ statSync as statSync13,
57319
59350
  writeFileSync as writeFileSync15
57320
59351
  } from "node:fs";
57321
- import path50 from "node:path";
59352
+ import path55 from "node:path";
57322
59353
  function attemptKindFor(subcommand) {
57323
59354
  if (subcommand === "deliver") return "deliver";
57324
59355
  if (subcommand === "record-work") return "record_work";
@@ -57326,7 +59357,7 @@ function attemptKindFor(subcommand) {
57326
59357
  return null;
57327
59358
  }
57328
59359
  function attemptsDirectory() {
57329
- return path50.join(resolveGlobalDataDir(), "operation-attempts");
59360
+ return path55.join(resolveGlobalDataDir(), "operation-attempts");
57330
59361
  }
57331
59362
  function sha2562(value2) {
57332
59363
  return createHash18("sha256").update(value2).digest("hex");
@@ -57371,7 +59402,7 @@ function attemptScopeDigest({
57371
59402
  )}`;
57372
59403
  }
57373
59404
  function recordPath(operationId) {
57374
- return path50.join(attemptsDirectory(), `${sha2562(operationId).slice(0, 32)}.json`);
59405
+ return path55.join(attemptsDirectory(), `${sha2562(operationId).slice(0, 32)}.json`);
57375
59406
  }
57376
59407
  function ensureDirectory() {
57377
59408
  const dir = attemptsDirectory();
@@ -57380,7 +59411,7 @@ function ensureDirectory() {
57380
59411
  }
57381
59412
  function readAttempt(operationId) {
57382
59413
  try {
57383
- const parsed = JSON.parse(readFileSync27(recordPath(operationId), "utf8"));
59414
+ const parsed = JSON.parse(readFileSync28(recordPath(operationId), "utf8"));
57384
59415
  return parsed.version === 1 && parsed.operationId === operationId ? parsed : null;
57385
59416
  } catch {
57386
59417
  return null;
@@ -57414,13 +59445,13 @@ function listAttempts() {
57414
59445
  const cutoff = Date.now() - ATTEMPT_RETENTION_MS;
57415
59446
  for (const entry of entries) {
57416
59447
  if (!entry.endsWith(".json")) continue;
57417
- const file2 = path50.join(dir, entry);
59448
+ const file2 = path55.join(dir, entry);
57418
59449
  try {
57419
- if (statSync12(file2).mtimeMs < cutoff) {
59450
+ if (statSync13(file2).mtimeMs < cutoff) {
57420
59451
  rmSync11(file2, { force: true });
57421
59452
  continue;
57422
59453
  }
57423
- const record2 = JSON.parse(readFileSync27(file2, "utf8"));
59454
+ const record2 = JSON.parse(readFileSync28(file2, "utf8"));
57424
59455
  if (record2.version === 1) records.push(record2);
57425
59456
  } catch {
57426
59457
  }
@@ -57600,8 +59631,8 @@ var init_operation_attempts = __esm({
57600
59631
  });
57601
59632
 
57602
59633
  // src/org-setup.ts
57603
- import { readFileSync as readFileSync28 } from "node:fs";
57604
- import path51 from "node:path";
59634
+ import { readFileSync as readFileSync29 } from "node:fs";
59635
+ import path56 from "node:path";
57605
59636
  import { createInterface } from "node:readline";
57606
59637
  function suggestSlug(name) {
57607
59638
  const cleaned = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -57680,12 +59711,12 @@ async function runOrgSetupCommand({
57680
59711
  let logoWarning = null;
57681
59712
  if (logoPath) {
57682
59713
  try {
57683
- const resolvedPath = path51.resolve(logoPath);
57684
- const bytes = readFileSync28(resolvedPath);
59714
+ const resolvedPath = path56.resolve(logoPath);
59715
+ const bytes = readFileSync29(resolvedPath);
57685
59716
  const stored = await runtime.backend.postRaw({
57686
59717
  path: "/api/uploads/organization-images",
57687
59718
  body: bytes,
57688
- filename: path51.basename(resolvedPath)
59719
+ filename: path56.basename(resolvedPath)
57689
59720
  });
57690
59721
  await runtime.backend.patch({
57691
59722
  path: `/api/organizations/${encodeURIComponent(organization.id)}`,
@@ -59127,15 +61158,15 @@ var init_resource_observations = __esm({
59127
61158
 
59128
61159
  // src/runner-identity.ts
59129
61160
  import { randomUUID as randomUUID4 } from "node:crypto";
59130
- import { existsSync as existsSync39, mkdirSync as mkdirSync15, readFileSync as readFileSync29, writeFileSync as writeFileSync16 } from "node:fs";
61161
+ import { existsSync as existsSync39, mkdirSync as mkdirSync15, readFileSync as readFileSync30, writeFileSync as writeFileSync16 } from "node:fs";
59131
61162
  import { hostname as hostname6 } from "node:os";
59132
- import path52 from "node:path";
61163
+ import path57 from "node:path";
59133
61164
  function envValue(name) {
59134
61165
  const value2 = process.env[name]?.trim();
59135
61166
  return value2 && value2.length > 0 ? value2 : null;
59136
61167
  }
59137
61168
  function runnerInstanceStatePath(dataDir = resolveGlobalDataDir()) {
59138
- return path52.join(dataDir, RUNNER_INSTANCE_STATE_FILENAME);
61169
+ return path57.join(dataDir, RUNNER_INSTANCE_STATE_FILENAME);
59139
61170
  }
59140
61171
  function resolveRunnerInstanceId(dataDir = resolveGlobalDataDir()) {
59141
61172
  const pinned = envValue("OVERLORD_RUNNER_INSTANCE_ID");
@@ -59143,7 +61174,7 @@ function resolveRunnerInstanceId(dataDir = resolveGlobalDataDir()) {
59143
61174
  const statePath = runnerInstanceStatePath(dataDir);
59144
61175
  if (existsSync39(statePath)) {
59145
61176
  try {
59146
- const parsed = JSON.parse(readFileSync29(statePath, "utf8"));
61177
+ const parsed = JSON.parse(readFileSync30(statePath, "utf8"));
59147
61178
  if (typeof parsed.runnerInstanceId === "string" && parsed.runnerInstanceId.trim()) {
59148
61179
  return parsed.runnerInstanceId.trim();
59149
61180
  }
@@ -59152,7 +61183,7 @@ function resolveRunnerInstanceId(dataDir = resolveGlobalDataDir()) {
59152
61183
  }
59153
61184
  const runnerInstanceId = randomUUID4();
59154
61185
  try {
59155
- mkdirSync15(path52.dirname(statePath), { recursive: true });
61186
+ mkdirSync15(path57.dirname(statePath), { recursive: true });
59156
61187
  writeFileSync16(statePath, `${JSON.stringify({ runnerInstanceId }, null, 2)}
59157
61188
  `, { mode: 384 });
59158
61189
  } catch {
@@ -59180,7 +61211,13 @@ function runnerRegistrationPayload(dataDir = resolveGlobalDataDir()) {
59180
61211
  ...relationEnv ? { runnerRelation: relationEnv } : {},
59181
61212
  runnerLabel: envValue("OVERLORD_DEVICE_LABEL") ?? hostname6(),
59182
61213
  runnerVersion: getCliVersion(),
59183
- capabilities: { [PROJECT_RESOURCE_READ_CAPABILITY]: true }
61214
+ capabilities: {
61215
+ [PROJECT_RESOURCE_READ_CAPABILITY]: true,
61216
+ [PROJECT_RESOURCE_WRITE_CAPABILITY]: true,
61217
+ [PROJECT_RESOURCE_SYNC_CAPABILITY]: true,
61218
+ [PROJECT_RESOURCE_BRANCH_CAPABILITY]: true,
61219
+ [PROJECT_RESOURCE_CONFLICT_CAPABILITY]: true
61220
+ }
59184
61221
  };
59185
61222
  }
59186
61223
  var RUNNER_INSTANCE_STATE_FILENAME;
@@ -59201,22 +61238,22 @@ import {
59201
61238
  chmodSync as chmodSync10,
59202
61239
  existsSync as existsSync40,
59203
61240
  mkdirSync as mkdirSync16,
59204
- readFileSync as readFileSync30,
61241
+ readFileSync as readFileSync31,
59205
61242
  rmSync as rmSync12,
59206
- statSync as statSync13,
61243
+ statSync as statSync14,
59207
61244
  writeFileSync as writeFileSync17
59208
61245
  } from "node:fs";
59209
61246
  import os10 from "node:os";
59210
- import path53 from "node:path";
61247
+ import path58 from "node:path";
59211
61248
  import { promisify as promisify2 } from "node:util";
59212
61249
  function writeServiceFile(filePath, contents) {
59213
61250
  writeFileSync17(filePath, contents, { mode: 384 });
59214
61251
  chmodSync10(filePath, 384);
59215
61252
  }
59216
61253
  function resolveRunnerEntryScript(argv = process.argv) {
59217
- return argv[1] ? path53.resolve(argv[1]) : null;
61254
+ return argv[1] ? path58.resolve(argv[1]) : null;
59218
61255
  }
59219
- function readRunnerExecutableFileIdentity(filePath, stat2 = statSync13) {
61256
+ function readRunnerExecutableFileIdentity(filePath, stat2 = statSync14) {
59220
61257
  try {
59221
61258
  const metadata = stat2(filePath);
59222
61259
  return { dev: metadata.dev, ino: metadata.ino, mtimeMs: metadata.mtimeMs };
@@ -59227,7 +61264,7 @@ function readRunnerExecutableFileIdentity(filePath, stat2 = statSync13) {
59227
61264
  function captureRunnerSupervisorIdentity({
59228
61265
  execPath = process.execPath,
59229
61266
  entryScript = resolveRunnerEntryScript(),
59230
- stat: stat2 = statSync13
61267
+ stat: stat2 = statSync14
59231
61268
  } = {}) {
59232
61269
  return {
59233
61270
  program: readRunnerExecutableFileIdentity(execPath, stat2),
@@ -59261,13 +61298,13 @@ function emptyRunnerServiceState() {
59261
61298
  };
59262
61299
  }
59263
61300
  function runnerServiceStatePath(dataDir = resolveGlobalDataDir()) {
59264
- return path53.join(dataDir, RUNNER_SERVICE_STATE_FILENAME);
61301
+ return path58.join(dataDir, RUNNER_SERVICE_STATE_FILENAME);
59265
61302
  }
59266
61303
  function readRunnerServiceState(dataDir = resolveGlobalDataDir()) {
59267
61304
  const filePath = runnerServiceStatePath(dataDir);
59268
61305
  if (!existsSync40(filePath)) return emptyRunnerServiceState();
59269
61306
  try {
59270
- const parsed = JSON.parse(readFileSync30(filePath, "utf8"));
61307
+ const parsed = JSON.parse(readFileSync31(filePath, "utf8"));
59271
61308
  return { ...emptyRunnerServiceState(), ...parsed };
59272
61309
  } catch {
59273
61310
  return emptyRunnerServiceState();
@@ -59289,17 +61326,17 @@ function applyPollJitter(intervalMs, random = Math.random) {
59289
61326
  }
59290
61327
  function resolveOverlordAppInvocation({
59291
61328
  platform: platform2 = process.platform,
59292
- homedir: homedir2 = os10.homedir(),
61329
+ homedir: homedir3 = os10.homedir(),
59293
61330
  exists = existsSync40
59294
61331
  } = {}) {
59295
61332
  if (platform2 !== "darwin") return null;
59296
61333
  const appDirs = [
59297
61334
  "/Applications/Overlord.app",
59298
- path53.join(homedir2, "Applications", "Overlord.app")
61335
+ path58.join(homedir3, "Applications", "Overlord.app")
59299
61336
  ];
59300
61337
  for (const appDir of appDirs) {
59301
- const program = path53.join(appDir, "Contents", "MacOS", "Overlord");
59302
- const script = path53.join(appDir, "Contents", "Resources", "cli", "bin", "ovld.mjs");
61338
+ const program = path58.join(appDir, "Contents", "MacOS", "Overlord");
61339
+ const script = path58.join(appDir, "Contents", "Resources", "cli", "bin", "ovld.mjs");
59303
61340
  if (exists(program) && exists(script)) {
59304
61341
  return { program, args: [script, "runner", "supervise"], runAsElectronNode: true };
59305
61342
  }
@@ -59311,7 +61348,7 @@ function resolveOvldInvocation(argv = process.argv, execPath = process.execPath)
59311
61348
  if (override) {
59312
61349
  return { program: override, args: ["runner", "supervise"] };
59313
61350
  }
59314
- const scriptPath = argv[1] ? path53.resolve(argv[1]) : "";
61351
+ const scriptPath = argv[1] ? path58.resolve(argv[1]) : "";
59315
61352
  if (process.env.ELECTRON_RUN_AS_NODE) {
59316
61353
  return scriptPath ? { program: execPath, args: [scriptPath, "runner", "supervise"], runAsElectronNode: true } : { program: execPath, args: ["runner", "supervise"], runAsElectronNode: true };
59317
61354
  }
@@ -59325,7 +61362,7 @@ function resolveOvldInvocation(argv = process.argv, execPath = process.execPath)
59325
61362
  function composeRunnerServicePath({
59326
61363
  homeDir = os10.homedir()
59327
61364
  } = {}) {
59328
- const localBin = path53.join(homeDir, ".local", "bin");
61365
+ const localBin = path58.join(homeDir, ".local", "bin");
59329
61366
  const dirs = [...RUNNER_SERVICE_PATH_PREFIX_DIRS, localBin, ...RUNNER_SERVICE_SYSTEM_PATH_DIRS];
59330
61367
  return [...new Set(dirs)].join(":");
59331
61368
  }
@@ -59340,7 +61377,7 @@ function parseLaunchdEnvPath(plist) {
59340
61377
  function inspectInstalledLaunchdPlist(plistPath) {
59341
61378
  if (!existsSync40(plistPath)) return { processType: null, path: null };
59342
61379
  try {
59343
- const plist = readFileSync30(plistPath, "utf8");
61380
+ const plist = readFileSync31(plistPath, "utf8");
59344
61381
  return {
59345
61382
  processType: parseLaunchdProcessType(plist),
59346
61383
  path: parseLaunchdEnvPath(plist)
@@ -59353,7 +61390,7 @@ function runnerServiceReinstallHint({
59353
61390
  installed,
59354
61391
  publisher,
59355
61392
  processType,
59356
- path: path55
61393
+ path: path60
59357
61394
  }) {
59358
61395
  if (!installed) return null;
59359
61396
  const hints = [];
@@ -59367,7 +61404,7 @@ function runnerServiceReinstallHint({
59367
61404
  `This LaunchAgent is ProcessType=${processType}. App auto-update respawns the supervisor but does not rewrite ProcessType, so Apple Events to Terminal/iTerm stay App-Napped. Reinstall with \`ovld runner service install\` (or Desktop \u2192 Reinstall service) to switch to ${LAUNCHD_PROCESS_TYPE}.`
59368
61405
  );
59369
61406
  }
59370
- if (path55 !== void 0 && path55 !== composeRunnerServicePath()) {
61407
+ if (path60 !== void 0 && path60 !== composeRunnerServicePath()) {
59371
61408
  hints.push(
59372
61409
  "This LaunchAgent PATH is not the deterministic prefix (`/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin` plus system dirs). App auto-update respawns the supervisor but does not rewrite PATH, so Latch/`open`/agent binaries spawned by the service may be missing. Reinstall with `ovld runner service install` (or Desktop \u2192 Reinstall service) to apply it."
59373
61410
  );
@@ -59385,7 +61422,7 @@ function buildRunnerServiceEnv({
59385
61422
  };
59386
61423
  if (!isLoopbackBackendUrl(backendUrl)) env.OVERLORD_BACKEND_URL = backendUrl;
59387
61424
  const home = overlordHome?.trim() || process.env.OVLD_HOME?.trim();
59388
- if (home) env.OVLD_HOME = path53.resolve(home);
61425
+ if (home) env.OVLD_HOME = path58.resolve(home);
59389
61426
  const token = process.env.OVERLORD_USER_TOKEN?.trim() || process.env.OVLD_USER_TOKEN?.trim();
59390
61427
  if (token) env.OVERLORD_USER_TOKEN = token;
59391
61428
  if (runAsElectronNode || process.env.ELECTRON_RUN_AS_NODE) env.ELECTRON_RUN_AS_NODE = "1";
@@ -59424,9 +61461,9 @@ ${envEntries}
59424
61461
  <key>KeepAlive</key>
59425
61462
  <true/>
59426
61463
  <key>StandardOutPath</key>
59427
- <string>${xmlEscape(path53.join(logDir, "runner-service.out.log"))}</string>
61464
+ <string>${xmlEscape(path58.join(logDir, "runner-service.out.log"))}</string>
59428
61465
  <key>StandardErrorPath</key>
59429
- <string>${xmlEscape(path53.join(logDir, "runner-service.err.log"))}</string>
61466
+ <string>${xmlEscape(path58.join(logDir, "runner-service.err.log"))}</string>
59430
61467
  <key>ProcessType</key>
59431
61468
  <string>${LAUNCHD_PROCESS_TYPE}</string>
59432
61469
  </dict>
@@ -59457,12 +61494,12 @@ WantedBy=default.target
59457
61494
  `;
59458
61495
  }
59459
61496
  function launchAgentsDir() {
59460
- return path53.join(os10.homedir(), "Library", "LaunchAgents");
61497
+ return path58.join(os10.homedir(), "Library", "LaunchAgents");
59461
61498
  }
59462
61499
  function systemdUserDir() {
59463
61500
  const xdg = process.env.XDG_CONFIG_HOME?.trim();
59464
- const base = xdg ? path53.resolve(xdg) : path53.join(os10.homedir(), ".config");
59465
- return path53.join(base, "systemd", "user");
61501
+ const base = xdg ? path58.resolve(xdg) : path58.join(os10.homedir(), ".config");
61502
+ return path58.join(base, "systemd", "user");
59466
61503
  }
59467
61504
  async function runCommand(program, args) {
59468
61505
  const { stdout } = await execFileAsync2(program, args);
@@ -59514,7 +61551,7 @@ var init_runner_service = __esm({
59514
61551
  this.exec = exec ?? ((args) => runCommand("launchctl", args));
59515
61552
  }
59516
61553
  unitPath() {
59517
- return path53.join(launchAgentsDir(), `${LAUNCHD_LABEL}.plist`);
61554
+ return path58.join(launchAgentsDir(), `${LAUNCHD_LABEL}.plist`);
59518
61555
  }
59519
61556
  uid() {
59520
61557
  return process.getuid?.() ?? "";
@@ -59542,12 +61579,12 @@ var init_runner_service = __esm({
59542
61579
  label: LAUNCHD_LABEL,
59543
61580
  invocation: opts.invocation,
59544
61581
  env: opts.env,
59545
- logDir: path53.join(resolveGlobalDataDir(), "logs")
61582
+ logDir: path58.join(resolveGlobalDataDir(), "logs")
59546
61583
  });
59547
61584
  }
59548
61585
  async install(opts) {
59549
61586
  mkdirSync16(launchAgentsDir(), { recursive: true });
59550
- mkdirSync16(path53.join(resolveGlobalDataDir(), "logs"), { recursive: true });
61587
+ mkdirSync16(path58.join(resolveGlobalDataDir(), "logs"), { recursive: true });
59551
61588
  await this.runSteps(planLaunchdUnloadCommands({ uid: this.uid() }));
59552
61589
  writeServiceFile(this.unitPath(), this.render(opts));
59553
61590
  if (opts.autoStart) await this.start();
@@ -59588,7 +61625,7 @@ var init_runner_service = __esm({
59588
61625
  kind = "systemd";
59589
61626
  identifier = `${SYSTEMD_UNIT_NAME}.service`;
59590
61627
  unitPath() {
59591
- return path53.join(systemdUserDir(), `${SYSTEMD_UNIT_NAME}.service`);
61628
+ return path58.join(systemdUserDir(), `${SYSTEMD_UNIT_NAME}.service`);
59592
61629
  }
59593
61630
  render(opts) {
59594
61631
  return renderSystemdUnit(opts);
@@ -59702,8 +61739,8 @@ __export(commands_exports, {
59702
61739
  sanitizeRunnerFailureMessage: () => sanitizeRunnerFailureMessage,
59703
61740
  shouldRefuseInlineRunnerLaunch: () => shouldRefuseInlineRunnerLaunch
59704
61741
  });
59705
- import { readFileSync as readFileSync31, writeFileSync as writeFileSync18 } from "node:fs";
59706
- import path54 from "node:path";
61742
+ import { readFileSync as readFileSync32, writeFileSync as writeFileSync18 } from "node:fs";
61743
+ import path59 from "node:path";
59707
61744
  function resourceAccessModeBody(value2) {
59708
61745
  if (typeof value2 !== "string") return {};
59709
61746
  const normalized = value2.trim().toLowerCase();
@@ -59792,7 +61829,7 @@ function deliveredBriefingPath({
59792
61829
  const displayId = objectiveAliases.find((alias) => OBJECTIVE_DISPLAY_ID_RE.test(alias.trim()));
59793
61830
  const stem = displayId ? `objective-${safeTmpNamePart(displayId.trim())}` : missionId.includes(":") && !missionId.includes(".") ? `mission-${safeTmpNamePart(missionId.trim())}` : null;
59794
61831
  if (!stem) return null;
59795
- const candidate = path54.join(projectTmpDir(workingDirectory), `${stem}.md`);
61832
+ const candidate = path59.join(projectTmpDir(workingDirectory), `${stem}.md`);
59796
61833
  return isSessionScratchDir(workingDirectory, candidate) ? null : candidate;
59797
61834
  }
59798
61835
  async function syncObjectiveLedger({
@@ -59838,8 +61875,8 @@ async function syncObjectiveLedger({
59838
61875
  changes.map((change) => [changeEvidenceIdentityKey(change), change])
59839
61876
  );
59840
61877
  const accepted = new Map(
59841
- Array.isArray(outcomes) ? outcomes.flatMap((outcome) => {
59842
- const record2 = asRecord5(outcome);
61878
+ Array.isArray(outcomes) ? outcomes.flatMap((outcome2) => {
61879
+ const record2 = asRecord5(outcome2);
59843
61880
  if (record2.status !== "accepted" && record2.status !== "ignored" || typeof record2.idempotencyKey !== "string" || typeof record2.filePath !== "string") {
59844
61881
  return [];
59845
61882
  }
@@ -60148,7 +62185,7 @@ async function appendDeclaredOutputPaths({
60148
62185
  const outcomes = Array.isArray(response.outcomes) ? response.outcomes.map(asRecord5) : [];
60149
62186
  if (batch.some(
60150
62187
  (entry) => !outcomes.some(
60151
- (outcome) => outcome.idempotencyKey === entry.idempotencyKey && outcome.filePath === entry.filePath && (outcome.status === "accepted" || outcome.status === "ignored")
62188
+ (outcome2) => outcome2.idempotencyKey === entry.idempotencyKey && outcome2.filePath === entry.filePath && (outcome2.status === "accepted" || outcome2.status === "ignored")
60152
62189
  )
60153
62190
  )) {
60154
62191
  console.error(
@@ -60190,7 +62227,7 @@ async function resolveProtocolFileInputs({
60190
62227
  } else if (process.stdin.isTTY) {
60191
62228
  stdinContent = "";
60192
62229
  } else {
60193
- stdinContent = readFileSync31(0, "utf8");
62230
+ stdinContent = readFileSync32(0, "utf8");
60194
62231
  }
60195
62232
  return stdinContent;
60196
62233
  };
@@ -60202,7 +62239,7 @@ async function resolveProtocolFileInputs({
60202
62239
  const content = readStdinOnce();
60203
62240
  fileInputs[flagName] = content;
60204
62241
  } else {
60205
- fileInputs[flagName] = readFileSync31(filePath, "utf8");
62242
+ fileInputs[flagName] = readFileSync32(filePath, "utf8");
60206
62243
  }
60207
62244
  }
60208
62245
  return { fileInputs };
@@ -60452,7 +62489,7 @@ Run \`${primaryCommand} protocol help\` for usage.`
60452
62489
  };
60453
62490
  }
60454
62491
  const scratchDir = process.env.OVERLORD_TMPDIR?.trim();
60455
- const inheritedScratchName = scratchDir && isSessionScratchDir(workingDirectory, scratchDir) ? path54.basename(scratchDir) : void 0;
62492
+ const inheritedScratchName = scratchDir && isSessionScratchDir(workingDirectory, scratchDir) ? path59.basename(scratchDir) : void 0;
60456
62493
  if (scratchDir && inheritedScratchName && subcommand === "resume-follow-up") {
60457
62494
  ensureHarnessScratchDir(workingDirectory, scratchDir);
60458
62495
  }
@@ -60555,8 +62592,8 @@ Run \`${primaryCommand} protocol help\` for usage.`
60555
62592
  const outcomes = asRecord5(resultRecord).outcomes;
60556
62593
  if (Array.isArray(outcomes)) {
60557
62594
  const accepted = new Map(
60558
- outcomes.flatMap((outcome) => {
60559
- const record2 = asRecord5(outcome);
62595
+ outcomes.flatMap((outcome2) => {
62596
+ const record2 = asRecord5(outcome2);
60560
62597
  if (record2.status !== "accepted" && record2.status !== "ignored" || typeof record2.idempotencyKey !== "string" || typeof record2.filePath !== "string") {
60561
62598
  return [];
60562
62599
  }
@@ -60786,7 +62823,7 @@ async function runManagementCommand({
60786
62823
  }
60787
62824
  case "add-cwd": {
60788
62825
  const directory = flagValue(parsed.flags, "--directory") ?? process.cwd();
60789
- const existingLinks = readProjectJsonLinks(path54.join(directory, ".overlord", "project.json"));
62826
+ const existingLinks = readProjectJsonLinks(path59.join(directory, ".overlord", "project.json"));
60790
62827
  let projectId = flagValue(parsed.flags, "--project-id");
60791
62828
  if (!projectId) {
60792
62829
  const allProjects = await listAccessibleProjects({ backend: runtime.backend });
@@ -61299,13 +63336,13 @@ async function runManagementCommand({
61299
63336
  "file-changes": `/api/missions/${encodeURIComponent(missionId)}/file-changes`,
61300
63337
  deliveries: `/api/missions/${encodeURIComponent(missionId)}/deliveries`
61301
63338
  };
61302
- const path55 = sub ? pathBySub[sub] : void 0;
61303
- if (!path55) {
63339
+ const path60 = sub ? pathBySub[sub] : void 0;
63340
+ if (!path60) {
61304
63341
  throw new CliError({
61305
63342
  message: "Usage: ovld mission context|events|deliveries|artifacts|file-changes <missionId> [--json]"
61306
63343
  });
61307
63344
  }
61308
- const result = await runtime.backend.get(path55);
63345
+ const result = await runtime.backend.get(path60);
61309
63346
  if (json2 || sub === "context") printJson(result);
61310
63347
  else {
61311
63348
  const items = missionEvidenceItems(result);
@@ -61431,7 +63468,7 @@ The runner will not register a target for you \u2014 declare this machine first,
61431
63468
  const projectId = String(requestRecord.projectId ?? "");
61432
63469
  const executionTargetId = typeof requestRecord.executionTargetId === "string" ? requestRecord.executionTargetId.trim() : "";
61433
63470
  const mutation = parseMutationFromMetadata(requestRecord.metadata);
61434
- const privateResourceRead = mutation?.capability === "readProjectResource";
63471
+ const privateResourceRead = mutation?.capability === "readProjectResource" || mutation?.capability === "writeProjectResource";
61435
63472
  if (projectId && executionTargetId && !privateResourceRead) {
61436
63473
  try {
61437
63474
  await reportRunnerResourceObservations({
@@ -61458,7 +63495,10 @@ The runner will not register a target for you \u2014 declare this machine first,
61458
63495
  const absentSession = mutation.capability === "inspectLatchSession" && !mutationResult.ok && mutationResult.code === "LATCH_SESSION_ABSENT";
61459
63496
  if (privateResourceRead) {
61460
63497
  if (json2) printJson({ requestId, processed: true });
61461
- else console.log(`Completed project resource read for ${requestRecord.projectId}`);
63498
+ else
63499
+ console.log(
63500
+ `Completed project resource ${mutation.capability === "writeProjectResource" ? "write" : "read"} for ${requestRecord.projectId}`
63501
+ );
61462
63502
  return { launched: false, longPoll, processed: true };
61463
63503
  }
61464
63504
  if (!mutationResult.ok && !absentSession) {