kith-coord 0.1.8 → 0.2.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
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __kithRequire } from 'node:module'; const require = __kithRequire(import.meta.url);
2
2
 
3
3
  // src/core/engine.ts
4
- import { execFileSync as execFileSync13 } from "child_process";
4
+ import { execFileSync as execFileSync18 } from "child_process";
5
5
 
6
6
  // src/core/repository.ts
7
7
  import { execFileSync } from "child_process";
@@ -53,16 +53,16 @@ function discoverRepository(input) {
53
53
  throw new Error("Cannot coordinate a filesystem root; select an explicit project with --repo.");
54
54
  }
55
55
  if (!fs.statSync(directory).isDirectory()) throw new Error(`Not a directory: ${input}`);
56
- const git3 = (...args) => execFileSync("git", ["rev-parse", ...args], {
56
+ const git4 = (...args) => execFileSync("git", ["rev-parse", ...args], {
57
57
  cwd: directory,
58
58
  encoding: "utf8",
59
59
  stdio: ["ignore", "pipe", "pipe"]
60
60
  }).replace(/\r?\n$/, "");
61
61
  try {
62
- const checkoutRoot = fs.realpathSync(git3("--show-toplevel"));
62
+ const checkoutRoot = fs.realpathSync(git4("--show-toplevel"));
63
63
  if (!isWithin(checkoutRoot, directory)) throw new Error("Git routing environment selects a different checkout");
64
- const commonGitDir = fs.realpathSync(git3("--path-format=absolute", "--git-common-dir"));
65
- const isLinkedWorktree = fs.realpathSync(git3("--absolute-git-dir")) !== commonGitDir;
64
+ const commonGitDir = fs.realpathSync(git4("--path-format=absolute", "--git-common-dir"));
65
+ const isLinkedWorktree = fs.realpathSync(git4("--absolute-git-dir")) !== commonGitDir;
66
66
  const coordDir = path.basename(commonGitDir) === ".git" ? path.join(path.dirname(commonGitDir), ".coord") : path.join(commonGitDir, "kith");
67
67
  return { checkoutRoot, commonGitDir, coordDir, isLinkedWorktree };
68
68
  } catch (error) {
@@ -162,7 +162,7 @@ async function waitForClaim(params) {
162
162
  }
163
163
 
164
164
  // src/version.ts
165
- var KITH_VERSION = "0.1.8";
165
+ var KITH_VERSION = "0.2.0";
166
166
  var KITH_PROTOCOL_VERSION = "1.6.0";
167
167
 
168
168
  // src/core/git-ignore.ts
@@ -411,8 +411,8 @@ function previewIntegration(repoRoot, agent) {
411
411
  }
412
412
 
413
413
  // src/core/engine.ts
414
- import fs18 from "fs";
415
- import path16 from "path";
414
+ import fs20 from "fs";
415
+ import path18 from "path";
416
416
 
417
417
  // src/core/ast-analyzer.ts
418
418
  import crypto from "crypto";
@@ -699,9 +699,11 @@ var AstAnalyzer = class _AstAnalyzer {
699
699
  };
700
700
 
701
701
  // src/core/bash-guard.ts
702
- import crypto5 from "crypto";
703
- import fs6 from "fs";
704
- import path6 from "path";
702
+ import { execFileSync as execFileSync7 } from "child_process";
703
+ import crypto6 from "crypto";
704
+ import { createRequire } from "module";
705
+ import fs7 from "fs";
706
+ import path7 from "path";
705
707
 
706
708
  // src/core/locks.ts
707
709
  import crypto4 from "crypto";
@@ -774,7 +776,7 @@ function scopesOverlap(a, b, literalA = false, literalB = false) {
774
776
  }
775
777
 
776
778
  // src/core/fencing.ts
777
- import { execFileSync as execFileSync4 } from "child_process";
779
+ import { execFile, execFileSync as execFileSync4 } from "child_process";
778
780
  import crypto3 from "crypto";
779
781
  import fs4 from "fs";
780
782
  import path4 from "path";
@@ -987,6 +989,9 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
987
989
  capabilities = /* @__PURE__ */ new Map();
988
990
  static ownWindowsStart = null;
989
991
  static inspectionFailure = null;
992
+ /** Confirmed start times. Heartbeats must not spawn `ps` on every 100ms tick: on macOS that blocks the event loop longer than a short mutex lease and the lease is lost before the command starts. */
993
+ static confirmedStarts = /* @__PURE__ */ new Map();
994
+ static rechecking = /* @__PURE__ */ new Set();
990
995
  static validateLease(duration) {
991
996
  if (!Number.isSafeInteger(duration) || duration < 100 || duration > 864e5) {
992
997
  throw new Error("Lease duration must be an integer between 100 and 86400000 milliseconds");
@@ -1000,7 +1005,7 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
1000
1005
  try {
1001
1006
  if (process.platform === "linux") {
1002
1007
  const stat = fs4.readFileSync(`/proc/${pid}/stat`, "utf8");
1003
- return `linux:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
1008
+ return this.rememberStart(pid, `linux:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`);
1004
1009
  }
1005
1010
  if (process.platform === "win32") {
1006
1011
  if (pid === process.pid && this.ownWindowsStart) return this.ownWindowsStart;
@@ -1021,7 +1026,7 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
1021
1026
  }
1022
1027
  const identity = `windows:${ticks}`;
1023
1028
  if (pid === process.pid) this.ownWindowsStart = identity;
1024
- return identity;
1029
+ return this.rememberStart(pid, identity);
1025
1030
  }
1026
1031
  const out = execFileSync4("ps", ["-o", "lstart=", "-p", String(pid)], {
1027
1032
  encoding: "utf8",
@@ -1029,22 +1034,92 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
1029
1034
  timeout: 1500,
1030
1035
  env: { ...process.env, LC_ALL: "C" }
1031
1036
  }).trim();
1032
- return out || null;
1037
+ return out ? this.rememberStart(pid, out) : null;
1033
1038
  } catch (error) {
1034
1039
  const failure = error;
1035
1040
  this.inspectionFailure = [failure.code, failure.status === void 0 ? null : `exit ${failure.status}`, failure.signal].filter(Boolean).join(", ") || "inspection unavailable";
1036
1041
  return null;
1037
1042
  }
1038
1043
  }
1044
+ /**
1045
+ * Resolve a start time without blocking lease renewal. A just-forked pid can be
1046
+ * invisible to `ps` for a moment, and a single timed-out `ps` must not abort the command.
1047
+ */
1048
+ static async waitForProcessStartTime(pid, budgetMs, aborted) {
1049
+ const deadline = Date.now() + budgetMs;
1050
+ while (!aborted?.() && Date.now() < deadline) {
1051
+ try {
1052
+ process.kill(pid, 0);
1053
+ } catch (err) {
1054
+ if (err.code === "ESRCH") return null;
1055
+ }
1056
+ const start = process.platform === "darwin" ? await this.readDarwinStartTime(pid, Math.min(800, Math.max(50, deadline - Date.now()))) : this.getProcessStartTime(pid);
1057
+ if (start) return start;
1058
+ await new Promise((resolve) => setTimeout(resolve, 20));
1059
+ }
1060
+ return null;
1061
+ }
1039
1062
  static isProcessAlive(pid, expectedStartTime) {
1040
1063
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
1041
1064
  try {
1042
1065
  process.kill(pid, 0);
1043
1066
  } catch (err) {
1044
- if (err.code === "ESRCH") return false;
1067
+ if (err.code === "ESRCH") {
1068
+ this.confirmedStarts.delete(pid);
1069
+ return false;
1070
+ }
1071
+ }
1072
+ const cached = this.confirmedStarts.get(pid);
1073
+ if (cached?.start === expectedStartTime) {
1074
+ this.scheduleStartRecheck(pid);
1075
+ return true;
1045
1076
  }
1046
1077
  const current = this.getProcessStartTime(pid);
1047
- return current === null || current === expectedStartTime;
1078
+ if (current === null) return true;
1079
+ if (current === expectedStartTime) return true;
1080
+ this.confirmedStarts.delete(pid);
1081
+ return false;
1082
+ }
1083
+ static rememberStart(pid, start) {
1084
+ this.confirmedStarts.set(pid, { start, at: Date.now() });
1085
+ return start;
1086
+ }
1087
+ /** Refresh identity in the background so a slow `ps` cannot stall mutex renewal. */
1088
+ static scheduleStartRecheck(pid) {
1089
+ const cached = this.confirmedStarts.get(pid);
1090
+ if (!cached || this.rechecking.has(pid) || Date.now() - cached.at < 250) return;
1091
+ this.rechecking.add(pid);
1092
+ const finish = (start) => {
1093
+ this.rechecking.delete(pid);
1094
+ if (start) {
1095
+ this.rememberStart(pid, start);
1096
+ return;
1097
+ }
1098
+ try {
1099
+ process.kill(pid, 0);
1100
+ } catch (err) {
1101
+ if (err.code === "ESRCH") this.confirmedStarts.delete(pid);
1102
+ }
1103
+ };
1104
+ if (process.platform === "darwin") void this.readDarwinStartTime(pid, 800).then(finish);
1105
+ else finish(this.getProcessStartTime(pid));
1106
+ }
1107
+ static readDarwinStartTime(pid, timeoutMs) {
1108
+ return new Promise((resolve) => {
1109
+ const child = execFile("ps", ["-o", "lstart=", "-p", String(pid)], {
1110
+ encoding: "utf8",
1111
+ timeout: timeoutMs,
1112
+ env: { ...process.env, LC_ALL: "C" }
1113
+ }, (err, stdout) => {
1114
+ if (err) {
1115
+ resolve(null);
1116
+ return;
1117
+ }
1118
+ const value = stdout.trim();
1119
+ resolve(value ? this.rememberStart(pid, value) : null);
1120
+ });
1121
+ child.unref();
1122
+ });
1048
1123
  }
1049
1124
  registerAgent(params) {
1050
1125
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(params.id)) throw new Error("Invalid agent ID");
@@ -1612,16 +1687,1567 @@ var LockEngine = class _LockEngine {
1612
1687
  return true;
1613
1688
  }
1614
1689
  }
1615
- listLocks() {
1616
- this.fencing.reapDeadAgents();
1617
- return this.coordDb.db.prepare(`SELECT * FROM locks WHERE expires_at > ? ORDER BY acquired_at ASC`).all(Date.now());
1690
+ listLocks() {
1691
+ this.fencing.reapDeadAgents();
1692
+ return this.coordDb.db.prepare(`SELECT * FROM locks WHERE expires_at > ? ORDER BY acquired_at ASC`).all(Date.now());
1693
+ }
1694
+ };
1695
+
1696
+ // src/core/shared-ref-update.ts
1697
+ import { execFileSync as execFileSync6 } from "child_process";
1698
+ import crypto5 from "crypto";
1699
+ import fs6 from "fs";
1700
+ import path6 from "path";
1701
+
1702
+ // src/core/recorded-files.ts
1703
+ import { execFileSync as execFileSync5 } from "child_process";
1704
+ function listDirtyFiles(rootDir) {
1705
+ try {
1706
+ const out = execFileSync5("git", ["status", "--porcelain", "-z", "--untracked-files=all"], {
1707
+ cwd: rootDir,
1708
+ encoding: "utf8",
1709
+ stdio: ["ignore", "pipe", "ignore"]
1710
+ });
1711
+ const tokens = out.split("\0");
1712
+ const files = [];
1713
+ for (let i = 0; i < tokens.length; i++) {
1714
+ const entry = tokens[i];
1715
+ if (!entry || entry.length < 4) continue;
1716
+ const status = entry.slice(0, 2);
1717
+ const file = entry.slice(3);
1718
+ if (file) files.push(file);
1719
+ if ((status.startsWith("R") || status.startsWith("C")) && i + 1 < tokens.length && tokens[i + 1]) {
1720
+ files.push(tokens[++i]);
1721
+ }
1722
+ }
1723
+ return Array.from(new Set(files));
1724
+ } catch {
1725
+ return [];
1726
+ }
1727
+ }
1728
+ function collectRecordedFiles(params) {
1729
+ const dirtySet = new Set(params.dirtyFiles);
1730
+ const collected = /* @__PURE__ */ new Set();
1731
+ for (const lock of params.locks) {
1732
+ if (!params.callerAgentIds.has(lock.owner_agent_id)) continue;
1733
+ if (lock.lock_type === "file" || !/[?*]/.test(lock.pattern)) {
1734
+ const rel = lock.pattern.startsWith("file:") ? lock.pattern.slice(5) : lock.pattern;
1735
+ if (!rel.startsWith("symbol:")) collected.add(rel);
1736
+ } else if (lock.pattern !== "**") {
1737
+ for (const df of params.dirtyFiles) {
1738
+ if (LockEngine.patternsOverlap(LockEngine.literalScope(df), lock.pattern)) collected.add(df);
1739
+ }
1740
+ }
1741
+ }
1742
+ for (const touched of params.presenceTouched) {
1743
+ try {
1744
+ collected.add(LockEngine.normalizeFile(params.worktreeRoot, touched));
1745
+ } catch {
1746
+ }
1747
+ }
1748
+ for (const task of params.tasks) {
1749
+ if (task.status !== "active" || !task.owner_agent_id || !params.callerAgentIds.has(task.owner_agent_id)) continue;
1750
+ for (const glob of task.scope_globs) {
1751
+ if (glob === "**") continue;
1752
+ for (const df of params.dirtyFiles) {
1753
+ if (LockEngine.patternsOverlap(LockEngine.literalScope(df), glob)) collected.add(df);
1754
+ }
1755
+ }
1756
+ }
1757
+ const candidates = [...collected].filter((f) => dirtySet.has(f));
1758
+ const ignored = candidates.length ? ignoredPaths(params.worktreeRoot, candidates) : /* @__PURE__ */ new Set();
1759
+ return candidates.filter((f) => !ignored.has(f));
1760
+ }
1761
+ function pathRecordedByCaller(params) {
1762
+ const relPath = params.relPath.replace(/\\/g, "/");
1763
+ const requested = LockEngine.literalScope(relPath);
1764
+ for (const lock of params.locks) {
1765
+ if (!params.callerAgentIds.has(lock.owner_agent_id)) continue;
1766
+ if (lock.pattern.startsWith("symbol:")) continue;
1767
+ if (lock.pattern === "**") continue;
1768
+ if (lock.lock_type === "file" || !/[?*]/.test(lock.pattern)) {
1769
+ const rel = lock.pattern.startsWith("file:") ? lock.pattern.slice(5) : lock.pattern;
1770
+ if (rel === relPath) return true;
1771
+ } else if (LockEngine.patternsOverlap(requested, lock.pattern)) {
1772
+ return true;
1773
+ }
1774
+ }
1775
+ for (const touched of params.presenceTouched) {
1776
+ try {
1777
+ if (LockEngine.normalizeFile(params.worktreeRoot, touched) === relPath) return true;
1778
+ } catch {
1779
+ }
1780
+ }
1781
+ for (const task of params.tasks) {
1782
+ if (task.status !== "active" || !task.owner_agent_id || !params.callerAgentIds.has(task.owner_agent_id)) continue;
1783
+ for (const glob of task.scope_globs) {
1784
+ if (glob === "**") continue;
1785
+ if (LockEngine.patternsOverlap(requested, glob)) return true;
1786
+ }
1787
+ }
1788
+ return false;
1789
+ }
1790
+ function peerClaimOnPath(params) {
1791
+ const requested = LockEngine.literalScope(params.relPath.replace(/\\/g, "/"));
1792
+ for (const lock of params.locks) {
1793
+ if (params.callerAgentIds.has(lock.owner_agent_id)) continue;
1794
+ if (LockEngine.patternsOverlap(requested, lock.pattern)) {
1795
+ return { agentId: lock.owner_agent_id, pattern: lock.pattern };
1796
+ }
1797
+ }
1798
+ return null;
1799
+ }
1800
+
1801
+ // src/core/shared-ref-update.ts
1802
+ var LEASE_MS = 3e4;
1803
+ var GIT_PREFIX = String.raw`\bgit(?:\s+(?:-C|-c|--git-dir|--work-tree)(?:=|\s+)(?:"[^"]*"|'[^']*'|[^\s;&|]+)|\s+--(?:no-pager|literal-pathspecs|no-optional-locks))*\s+`;
1804
+ var DESTRUCTIVE_SHARED_REFS = new RegExp(GIT_PREFIX + String.raw`(?:update-ref|symbolic-ref|worktree\s+(?:remove|prune)|branch\s+(?:-[dDmMfF]|--(?:delete|move|force)))\b`);
1805
+ var DESTRUCTIVE_SHARED_TREE = new RegExp(GIT_PREFIX + String.raw`(?:reset|clean|checkout|restore|switch|stash|merge|rebase|pull|cherry-pick|revert|am)\b`);
1806
+ var SAFE_GIT_GLOBALS = /* @__PURE__ */ new Set([
1807
+ "--no-pager",
1808
+ "-P",
1809
+ "--paginate",
1810
+ "-p",
1811
+ "--literal-pathspecs",
1812
+ "--no-optional-locks",
1813
+ "--no-replace-objects"
1814
+ ]);
1815
+ var CHECKOUT_REWRITE = /* @__PURE__ */ new Set([
1816
+ "reset",
1817
+ "clean",
1818
+ "checkout",
1819
+ "restore",
1820
+ "switch",
1821
+ "stash",
1822
+ "merge",
1823
+ "rebase",
1824
+ "pull",
1825
+ "cherry-pick",
1826
+ "revert",
1827
+ "am",
1828
+ "commit"
1829
+ ]);
1830
+ var SAFE_REV = /^(?!-)[A-Za-z0-9._/^~:@{}-]+$/;
1831
+ function commandMovesSharedCheckout(command) {
1832
+ return DESTRUCTIVE_SHARED_REFS.test(command) || DESTRUCTIVE_SHARED_TREE.test(command) || /\bgit(?:\s+\S+)*?\s+commit(?![\w-])/.test(command);
1833
+ }
1834
+ function firewallReason(suggestion, specific) {
1835
+ const detail = specific ? `${specific.endsWith(".") ? specific : `${specific}.`} ` : "";
1836
+ return `Git operation can replace shared work or refs while peer agents are active. ${detail}To commit only your own files safely while peers are active, run: ${suggestion}`;
1837
+ }
1838
+ function suggestKithCommit(host, command) {
1839
+ const message = extractCommitMessage(command) ?? "<message>";
1840
+ let files = [];
1841
+ try {
1842
+ const root = checkoutOf(host).checkout;
1843
+ files = collectRecordedFiles({
1844
+ worktreeRoot: root,
1845
+ callerAgentIds: /* @__PURE__ */ new Set([host.agentId]),
1846
+ locks: host.locks,
1847
+ tasks: host.tasks,
1848
+ presenceTouched: host.presenceTouched,
1849
+ dirtyFiles: listDirtyFiles(root)
1850
+ });
1851
+ } catch {
1852
+ files = [];
1853
+ }
1854
+ const shown = files.slice(0, 20).map(quoteArg);
1855
+ const more = files.length > 20 ? " ..." : "";
1856
+ const filePart = shown.length ? ` ${shown.join(" ")}${more}` : " [files...]";
1857
+ return `kith commit -m ${quoteArg(message)}${filePart}`;
1858
+ }
1859
+ function assessSharedCheckoutUpdate(host, command, startDir) {
1860
+ const place = checkoutOf(host);
1861
+ if (!place.shared) return { action: "skip" };
1862
+ let scan;
1863
+ try {
1864
+ scan = scanCommand(command, startDir);
1865
+ } catch {
1866
+ clearSharedRefLease(host.coordDir, host.agentId);
1867
+ return block(host, command, "The ref command could not be parsed.");
1868
+ }
1869
+ if (!scan.sawUpdateRef) {
1870
+ clearSharedRefLease(host.coordDir, host.agentId);
1871
+ return { action: "skip" };
1872
+ }
1873
+ if (scan.updates.length > 1) scan.failure = scan.failure ?? "Multiple update-ref commands cannot be verified together.";
1874
+ if (scan.updates.length >= 1 && (scan.checkoutRewrite || scan.otherRefWrite)) {
1875
+ scan.failure = scan.failure ?? "The command mixes update-ref with another ref or checkout rewrite.";
1876
+ }
1877
+ if (scan.failure || scan.updates.length !== 1) {
1878
+ clearSharedRefLease(host.coordDir, host.agentId);
1879
+ return block(host, command, scan.failure ?? "The update-ref command could not be verified.");
1880
+ }
1881
+ const verdict = verifyCandidate(host, place.checkout, scan.updates[0]);
1882
+ if (!verdict.ok) {
1883
+ clearSharedRefLease(host.coordDir, host.agentId);
1884
+ return block(host, command, verdict.reason);
1885
+ }
1886
+ if (verdict.defer) {
1887
+ writeLease(host, {
1888
+ agentId: host.agentId,
1889
+ command,
1890
+ createdAt: Date.now(),
1891
+ expiresAt: Date.now() + LEASE_MS,
1892
+ updates: [{ dir: verdict.dir, ref: verdict.ref, old: verdict.old, noDeref: verdict.noDeref }]
1893
+ });
1894
+ return { action: "defer" };
1895
+ }
1896
+ clearSharedRefLease(host.coordDir, host.agentId);
1897
+ return { action: "allow" };
1898
+ }
1899
+ function casCommandDirectories(command, startDir) {
1900
+ try {
1901
+ const scan = scanCommand(command, startDir);
1902
+ if (scan.failure || scan.checkoutRewrite || scan.otherRefWrite || scan.updates.length !== 1) return [];
1903
+ return [scan.updates[0].dir];
1904
+ } catch {
1905
+ return [];
1906
+ }
1907
+ }
1908
+ function settleDeferredRefUpdate(host, command) {
1909
+ const pending = readLease(host.coordDir, host.agentId);
1910
+ if (!pending || pending.command !== command) return { warnings: [], reverted: false };
1911
+ clearSharedRefLease(host.coordDir, host.agentId);
1912
+ const warnings = [];
1913
+ let reverted = false;
1914
+ const suggestion = suggestKithCommit(host, command);
1915
+ for (const update of pending.updates) {
1916
+ if (!isSafeHeadRef(update.ref) || !isFullSha(update.old)) {
1917
+ warnings.push(`[KITH BASH FIREWALL] Dropped an unreadable shared-checkout update record for ${host.agentId}.`);
1918
+ continue;
1919
+ }
1920
+ const current = readCommitRef(update.dir, update.ref);
1921
+ if (!current) {
1922
+ warnings.push(`[KITH BASH FIREWALL] Could not read ${update.ref} after update-ref. To commit only your own files safely while peers are active, run: ${suggestion}`);
1923
+ continue;
1924
+ }
1925
+ if (current === update.old) continue;
1926
+ const verdict = verifyFastForward(host, update.dir, current, update.old);
1927
+ if (verdict.ok) continue;
1928
+ const didRevert = revertRef(update, current);
1929
+ reverted = reverted || didRevert;
1930
+ const action = didRevert ? `Reverted ${update.ref} from ${short(current)} to ${short(update.old)}` : `Could not revert ${update.ref} from ${short(current)} to ${short(update.old)} because a later update won the compare-and-swap`;
1931
+ warnings.push(`[KITH BASH FIREWALL] ${action}: ${verdict.reason} To commit only your own files safely while peers are active, run: ${suggestion}`);
1932
+ host.logEvent?.(host.agentId, didRevert ? "shared_ref_update_reverted" : "shared_ref_update_revert_failed", {
1933
+ ref: update.ref,
1934
+ from: current,
1935
+ to: update.old,
1936
+ reason: verdict.reason
1937
+ });
1938
+ }
1939
+ return { warnings, reverted };
1940
+ }
1941
+ function foreignRefLease(coordDir, agentId) {
1942
+ for (const pending of listLeases(coordDir)) {
1943
+ if (pending.agentId !== agentId) return { agentId: pending.agentId };
1944
+ }
1945
+ return null;
1946
+ }
1947
+ function waitForSharedRefLease(coordDir, agentId, timeoutMs = 15e3) {
1948
+ const started = Date.now();
1949
+ while (true) {
1950
+ const foreign = foreignRefLease(coordDir, agentId ?? "");
1951
+ if (!foreign) return null;
1952
+ if (Date.now() - started >= timeoutMs) {
1953
+ return `Timed out waiting for agent ${foreign.agentId} to finish verifying a shared-checkout commit. Retry shortly.`;
1954
+ }
1955
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40);
1956
+ }
1957
+ }
1958
+ function clearSharedRefLease(coordDir, agentId) {
1959
+ try {
1960
+ fs6.unlinkSync(leasePath(coordDir, agentId));
1961
+ } catch {
1962
+ }
1963
+ }
1964
+ function block(host, command, specific) {
1965
+ return { action: "block", reason: firewallReason(suggestKithCommit(host, command), specific) };
1966
+ }
1967
+ function checkoutOf(host) {
1968
+ let checkout = host.repoRoot;
1969
+ try {
1970
+ checkout = physicalPath(host.agent?.worktree_path ?? host.repoRoot);
1971
+ } catch {
1972
+ return { shared: false, checkout: host.repoRoot };
1973
+ }
1974
+ if (!host.agent?.worktree_path) return { shared: true, checkout };
1975
+ const main = mainCheckout(checkout);
1976
+ if (!main) return { shared: false, checkout };
1977
+ return { shared: main.path === checkout, checkout };
1978
+ }
1979
+ function verifyCandidate(host, checkout, update) {
1980
+ if (!directoryInside(update.dir, checkout)) {
1981
+ return { ok: false, reason: "update-ref runs outside this shared checkout" };
1982
+ }
1983
+ if (!isSafeHeadRef(update.ref)) return { ok: false, reason: "The ref must be a literal HEAD or refs/heads/<current branch>." };
1984
+ const checked = checkedOutBranch(update.dir);
1985
+ if (!checked.ok) return { ok: false, reason: "The current branch could not be read." };
1986
+ const currentBranch = checked.branch ? `refs/heads/${checked.branch}` : null;
1987
+ if (update.ref !== "HEAD" && update.ref !== currentBranch) {
1988
+ return { ok: false, reason: `Ref ${update.ref} is not HEAD or the current branch${currentBranch ? ` (${currentBranch})` : ""}.` };
1989
+ }
1990
+ if (update.noDeref && symbolicRef(update.dir, update.ref)) {
1991
+ return { ok: false, reason: "--no-deref would update the symbolic ref itself instead of fast-forwarding the branch." };
1992
+ }
1993
+ const current = readCommitRef(update.dir, update.ref);
1994
+ if (!current) return { ok: false, reason: `The current value of ${update.ref} could not be read.` };
1995
+ if (!update.oldWord.expansion) {
1996
+ const old = resolveCommit(update.dir, update.oldWord.text);
1997
+ if (!old.ok) return { ok: false, reason: `Compare-and-swap old value ${old.reason}` };
1998
+ if (old.sha !== current) {
1999
+ return { ok: false, reason: `Compare-and-swap old value ${short(old.sha)} does not equal current ${update.ref} (${short(current)}).` };
2000
+ }
2001
+ }
2002
+ if (!update.newWord.expansion) {
2003
+ const created = resolveCommit(update.dir, update.newWord.text);
2004
+ if (!created.ok) return { ok: false, reason: `New value ${created.reason}` };
2005
+ const ff = verifyFastForward(host, checkout, created.sha, current);
2006
+ if (!ff.ok) return ff;
2007
+ if (update.oldWord.expansion) {
2008
+ return { ok: true, defer: true, dir: update.dir, ref: update.ref, old: current, noDeref: update.noDeref };
2009
+ }
2010
+ return { ok: true, defer: false };
2011
+ }
2012
+ return { ok: true, defer: true, dir: update.dir, ref: update.ref, old: current, noDeref: update.noDeref };
2013
+ }
2014
+ function verifyFastForward(host, checkout, newSha, oldSha) {
2015
+ const parents = commitParents(checkout, newSha);
2016
+ if (!parents) return { ok: false, reason: "The new commit could not be read." };
2017
+ if (parents.length === 0) return { ok: false, reason: "New commit has no parent (not a one-commit fast-forward)." };
2018
+ if (parents.length > 1) {
2019
+ return { ok: false, reason: `New commit is a merge (${parents.length} parents); only a one-commit fast-forward is allowed.` };
2020
+ }
2021
+ if (parents[0] !== oldSha) {
2022
+ return { ok: false, reason: `New commit parent ${short(parents[0])} is not ${short(oldSha)} (not a one-commit fast-forward).` };
2023
+ }
2024
+ const paths = changedPaths(checkout, oldSha, newSha);
2025
+ if (!paths) return { ok: false, reason: "The commit diff could not be read." };
2026
+ const caller = /* @__PURE__ */ new Set([host.agentId]);
2027
+ const problems = [];
2028
+ for (const rel of paths) {
2029
+ const peer = peerClaimOnPath({ relPath: rel, callerAgentIds: caller, locks: host.locks });
2030
+ if (peer) {
2031
+ problems.push(`path ${rel} is claimed by agent ${peer.agentId}`);
2032
+ continue;
2033
+ }
2034
+ if (!pathRecordedByCaller({
2035
+ worktreeRoot: checkout,
2036
+ relPath: rel,
2037
+ callerAgentIds: caller,
2038
+ locks: host.locks,
2039
+ tasks: host.tasks,
2040
+ presenceTouched: host.presenceTouched
2041
+ })) {
2042
+ problems.push(`path ${rel} is not claimed, locked, or recorded by this session`);
2043
+ }
2044
+ }
2045
+ if (problems.length === 0) return { ok: true };
2046
+ const shown = problems.slice(0, 5).join("; ");
2047
+ const more = problems.length > 5 ? `; and ${problems.length - 5} more` : "";
2048
+ return { ok: false, reason: `${shown}${more}` };
2049
+ }
2050
+ function resolveCommit(dir, rev) {
2051
+ if (!isSafeRev(rev)) return { ok: false, reason: "is not a literal commit." };
2052
+ const type = git2(dir, ["cat-file", "-t", "--end-of-options", rev]);
2053
+ if (type !== "commit") {
2054
+ return { ok: false, reason: type ? `resolves to a ${type}, not a commit.` : "does not resolve to a commit." };
2055
+ }
2056
+ const sha = git2(dir, ["rev-parse", "--verify", "--end-of-options", `${rev}^{commit}`]);
2057
+ if (!sha || !isFullSha(sha)) return { ok: false, reason: "does not resolve to a commit." };
2058
+ return { ok: true, sha };
2059
+ }
2060
+ function commitParents(dir, sha) {
2061
+ if (!isFullSha(sha)) return null;
2062
+ const text = gitRaw(dir, ["cat-file", "-p", "--end-of-options", sha]);
2063
+ if (text === null) return null;
2064
+ const parents = [];
2065
+ for (const line of text.split("\n")) {
2066
+ if (line === "") break;
2067
+ if (!line.startsWith("parent ")) continue;
2068
+ const parent = line.slice("parent ".length).trim();
2069
+ if (!isFullSha(parent)) return null;
2070
+ parents.push(parent);
2071
+ }
2072
+ return parents;
2073
+ }
2074
+ function changedPaths(dir, oldSha, newSha) {
2075
+ if (!isFullSha(oldSha) || !isFullSha(newSha)) return null;
2076
+ const out = gitRaw(dir, [
2077
+ "diff-tree",
2078
+ "-r",
2079
+ "-z",
2080
+ "--name-only",
2081
+ "--no-renames",
2082
+ "--end-of-options",
2083
+ oldSha,
2084
+ newSha
2085
+ ]);
2086
+ if (out === null) return null;
2087
+ return [...new Set(out.split("\0").filter(Boolean).map((entry) => entry.replace(/\\/g, "/")))];
2088
+ }
2089
+ function revertRef(update, current) {
2090
+ if (!isSafeHeadRef(update.ref) || !isFullSha(update.old) || !isFullSha(current)) return false;
2091
+ const args = ["update-ref"];
2092
+ if (update.noDeref) args.push("--no-deref");
2093
+ args.push("-m", "kith: revert shared-checkout update that failed ownership checks", update.ref, update.old, current);
2094
+ try {
2095
+ execFileSync6("git", args, { cwd: update.dir, stdio: ["ignore", "pipe", "pipe"], timeout: 5e3 });
2096
+ return true;
2097
+ } catch {
2098
+ return false;
2099
+ }
2100
+ }
2101
+ function readCommitRef(dir, ref) {
2102
+ if (!isSafeHeadRef(ref)) return null;
2103
+ const sha = git2(dir, ["rev-parse", "--verify", "--end-of-options", ref]);
2104
+ return sha && isFullSha(sha) ? sha : null;
2105
+ }
2106
+ function symbolicRef(dir, ref) {
2107
+ if (!isSafeHeadRef(ref)) return null;
2108
+ const value = git2(dir, ["symbolic-ref", "-q", "--end-of-options", ref]);
2109
+ return value || null;
2110
+ }
2111
+ function checkedOutBranch(dir) {
2112
+ try {
2113
+ const out = execFileSync6("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
2114
+ cwd: dir,
2115
+ encoding: "utf8",
2116
+ stdio: ["ignore", "pipe", "ignore"],
2117
+ timeout: 5e3
2118
+ }).trim();
2119
+ return { ok: true, branch: out || null };
2120
+ } catch (error) {
2121
+ if (error.status === 1) return { ok: true, branch: null };
2122
+ return { ok: false };
2123
+ }
2124
+ }
2125
+ function mainCheckout(cwd) {
2126
+ let out;
2127
+ try {
2128
+ out = execFileSync6("git", ["worktree", "list", "--porcelain"], {
2129
+ cwd,
2130
+ encoding: "utf8",
2131
+ stdio: ["ignore", "pipe", "ignore"],
2132
+ timeout: 5e3
2133
+ });
2134
+ } catch {
2135
+ return null;
2136
+ }
2137
+ const first = out.split(/\n\s*\n/)[0] ?? "";
2138
+ let wt = null;
2139
+ let branch = null;
2140
+ let detached = false;
2141
+ for (const line of first.split("\n")) {
2142
+ if (line.startsWith("worktree ")) wt = line.slice("worktree ".length).trim();
2143
+ else if (line.startsWith("branch ")) branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
2144
+ else if (line === "detached" || line.startsWith("detached ")) detached = true;
2145
+ }
2146
+ if (!wt) return null;
2147
+ try {
2148
+ return { path: physicalPath(wt), branch: detached ? null : branch };
2149
+ } catch {
2150
+ return null;
2151
+ }
2152
+ }
2153
+ function directoryInside(dir, root) {
2154
+ try {
2155
+ const resolved = physicalPath(dir);
2156
+ const base = physicalPath(root);
2157
+ return resolved === base || isWithin(base, resolved);
2158
+ } catch {
2159
+ return false;
2160
+ }
2161
+ }
2162
+ function git2(dir, args) {
2163
+ const out = gitRaw(dir, args);
2164
+ return out === null ? null : out.trim();
2165
+ }
2166
+ function gitRaw(dir, args) {
2167
+ try {
2168
+ return execFileSync6("git", args, {
2169
+ cwd: dir,
2170
+ encoding: "utf8",
2171
+ stdio: ["ignore", "pipe", "ignore"],
2172
+ timeout: 5e3,
2173
+ maxBuffer: 8 * 1024 * 1024
2174
+ });
2175
+ } catch {
2176
+ return null;
2177
+ }
2178
+ }
2179
+ function isFullSha(value) {
2180
+ return /^[0-9a-f]{40}$/.test(value);
2181
+ }
2182
+ function isSafeRev(rev) {
2183
+ return rev.length > 0 && rev.length < 200 && SAFE_REV.test(rev) && !rev.includes("..");
2184
+ }
2185
+ function isSafeHeadRef(ref) {
2186
+ if (ref === "HEAD") return true;
2187
+ if (!ref.startsWith("refs/heads/")) return false;
2188
+ const name = ref.slice("refs/heads/".length);
2189
+ if (!name || name.startsWith("/") || name.endsWith("/") || name.includes("..") || name.includes("@{")) return false;
2190
+ return /^[A-Za-z0-9._/-]+$/.test(name);
2191
+ }
2192
+ function short(sha) {
2193
+ return sha.length > 12 ? sha.slice(0, 12) : sha;
2194
+ }
2195
+ function leasePath(coordDir, agentId) {
2196
+ const name = crypto5.createHash("sha256").update(agentId).digest("hex") + ".json";
2197
+ return path6.join(coordDir, "ref-guards", name);
2198
+ }
2199
+ function writeLease(host, pending) {
2200
+ const dir = path6.join(host.coordDir, "ref-guards");
2201
+ fs6.mkdirSync(dir, { recursive: true, mode: 448 });
2202
+ const target = leasePath(host.coordDir, host.agentId);
2203
+ const tmp = `${target}.${process.pid}.tmp`;
2204
+ fs6.writeFileSync(tmp, JSON.stringify(pending), { mode: 384 });
2205
+ fs6.renameSync(tmp, target);
2206
+ }
2207
+ function readLease(coordDir, agentId) {
2208
+ return listLeases(coordDir).find((pending) => pending.agentId === agentId) ?? null;
2209
+ }
2210
+ function listLeases(coordDir) {
2211
+ const dir = path6.join(coordDir, "ref-guards");
2212
+ let names = [];
2213
+ try {
2214
+ names = fs6.readdirSync(dir);
2215
+ } catch {
2216
+ return [];
2217
+ }
2218
+ const now = Date.now();
2219
+ const pending = [];
2220
+ for (const name of names) {
2221
+ if (!name.endsWith(".json")) continue;
2222
+ const file = path6.join(dir, name);
2223
+ let parsed = null;
2224
+ try {
2225
+ parsed = JSON.parse(fs6.readFileSync(file, "utf8"));
2226
+ } catch {
2227
+ parsed = null;
2228
+ }
2229
+ if (!parsed || typeof parsed.agentId !== "string" || !Array.isArray(parsed.updates) || typeof parsed.expiresAt !== "number") {
2230
+ try {
2231
+ fs6.unlinkSync(file);
2232
+ } catch {
2233
+ }
2234
+ continue;
2235
+ }
2236
+ if (parsed.expiresAt <= now) {
2237
+ try {
2238
+ fs6.unlinkSync(file);
2239
+ } catch {
2240
+ }
2241
+ continue;
2242
+ }
2243
+ pending.push(parsed);
2244
+ }
2245
+ return pending;
2246
+ }
2247
+ function extractCommitMessage(command) {
2248
+ const fromTree = flagMessage(command, "commit-tree");
2249
+ if (fromTree) return subject(fromTree);
2250
+ const fromRef = flagMessage(command, "update-ref");
2251
+ if (!fromRef) return null;
2252
+ return subject(fromRef.replace(/^commit:\s*/, ""));
2253
+ }
2254
+ function flagMessage(command, subcommand) {
2255
+ const re = new RegExp(String.raw`\b${subcommand}\b[\s\S]{0,500}?(?:-m|--message)(?:=|\s+)(?:'([^']*)'|"([^"]*)"|(\S+))`);
2256
+ const match = re.exec(command);
2257
+ const text = match?.[1] ?? match?.[2] ?? match?.[3];
2258
+ const trimmed = text?.trim();
2259
+ return trimmed ? trimmed : null;
2260
+ }
2261
+ function subject(message) {
2262
+ const line = message.split(/\r?\n/, 1)[0]?.trim() ?? "";
2263
+ if (!line) return null;
2264
+ return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;
2265
+ }
2266
+ function quoteArg(value) {
2267
+ if (/^[A-Za-z0-9._@/:+=,-]+$/.test(value)) return value;
2268
+ if (!/["\\$`]/.test(value)) return `"${value}"`;
2269
+ return `'${value.replaceAll("'", `'\\''`)}'`;
2270
+ }
2271
+ function scanCommand(command, startDir) {
2272
+ const scan = { sawUpdateRef: false, updates: [], failure: null, checkoutRewrite: false, otherRefWrite: false };
2273
+ const segments = splitShellSegments(command);
2274
+ if (!segments) {
2275
+ scan.sawUpdateRef = /\bupdate-ref\b/.test(command);
2276
+ scan.failure = "The ref command could not be parsed.";
2277
+ return scan;
2278
+ }
2279
+ let cwd = path6.resolve(startDir);
2280
+ let untrusted = false;
2281
+ for (const segment of segments) {
2282
+ const matched = DESTRUCTIVE_SHARED_REFS.test(segment.raw);
2283
+ const sawRef = /\bupdate-ref\b/.test(segment.raw);
2284
+ if (sawRef) scan.sawUpdateRef = true;
2285
+ const words = tokenizeShell(segment.raw);
2286
+ if (!words) {
2287
+ if (matched || sawRef) scan.failure = scan.failure ?? "The ref command could not be parsed.";
2288
+ if (continuesShell(segment.nextSep) && /\b(?:cd|pushd|popd|export|source)\b|\bGIT_DIR\b/.test(segment.raw)) untrusted = true;
2289
+ continue;
2290
+ }
2291
+ const { danger, argv } = stripLeadingEnv(words);
2292
+ if (argv.length === 0) continue;
2293
+ const head = argv[0];
2294
+ if (!head.expansion && head.text === "cd") {
2295
+ const next = applyCd(argv, cwd);
2296
+ if (next && continuesShell(segment.nextSep)) cwd = next;
2297
+ else if (!next && continuesShell(segment.nextSep)) untrusted = true;
2298
+ continue;
2299
+ }
2300
+ if (!head.expansion && (head.text === "pushd" || head.text === "popd" || head.text === "source" || head.text === "." && argv.length > 1)) {
2301
+ if (continuesShell(segment.nextSep)) untrusted = true;
2302
+ continue;
2303
+ }
2304
+ if (!head.expansion && head.text === "export") {
2305
+ if (argv.slice(1).some((arg) => dangerousGitEnv(assignmentName(arg) ?? arg.text))) untrusted = true;
2306
+ continue;
2307
+ }
2308
+ if (head.expansion || !isGitBinary(head.text) || danger || untrusted) {
2309
+ if (matched || sawRef) {
2310
+ scan.failure = scan.failure ?? (untrusted || danger ? "update-ref follows a directory or GIT_DIR change that could not be resolved." : "The ref command could not be classified.");
2311
+ }
2312
+ continue;
2313
+ }
2314
+ const parsed = parseLooseGit(argv, cwd);
2315
+ if (parsed.kind === "unclassified") {
2316
+ if (matched || sawRef) scan.failure = scan.failure ?? "The ref command could not be classified.";
2317
+ continue;
2318
+ }
2319
+ if (parsed.sub === "update-ref") {
2320
+ scan.sawUpdateRef = true;
2321
+ const cas = parseCas(parsed.dir, parsed.args);
2322
+ if (cas.failure) scan.failure = scan.failure ?? cas.failure;
2323
+ if (cas.update) scan.updates.push(cas.update);
2324
+ continue;
2325
+ }
2326
+ if (parsed.sub === "symbolic-ref") {
2327
+ const kind = classifySymbolic(parsed.args);
2328
+ if (kind !== "read") scan.otherRefWrite = true;
2329
+ continue;
2330
+ }
2331
+ if (parsed.sub === "worktree" && matched) {
2332
+ scan.otherRefWrite = true;
2333
+ continue;
2334
+ }
2335
+ if (parsed.sub === "branch" && matched) {
2336
+ scan.otherRefWrite = true;
2337
+ continue;
2338
+ }
2339
+ if (CHECKOUT_REWRITE.has(parsed.sub)) scan.checkoutRewrite = true;
2340
+ }
2341
+ return scan;
2342
+ }
2343
+ function parseCas(dir, args) {
2344
+ let noDeref = false;
2345
+ let deleteRef = false;
2346
+ let stdin = false;
2347
+ let end = false;
2348
+ const positionals = [];
2349
+ for (let i = 0; i < args.length; i++) {
2350
+ const word = args[i];
2351
+ if (!end && !word.expansion && word.text === "--") {
2352
+ end = true;
2353
+ continue;
2354
+ }
2355
+ if (!end && !word.expansion && word.text.startsWith("-")) {
2356
+ const arg = word.text;
2357
+ if (arg === "--no-deref") {
2358
+ noDeref = true;
2359
+ continue;
2360
+ }
2361
+ if (arg === "--deref") {
2362
+ noDeref = false;
2363
+ continue;
2364
+ }
2365
+ if (arg === "--create-reflog" || arg === "--no-create-reflog" || arg === "--no-stdin") continue;
2366
+ if (arg === "--stdin" || arg === "-z") {
2367
+ stdin = true;
2368
+ continue;
2369
+ }
2370
+ if (arg === "-d" || arg === "--delete") {
2371
+ deleteRef = true;
2372
+ continue;
2373
+ }
2374
+ if (arg === "-m" || arg === "--message") {
2375
+ if (args[i + 1] === void 0) return { failure: "update-ref -m is missing its message." };
2376
+ i++;
2377
+ continue;
2378
+ }
2379
+ if (arg.startsWith("-m") && arg.length > 2 || arg.startsWith("--message=")) continue;
2380
+ return { failure: `Unrecognized update-ref option '${arg}'.` };
2381
+ }
2382
+ positionals.push(word);
2383
+ }
2384
+ if (stdin) return { failure: "update-ref --stdin batches cannot be verified before they run." };
2385
+ if (deleteRef) return { failure: "Deleting a ref is not a one-commit fast-forward." };
2386
+ if (positionals.length === 2) return { failure: "No compare-and-swap old value." };
2387
+ if (positionals.length !== 3 || !positionals[0]) return { failure: "update-ref is missing a ref or value." };
2388
+ const ref = positionals[0];
2389
+ if (ref.expansion || !ref.text) return { failure: "The ref must be a literal HEAD or refs/heads/<current branch>." };
2390
+ return {
2391
+ update: { dir, ref: ref.text, noDeref, newWord: positionals[1], oldWord: positionals[2] }
2392
+ };
2393
+ }
2394
+ function classifySymbolic(args) {
2395
+ let deleteRef = false;
2396
+ let end = false;
2397
+ const positionals = [];
2398
+ for (let i = 0; i < args.length; i++) {
2399
+ const word = args[i];
2400
+ if (!end && !word.expansion && word.text === "--") {
2401
+ end = true;
2402
+ continue;
2403
+ }
2404
+ if (!end && !word.expansion && word.text.startsWith("-")) {
2405
+ const arg = word.text;
2406
+ if (arg === "-q" || arg === "--quiet" || arg === "--no-quiet" || arg === "--short" || arg === "--no-short") continue;
2407
+ if (arg === "--recurse" || arg === "--no-recurse") continue;
2408
+ if (arg === "-d" || arg === "--delete") {
2409
+ deleteRef = true;
2410
+ continue;
2411
+ }
2412
+ if (arg === "--no-delete") {
2413
+ deleteRef = false;
2414
+ continue;
2415
+ }
2416
+ if (arg === "-m" || arg === "--message") {
2417
+ if (args[i + 1] === void 0) return "unknown";
2418
+ i++;
2419
+ continue;
2420
+ }
2421
+ if (arg.startsWith("-m") && arg.length > 2 || arg.startsWith("--message=")) continue;
2422
+ return "unknown";
2423
+ }
2424
+ if (word.expansion) return "unknown";
2425
+ positionals.push(word);
2426
+ }
2427
+ if (deleteRef) return positionals.length === 1 ? "write" : "unknown";
2428
+ if (positionals.length === 1) return "read";
2429
+ if (positionals.length === 2) return "write";
2430
+ return "unknown";
2431
+ }
2432
+ function parseLooseGit(argv, cwd) {
2433
+ let i = 1;
2434
+ let dir = cwd;
2435
+ while (i < argv.length) {
2436
+ const token = argv[i];
2437
+ if (token.expansion) return { kind: "unclassified" };
2438
+ const text = token.text;
2439
+ if (text === "--") {
2440
+ i++;
2441
+ break;
2442
+ }
2443
+ if (text === "-C") {
2444
+ const next = argv[i + 1];
2445
+ if (!next || next.expansion || next.text.startsWith("~")) return { kind: "unclassified" };
2446
+ if (next.text !== "") dir = path6.isAbsolute(next.text) ? next.text : path6.resolve(dir, next.text);
2447
+ i += 2;
2448
+ continue;
2449
+ }
2450
+ if (text.startsWith("-C") && text.length > 2) {
2451
+ const next = text.slice(2);
2452
+ if (next.startsWith("~")) return { kind: "unclassified" };
2453
+ dir = path6.isAbsolute(next) ? next : path6.resolve(dir, next);
2454
+ i++;
2455
+ continue;
2456
+ }
2457
+ if (SAFE_GIT_GLOBALS.has(text)) {
2458
+ i++;
2459
+ continue;
2460
+ }
2461
+ if (text.startsWith("-")) return { kind: "unclassified" };
2462
+ break;
2463
+ }
2464
+ const sub = argv[i];
2465
+ if (!sub || sub.expansion) return { kind: "unclassified" };
2466
+ return { kind: "git", dir, sub: sub.text, args: argv.slice(i + 1) };
2467
+ }
2468
+ function stripLeadingEnv(words) {
2469
+ let i = 0;
2470
+ let danger = false;
2471
+ while (i < words.length) {
2472
+ const name = assignmentName(words[i]);
2473
+ if (!name) break;
2474
+ if (dangerousGitEnv(name)) danger = true;
2475
+ i++;
2476
+ }
2477
+ return { danger, argv: words.slice(i) };
2478
+ }
2479
+ function assignmentName(word) {
2480
+ const eq = word.text.indexOf("=");
2481
+ if (eq <= 0) return null;
2482
+ const name = word.text.slice(0, eq);
2483
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : null;
2484
+ }
2485
+ function dangerousGitEnv(name) {
2486
+ return name === "GIT_DIR" || name === "GIT_WORK_TREE" || name === "GIT_COMMON_DIR" || name === "GIT_NAMESPACE" || name === "GIT_OBJECT_DIRECTORY" || name === "GIT_ALTERNATE_OBJECT_DIRECTORIES" || name === "GIT_CONFIG_PARAMETERS" || name === "GIT_CONFIG_COUNT" || name === "GIT_CONFIG_GLOBAL" || name === "GIT_CONFIG_SYSTEM" || /^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(name);
2487
+ }
2488
+ function applyCd(argv, cwd) {
2489
+ let args = argv.slice(1);
2490
+ if (args[0] && !args[0].expansion && args[0].text === "--") args = args.slice(1);
2491
+ if (args.length !== 1 || !args[0] || args[0].expansion) return null;
2492
+ const target = args[0].text;
2493
+ if (target === "-" || target.startsWith("-") || target.startsWith("~")) return null;
2494
+ return path6.resolve(cwd, target);
2495
+ }
2496
+ function isGitBinary(word) {
2497
+ const base = word.slice(Math.max(word.lastIndexOf("/"), word.lastIndexOf("\\")) + 1);
2498
+ return base === "git" || base.toLowerCase() === "git.exe";
2499
+ }
2500
+ function continuesShell(sep) {
2501
+ return sep === "&&" || sep === ";" || sep === "\n";
2502
+ }
2503
+ function splitShellSegments(command) {
2504
+ const parts = [];
2505
+ let buf = "";
2506
+ let quote = null;
2507
+ const push = (sep) => {
2508
+ const raw = buf.trim();
2509
+ buf = "";
2510
+ if (raw) parts.push({ raw, nextSep: sep });
2511
+ };
2512
+ for (let i = 0; i < command.length; i++) {
2513
+ const ch = command[i];
2514
+ if (quote === "'") {
2515
+ buf += ch;
2516
+ if (ch === "'") quote = null;
2517
+ continue;
2518
+ }
2519
+ if (quote === '"') {
2520
+ if (ch === "\\" && i + 1 < command.length) {
2521
+ const next = command[i + 1];
2522
+ if (next === "$" || next === "`" || next === '"' || next === "\\" || next === "\n") {
2523
+ buf += ch + next;
2524
+ i++;
2525
+ continue;
2526
+ }
2527
+ }
2528
+ buf += ch;
2529
+ if (ch === '"') quote = null;
2530
+ continue;
2531
+ }
2532
+ if (ch === "\\" && i + 1 < command.length) {
2533
+ if (command[i + 1] === "\n") {
2534
+ i++;
2535
+ continue;
2536
+ }
2537
+ buf += ch + command[i + 1];
2538
+ i++;
2539
+ continue;
2540
+ }
2541
+ if (ch === "'" || ch === '"') {
2542
+ quote = ch;
2543
+ buf += ch;
2544
+ continue;
2545
+ }
2546
+ if (ch === "&" && command[i + 1] === "&") {
2547
+ push("&&");
2548
+ i++;
2549
+ continue;
2550
+ }
2551
+ if (ch === "|" && command[i + 1] === "|") {
2552
+ push("||");
2553
+ i++;
2554
+ continue;
2555
+ }
2556
+ if (ch === "\r" && command[i + 1] === "\n") {
2557
+ push("\n");
2558
+ i++;
2559
+ continue;
2560
+ }
2561
+ if (ch === "\n") {
2562
+ push("\n");
2563
+ continue;
2564
+ }
2565
+ if (ch === ";") {
2566
+ push(";");
2567
+ continue;
2568
+ }
2569
+ if (ch === "|") {
2570
+ push("|");
2571
+ continue;
2572
+ }
2573
+ if (ch === "&") {
2574
+ push("&");
2575
+ continue;
2576
+ }
2577
+ buf += ch;
2578
+ }
2579
+ if (quote) return null;
2580
+ push("end");
2581
+ return parts;
2582
+ }
2583
+ function tokenizeShell(segment) {
2584
+ const words = [];
2585
+ let buf = "";
2586
+ let expansion = false;
2587
+ let quote = null;
2588
+ let word = false;
2589
+ const flush = () => {
2590
+ if (word) words.push({ text: buf, expansion });
2591
+ buf = "";
2592
+ expansion = false;
2593
+ word = false;
2594
+ };
2595
+ const mark = (text) => {
2596
+ buf += text;
2597
+ word = true;
2598
+ expansion = true;
2599
+ };
2600
+ for (let i = 0; i < segment.length; i++) {
2601
+ const ch = segment[i];
2602
+ if (quote === "'") {
2603
+ if (ch === "'") quote = null;
2604
+ else {
2605
+ buf += ch;
2606
+ word = true;
2607
+ }
2608
+ continue;
2609
+ }
2610
+ if (quote === '"') {
2611
+ if (ch === "\\" && i + 1 < segment.length) {
2612
+ const next = segment[i + 1];
2613
+ if ('$`"\\'.includes(next)) {
2614
+ buf += next;
2615
+ word = true;
2616
+ i++;
2617
+ continue;
2618
+ }
2619
+ if (next === "\n") {
2620
+ i++;
2621
+ continue;
2622
+ }
2623
+ }
2624
+ if (ch === '"') {
2625
+ quote = null;
2626
+ word = true;
2627
+ continue;
2628
+ }
2629
+ if (ch === "`") {
2630
+ const end = segment.indexOf("`", i + 1);
2631
+ if (end < 0) return null;
2632
+ mark(segment.slice(i, end + 1));
2633
+ i = end;
2634
+ continue;
2635
+ }
2636
+ if (ch === "$") {
2637
+ const consumed = consumeExpansion(segment, i);
2638
+ if (!consumed) return null;
2639
+ mark(consumed.text);
2640
+ i = consumed.end - 1;
2641
+ continue;
2642
+ }
2643
+ buf += ch;
2644
+ word = true;
2645
+ continue;
2646
+ }
2647
+ if (ch === "\\" && i + 1 < segment.length) {
2648
+ buf += segment[i + 1];
2649
+ word = true;
2650
+ i++;
2651
+ continue;
2652
+ }
2653
+ if (ch === "'" || ch === '"') {
2654
+ quote = ch;
2655
+ word = true;
2656
+ continue;
2657
+ }
2658
+ if (ch === "`") {
2659
+ const end = segment.indexOf("`", i + 1);
2660
+ if (end < 0) return null;
2661
+ mark(segment.slice(i, end + 1));
2662
+ i = end;
2663
+ continue;
2664
+ }
2665
+ if (ch === "$") {
2666
+ const consumed = consumeExpansion(segment, i);
2667
+ if (!consumed) return null;
2668
+ mark(consumed.text);
2669
+ i = consumed.end - 1;
2670
+ continue;
2671
+ }
2672
+ if (ch === "(" || ch === ")" || ch === "<" || ch === ">") return null;
2673
+ if (ch === "#" && !word) break;
2674
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
2675
+ flush();
2676
+ continue;
2677
+ }
2678
+ buf += ch;
2679
+ word = true;
2680
+ }
2681
+ if (quote) return null;
2682
+ flush();
2683
+ return words;
2684
+ }
2685
+ function consumeExpansion(segment, i) {
2686
+ const next = segment[i + 1];
2687
+ if (next === "(") {
2688
+ let depth = 1;
2689
+ let quoted = null;
2690
+ for (let j = i + 2; j < segment.length; j++) {
2691
+ const ch = segment[j];
2692
+ if (quoted === "'") {
2693
+ if (ch === "'") quoted = null;
2694
+ continue;
2695
+ }
2696
+ if (quoted === '"') {
2697
+ if (ch === "\\" && j + 1 < segment.length) {
2698
+ j++;
2699
+ continue;
2700
+ }
2701
+ if (ch === '"') quoted = null;
2702
+ continue;
2703
+ }
2704
+ if (ch === "\\") {
2705
+ j++;
2706
+ continue;
2707
+ }
2708
+ if (ch === "'" || ch === '"') {
2709
+ quoted = ch;
2710
+ continue;
2711
+ }
2712
+ if (ch === "`") {
2713
+ const end = segment.indexOf("`", j + 1);
2714
+ if (end < 0) return null;
2715
+ j = end;
2716
+ continue;
2717
+ }
2718
+ if (ch === "(") depth++;
2719
+ else if (ch === ")") {
2720
+ depth--;
2721
+ if (depth === 0) return { text: segment.slice(i, j + 1), end: j + 1 };
2722
+ }
2723
+ }
2724
+ return null;
2725
+ }
2726
+ if (next === "{") {
2727
+ let depth = 1;
2728
+ for (let j = i + 2; j < segment.length; j++) {
2729
+ if (segment[j] === "{") depth++;
2730
+ else if (segment[j] === "}") {
2731
+ depth--;
2732
+ if (depth === 0) return { text: segment.slice(i, j + 1), end: j + 1 };
2733
+ }
2734
+ }
2735
+ return null;
2736
+ }
2737
+ if (next && /[A-Za-z_]/.test(next)) {
2738
+ let j = i + 2;
2739
+ while (j < segment.length && /[A-Za-z0-9_]/.test(segment[j])) j++;
2740
+ return { text: segment.slice(i, j), end: j };
2741
+ }
2742
+ return null;
2743
+ }
2744
+
2745
+ // src/core/bash-guard.ts
2746
+ var require2 = createRequire(import.meta.url);
2747
+ var SAFE_GIT_GLOBALS2 = /* @__PURE__ */ new Set([
2748
+ "--no-pager",
2749
+ "-P",
2750
+ "--paginate",
2751
+ "-p",
2752
+ "--literal-pathspecs",
2753
+ "--no-optional-locks",
2754
+ "--no-replace-objects"
2755
+ ]);
2756
+ function refUpdateResyncRoots(command, startDir) {
2757
+ const dirs = [];
2758
+ const ops = parseRefOps(command, startDir);
2759
+ if (ops) {
2760
+ for (const op of ops) {
2761
+ if (op.kind === "update-ref" && !op.stdin && op.ref) dirs.push(op.dir);
2762
+ }
2763
+ }
2764
+ if (dirs.length === 0) dirs.push(...casCommandDirectories(command, startDir));
2765
+ if (dirs.length === 0) return [];
2766
+ let anchor = null;
2767
+ try {
2768
+ anchor = discoverRepository(startDir).commonGitDir;
2769
+ } catch {
2770
+ anchor = null;
2771
+ }
2772
+ const roots = [];
2773
+ for (const dir of dirs) {
2774
+ let checkout;
2775
+ let common;
2776
+ try {
2777
+ const layout = discoverRepository(dir);
2778
+ checkout = layout.checkoutRoot;
2779
+ common = layout.commonGitDir;
2780
+ } catch {
2781
+ continue;
2782
+ }
2783
+ if (!common) continue;
2784
+ if (anchor && common !== anchor) continue;
2785
+ if (!roots.includes(checkout)) roots.push(checkout);
2786
+ }
2787
+ return roots;
2788
+ }
2789
+ function sharedRefUpdatesAreOwned(command, startDir, agent, peers) {
2790
+ const ops = parseRefOps(command, startDir);
2791
+ if (!ops) return false;
2792
+ if (ops.some((op) => op.kind === "block")) return false;
2793
+ const needsOwner = ops.some((op) => op.kind === "update-ref" || op.kind === "symbolic-write");
2794
+ if (!needsOwner) return true;
2795
+ if (!agent?.worktree_path || !agent.branch) return false;
2796
+ const owner = isolatedOwner(agent, peers);
2797
+ for (const op of ops) {
2798
+ if (op.kind === "update-ref" && !updateRefOwned(op, owner)) return false;
2799
+ if (op.kind === "symbolic-write" && !symbolicWriteOwned(op, owner)) return false;
2800
+ }
2801
+ return true;
2802
+ }
2803
+ function isolatedOwner(agent, peers) {
2804
+ if (!agent.worktree_path || !agent.branch) return null;
2805
+ let worktree;
2806
+ try {
2807
+ worktree = physicalPath(agent.worktree_path);
2808
+ } catch {
2809
+ return null;
2810
+ }
2811
+ const main = mainCheckout2(worktree);
2812
+ if (!main || main.path === worktree) return null;
2813
+ if (main.branch && agent.branch === main.branch) return null;
2814
+ for (const peer of peers) {
2815
+ if (peer.branch === agent.branch) return null;
2816
+ try {
2817
+ if (physicalPath(peer.worktree_path ?? main.path) === worktree) return null;
2818
+ } catch {
2819
+ return null;
2820
+ }
2821
+ }
2822
+ return { worktree, branch: agent.branch, integrationBranch: main.branch };
2823
+ }
2824
+ function mainCheckout2(cwd) {
2825
+ let out;
2826
+ try {
2827
+ out = execFileSync7("git", ["worktree", "list", "--porcelain"], {
2828
+ cwd,
2829
+ encoding: "utf8",
2830
+ stdio: ["ignore", "pipe", "ignore"],
2831
+ timeout: 5e3
2832
+ });
2833
+ } catch {
2834
+ return null;
2835
+ }
2836
+ const first = out.split(/\n\s*\n/)[0] ?? "";
2837
+ let wt = null;
2838
+ let branch = null;
2839
+ let detached = false;
2840
+ for (const line of first.split("\n")) {
2841
+ if (line.startsWith("worktree ")) wt = line.slice("worktree ".length).trim();
2842
+ else if (line.startsWith("branch ")) branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
2843
+ else if (line === "detached" || line.startsWith("detached ")) detached = true;
2844
+ }
2845
+ if (!wt) return null;
2846
+ try {
2847
+ return { path: physicalPath(wt), branch: detached ? null : branch };
2848
+ } catch {
2849
+ return null;
2850
+ }
2851
+ }
2852
+ function updateRefOwned(op, owner) {
2853
+ if (op.stdin || !owner || !directoryInside2(op.dir, owner.worktree)) return false;
2854
+ if (op.ref === "HEAD") {
2855
+ if (op.noDeref) return true;
2856
+ const checked2 = checkedOutBranch2(op.dir);
2857
+ if (!checked2.ok) return false;
2858
+ if (checked2.branch === null) return true;
2859
+ return checked2.branch === owner.branch && checked2.branch !== owner.integrationBranch;
2860
+ }
2861
+ const branch = headsBranch(op.ref);
2862
+ if (!branch || branch !== owner.branch || branch === owner.integrationBranch) return false;
2863
+ const checked = checkedOutBranch2(op.dir);
2864
+ return checked.ok && checked.branch === branch;
2865
+ }
2866
+ function symbolicWriteOwned(op, owner) {
2867
+ if (op.delete || !op.target || !owner || op.name !== "HEAD") return false;
2868
+ if (!directoryInside2(op.dir, owner.worktree)) return false;
2869
+ if (owner.integrationBranch && owner.branch === owner.integrationBranch) return false;
2870
+ return op.target === `refs/heads/${owner.branch}`;
2871
+ }
2872
+ function headsBranch(ref) {
2873
+ if (!ref.startsWith("refs/heads/")) return null;
2874
+ const name = ref.slice("refs/heads/".length);
2875
+ if (!name || name.startsWith("/") || name.endsWith("/") || name.includes("@{") || name.includes("..")) return null;
2876
+ return name;
2877
+ }
2878
+ function directoryInside2(dir, worktree) {
2879
+ try {
2880
+ const resolved = physicalPath(dir);
2881
+ return resolved === worktree || isWithin(worktree, resolved);
2882
+ } catch {
2883
+ return false;
2884
+ }
2885
+ }
2886
+ function checkedOutBranch2(dir) {
2887
+ try {
2888
+ const out = execFileSync7("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
2889
+ cwd: dir,
2890
+ encoding: "utf8",
2891
+ stdio: ["ignore", "pipe", "ignore"],
2892
+ timeout: 5e3
2893
+ }).trim();
2894
+ return { ok: true, branch: out || null };
2895
+ } catch (error) {
2896
+ if (error.status === 1) return { ok: true, branch: null };
2897
+ return { ok: false };
2898
+ }
2899
+ }
2900
+ function parseRefOps(command, startDir) {
2901
+ const segments = splitShellSegments2(command);
2902
+ if (!segments) return null;
2903
+ let cwd = path7.resolve(startDir);
2904
+ let trusted = true;
2905
+ const ops = [];
2906
+ for (const segment of segments) {
2907
+ const words = shellWords(segment.raw);
2908
+ const matched = DESTRUCTIVE_SHARED_REFS.test(segment.raw);
2909
+ if (!words) {
2910
+ if (matched) ops.push({ kind: "block" });
2911
+ if (continuesShell2(segment.nextSep) && /\b(?:cd|pushd|popd|export|source)\b|\bGIT_DIR\b/.test(segment.raw)) trusted = false;
2912
+ continue;
2913
+ }
2914
+ const { danger, argv } = stripLeadingEnv2(words);
2915
+ if (argv.length === 0) continue;
2916
+ const head = argv[0];
2917
+ if (head === "cd") {
2918
+ const next = applyCd2(argv, cwd);
2919
+ if (next && continuesShell2(segment.nextSep)) cwd = next;
2920
+ else if (!next && continuesShell2(segment.nextSep)) trusted = false;
2921
+ continue;
2922
+ }
2923
+ if (head === "pushd" || head === "popd" || head === "source" || head === "." && argv.length > 1) {
2924
+ if (continuesShell2(segment.nextSep)) trusted = false;
2925
+ continue;
2926
+ }
2927
+ if (head === "export") {
2928
+ if (argv.slice(1).some((arg) => dangerousGitEnv2(arg.split("=")[0] ?? arg))) trusted = false;
2929
+ continue;
2930
+ }
2931
+ if (!isGitBinary2(head) || danger || !trusted) {
2932
+ if (matched) ops.push({ kind: "block" });
2933
+ continue;
2934
+ }
2935
+ const parsed = parseGitInvocation(argv, cwd);
2936
+ if (parsed.kind === "unclassified") {
2937
+ if (matched) ops.push({ kind: "block" });
2938
+ continue;
2939
+ }
2940
+ if (parsed.kind !== "other") ops.push(parsed);
2941
+ }
2942
+ return ops;
2943
+ }
2944
+ function continuesShell2(sep) {
2945
+ return sep === "&&" || sep === ";" || sep === "\n";
2946
+ }
2947
+ function splitShellSegments2(command) {
2948
+ const parts = [];
2949
+ let buf = "";
2950
+ let quote = null;
2951
+ const push = (sep) => {
2952
+ const raw = buf.trim();
2953
+ buf = "";
2954
+ if (raw) parts.push({ raw, nextSep: sep });
2955
+ };
2956
+ for (let i = 0; i < command.length; i++) {
2957
+ const ch = command[i];
2958
+ if (quote === "'") {
2959
+ buf += ch;
2960
+ if (ch === "'") quote = null;
2961
+ continue;
2962
+ }
2963
+ if (quote === '"') {
2964
+ if (ch === "\\" && i + 1 < command.length) {
2965
+ const next = command[i + 1];
2966
+ if (next === "$" || next === "`" || next === '"' || next === "\\" || next === "\n") {
2967
+ buf += ch + next;
2968
+ i++;
2969
+ continue;
2970
+ }
2971
+ }
2972
+ buf += ch;
2973
+ if (ch === '"') quote = null;
2974
+ continue;
2975
+ }
2976
+ if (ch === "\\" && i + 1 < command.length) {
2977
+ if (command[i + 1] === "\n") {
2978
+ i++;
2979
+ continue;
2980
+ }
2981
+ buf += ch + command[i + 1];
2982
+ i++;
2983
+ continue;
2984
+ }
2985
+ if (ch === "'" || ch === '"') {
2986
+ quote = ch;
2987
+ buf += ch;
2988
+ continue;
2989
+ }
2990
+ if (ch === "&" && command[i + 1] === "&") {
2991
+ push("&&");
2992
+ i++;
2993
+ continue;
2994
+ }
2995
+ if (ch === "|" && command[i + 1] === "|") {
2996
+ push("||");
2997
+ i++;
2998
+ continue;
2999
+ }
3000
+ if (ch === "\r" && command[i + 1] === "\n") {
3001
+ push("\n");
3002
+ i++;
3003
+ continue;
3004
+ }
3005
+ if (ch === "\n") {
3006
+ push("\n");
3007
+ continue;
3008
+ }
3009
+ if (ch === ";") {
3010
+ push(";");
3011
+ continue;
3012
+ }
3013
+ if (ch === "|") {
3014
+ push("|");
3015
+ continue;
3016
+ }
3017
+ if (ch === "&") {
3018
+ push("&");
3019
+ continue;
3020
+ }
3021
+ buf += ch;
3022
+ }
3023
+ if (quote) return null;
3024
+ push("end");
3025
+ return parts;
3026
+ }
3027
+ function shellWords(segment) {
3028
+ const words = [];
3029
+ let buf = "";
3030
+ let quote = null;
3031
+ let word = false;
3032
+ const flush = () => {
3033
+ if (word) words.push(buf);
3034
+ buf = "";
3035
+ word = false;
3036
+ };
3037
+ for (let i = 0; i < segment.length; i++) {
3038
+ const ch = segment[i];
3039
+ if (quote === "'") {
3040
+ if (ch === "'") quote = null;
3041
+ else {
3042
+ buf += ch;
3043
+ word = true;
3044
+ }
3045
+ continue;
3046
+ }
3047
+ if (quote === '"') {
3048
+ if (ch === "\\" && i + 1 < segment.length) {
3049
+ const next = segment[i + 1];
3050
+ if ('$`"\\'.includes(next)) {
3051
+ buf += next;
3052
+ word = true;
3053
+ i++;
3054
+ continue;
3055
+ }
3056
+ if (next === "\n") {
3057
+ i++;
3058
+ continue;
3059
+ }
3060
+ }
3061
+ if (ch === '"') {
3062
+ quote = null;
3063
+ word = true;
3064
+ continue;
3065
+ }
3066
+ if (ch === "`" || ch === "$") return null;
3067
+ buf += ch;
3068
+ word = true;
3069
+ continue;
3070
+ }
3071
+ if (ch === "\\" && i + 1 < segment.length) {
3072
+ buf += segment[i + 1];
3073
+ word = true;
3074
+ i++;
3075
+ continue;
3076
+ }
3077
+ if (ch === "'" || ch === '"') {
3078
+ quote = ch;
3079
+ word = true;
3080
+ continue;
3081
+ }
3082
+ if (ch === "`" || ch === "$" || ch === "(" || ch === ")" || ch === "<" || ch === ">") return null;
3083
+ if (ch === "#" && !word) break;
3084
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
3085
+ flush();
3086
+ continue;
3087
+ }
3088
+ buf += ch;
3089
+ word = true;
3090
+ }
3091
+ if (quote) return null;
3092
+ flush();
3093
+ return words;
3094
+ }
3095
+ function stripLeadingEnv2(argv) {
3096
+ let i = 0;
3097
+ let danger = false;
3098
+ while (i < argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[i])) {
3099
+ if (dangerousGitEnv2(argv[i].slice(0, argv[i].indexOf("=")))) danger = true;
3100
+ i++;
3101
+ }
3102
+ return { danger, argv: argv.slice(i) };
3103
+ }
3104
+ function dangerousGitEnv2(name) {
3105
+ return name === "GIT_DIR" || name === "GIT_WORK_TREE" || name === "GIT_COMMON_DIR" || name === "GIT_NAMESPACE" || name === "GIT_OBJECT_DIRECTORY" || name === "GIT_ALTERNATE_OBJECT_DIRECTORIES" || name === "GIT_CONFIG_PARAMETERS" || name === "GIT_CONFIG_COUNT" || name === "GIT_CONFIG_GLOBAL" || name === "GIT_CONFIG_SYSTEM" || /^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(name);
3106
+ }
3107
+ function applyCd2(argv, cwd) {
3108
+ let args = argv.slice(1);
3109
+ if (args[0] === "--") args = args.slice(1);
3110
+ if (args.length !== 1 || args[0] === "-" || args[0].startsWith("-") || args[0].startsWith("~")) return null;
3111
+ return path7.resolve(cwd, args[0]);
3112
+ }
3113
+ function isGitBinary2(word) {
3114
+ const base = word.slice(Math.max(word.lastIndexOf("/"), word.lastIndexOf("\\")) + 1);
3115
+ return base === "git" || base.toLowerCase() === "git.exe";
3116
+ }
3117
+ function parseGitInvocation(argv, cwd) {
3118
+ let i = 1;
3119
+ let dir = cwd;
3120
+ while (i < argv.length) {
3121
+ const token = argv[i];
3122
+ if (token === "--") {
3123
+ i++;
3124
+ break;
3125
+ }
3126
+ if (token === "-C") {
3127
+ const next = argv[i + 1];
3128
+ if (next === void 0 || next.startsWith("~")) return { kind: "unclassified" };
3129
+ if (next !== "") dir = path7.isAbsolute(next) ? next : path7.resolve(dir, next);
3130
+ i += 2;
3131
+ continue;
3132
+ }
3133
+ if (token.startsWith("-C") && token.length > 2) {
3134
+ const next = token.slice(2);
3135
+ if (next.startsWith("~")) return { kind: "unclassified" };
3136
+ dir = path7.isAbsolute(next) ? next : path7.resolve(dir, next);
3137
+ i++;
3138
+ continue;
3139
+ }
3140
+ if (SAFE_GIT_GLOBALS2.has(token)) {
3141
+ i++;
3142
+ continue;
3143
+ }
3144
+ if (token.startsWith("-")) return { kind: "unclassified" };
3145
+ break;
3146
+ }
3147
+ const sub = argv[i];
3148
+ if (!sub) return { kind: "other" };
3149
+ const args = argv.slice(i + 1);
3150
+ if (sub === "update-ref") return parseUpdateRef(dir, args);
3151
+ if (sub === "symbolic-ref") return parseSymbolicRef(dir, args);
3152
+ if (sub === "worktree") return args.some((arg) => arg === "remove" || arg === "prune") ? { kind: "block" } : { kind: "other" };
3153
+ if (sub === "branch") return branchArgsAreDestructive(args) ? { kind: "block" } : { kind: "other" };
3154
+ return { kind: "other" };
3155
+ }
3156
+ function branchArgsAreDestructive(args) {
3157
+ for (const arg of args) {
3158
+ if (arg === "--") break;
3159
+ if (arg === "--delete" || arg === "--move" || arg === "--force") return true;
3160
+ if (arg.startsWith("--delete") || arg.startsWith("--move") || arg.startsWith("--force")) return true;
3161
+ if (arg.startsWith("-") && !arg.startsWith("--") && /[dDmMfF]/.test(arg.slice(1))) return true;
3162
+ }
3163
+ return false;
3164
+ }
3165
+ function parseUpdateRef(dir, args) {
3166
+ let noDeref = false;
3167
+ let deleteRef = false;
3168
+ let stdin = false;
3169
+ let end = false;
3170
+ const positionals = [];
3171
+ for (let i = 0; i < args.length; i++) {
3172
+ const arg = args[i];
3173
+ if (!end && arg === "--") {
3174
+ end = true;
3175
+ continue;
3176
+ }
3177
+ if (!end && arg.startsWith("-")) {
3178
+ if (arg === "--no-deref") {
3179
+ noDeref = true;
3180
+ continue;
3181
+ }
3182
+ if (arg === "--deref") {
3183
+ noDeref = false;
3184
+ continue;
3185
+ }
3186
+ if (arg === "--create-reflog" || arg === "--no-create-reflog" || arg === "--no-stdin") continue;
3187
+ if (arg === "--stdin" || arg === "-z") {
3188
+ stdin = true;
3189
+ continue;
3190
+ }
3191
+ if (arg === "-d") {
3192
+ deleteRef = true;
3193
+ continue;
3194
+ }
3195
+ if (arg === "-m" || arg === "--message") {
3196
+ if (args[i + 1] === void 0) return { kind: "unclassified" };
3197
+ i++;
3198
+ continue;
3199
+ }
3200
+ if (arg.startsWith("-m") && arg.length > 2) continue;
3201
+ if (arg.startsWith("--message=")) continue;
3202
+ return { kind: "unclassified" };
3203
+ }
3204
+ positionals.push(arg);
3205
+ }
3206
+ if (stdin) return { kind: "update-ref", dir, ref: "", noDeref, stdin: true };
3207
+ const expected = deleteRef ? [1, 2] : [2, 3];
3208
+ if (!expected.includes(positionals.length) || !positionals[0]) return { kind: "unclassified" };
3209
+ return { kind: "update-ref", dir, ref: positionals[0], noDeref, stdin: false };
3210
+ }
3211
+ function parseSymbolicRef(dir, args) {
3212
+ let deleteRef = false;
3213
+ let end = false;
3214
+ const positionals = [];
3215
+ for (let i = 0; i < args.length; i++) {
3216
+ const arg = args[i];
3217
+ if (!end && arg === "--") {
3218
+ end = true;
3219
+ continue;
3220
+ }
3221
+ if (!end && arg.startsWith("-")) {
3222
+ if (arg === "-q" || arg === "--quiet" || arg === "--no-quiet" || arg === "--short" || arg === "--no-short") continue;
3223
+ if (arg === "--recurse" || arg === "--no-recurse") continue;
3224
+ if (arg === "-d" || arg === "--delete") {
3225
+ deleteRef = true;
3226
+ continue;
3227
+ }
3228
+ if (arg === "--no-delete") {
3229
+ deleteRef = false;
3230
+ continue;
3231
+ }
3232
+ if (arg === "-m" || arg === "--message") {
3233
+ if (args[i + 1] === void 0) return { kind: "unclassified" };
3234
+ i++;
3235
+ continue;
3236
+ }
3237
+ if (arg.startsWith("-m") && arg.length > 2) continue;
3238
+ if (arg.startsWith("--message=")) continue;
3239
+ return { kind: "unclassified" };
3240
+ }
3241
+ positionals.push(arg);
1618
3242
  }
1619
- };
1620
-
1621
- // src/core/bash-guard.ts
1622
- var GIT_PREFIX = String.raw`\bgit(?:\s+(?:-C|-c|--git-dir|--work-tree)(?:=|\s+)(?:"[^"]*"|'[^']*'|[^\s;&|]+)|\s+--(?:no-pager|literal-pathspecs|no-optional-locks))*\s+`;
1623
- var DESTRUCTIVE_SHARED_TREE = new RegExp(GIT_PREFIX + String.raw`(?:reset|clean|checkout|restore|switch|stash|merge|rebase|pull|cherry-pick|revert|am)\b`);
1624
- var DESTRUCTIVE_SHARED_REFS = new RegExp(GIT_PREFIX + String.raw`(?:update-ref|symbolic-ref|worktree\s+(?:remove|prune)|branch\s+(?:-[dDmMfF]|--(?:delete|move|force)))\b`);
3243
+ if (deleteRef) {
3244
+ if (positionals.length !== 1) return { kind: "unclassified" };
3245
+ return { kind: "symbolic-write", dir, name: positionals[0], target: null, delete: true };
3246
+ }
3247
+ if (positionals.length === 1) return { kind: "symbolic-read" };
3248
+ if (positionals.length === 2) return { kind: "symbolic-write", dir, name: positionals[0], target: positionals[1], delete: false };
3249
+ return { kind: "unclassified" };
3250
+ }
1625
3251
  var WRITE_PRIMITIVE_RE = /(?:>>?|\b(?:tee|rm|mv|cp|dd|patch|truncate|touch|unlink|writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream)\b|\bsed\s+(?:-[a-zA-Z]*i|--in-place)|\bperl\s+-[a-zA-Z]*i|\.write_(?:text|bytes)\(|open\([^)]*['"][wa+])/u;
1626
3252
  var READ_ONLY_CMD_RE = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|[^\s;&|]+)\s+)*(?:ls|tail|head|cat|less|more|grep|egrep|fgrep|rg|find|fd|wc|stat|file|du|df|pwd|echo|printf|true|false|which|whereis|type|uname|whoami|id|date|env|printenv|ps|lsof|jq|awk|cut|sort|uniq|tr|diff|shasum|sha256sum|md5|git\s+(?:status|diff|log|show|branch|rev-parse|ls-files|check-ignore| blame)\b|kith\s+(?:status|brief|doctor|mode|lock\s+list|task\s+list|handoff\s+list)\b|(?:node\s+)?(?:\S*\/)?stack\.mjs\s+status\b)/u;
1627
3253
  function isReadOnlyShellCommand(command) {
@@ -1637,7 +3263,7 @@ function commandTargetsFileForWrite(command, relPath) {
1637
3263
  if (!WRITE_PRIMITIVE_RE.test(stripped)) return false;
1638
3264
  const norm = relPath.replace(/\\/g, "/");
1639
3265
  if (stripped.includes(norm)) return true;
1640
- const base = path6.posix.basename(norm);
3266
+ const base = path7.posix.basename(norm);
1641
3267
  return base.length >= 4 && stripped.includes(base);
1642
3268
  }
1643
3269
  var BashMerkleGuard = class _BashMerkleGuard {
@@ -1658,21 +3284,76 @@ var BashMerkleGuard = class _BashMerkleGuard {
1658
3284
  */
1659
3285
  checkCommandSafety(params) {
1660
3286
  this.fencing.assertSession(params.agentId);
1661
- const root = physicalPath(this.fencing.getAgent(params.agentId)?.worktree_path ?? this.coordDb.repoRoot);
3287
+ const agent = this.fencing.getAgent(params.agentId);
3288
+ const repoRoot = this.coordDb.repoRoot;
3289
+ const root = physicalPath(agent?.worktree_path ?? repoRoot);
1662
3290
  const peers = this.fencing.listAgents(true).filter((a) => a.id !== params.agentId);
1663
- const sharesCheckout = peers.some((a) => physicalPath(a.worktree_path ?? this.coordDb.repoRoot) === root);
1664
- if (peers.length && DESTRUCTIVE_SHARED_REFS.test(params.command) || sharesCheckout && DESTRUCTIVE_SHARED_TREE.test(params.command)) {
1665
- return {
1666
- safe: false,
1667
- reason: 'Git operation can replace shared work or refs while peer agents are active. To commit only your own files safely while peers are active, run: kith commit -m "<message>" [files...]'
1668
- };
3291
+ const sharesCheckout = peers.some((a) => physicalPath(a.worktree_path ?? repoRoot) === root);
3292
+ const startDir = agent?.worktree_path ?? repoRoot;
3293
+ const refuse = (specific) => ({
3294
+ safe: false,
3295
+ reason: firewallReason(suggestKithCommit(this.refHost(params.agentId), params.command), specific)
3296
+ });
3297
+ if (peers.length && sharesCheckout && commandMovesSharedCheckout(params.command)) {
3298
+ const foreign = foreignRefLease(this.coordDb.coordDir, params.agentId);
3299
+ if (foreign) {
3300
+ return refuse(`Agent ${foreign.agentId} is verifying a shared-checkout commit; retry shortly.`);
3301
+ }
3302
+ }
3303
+ if (peers.length && DESTRUCTIVE_SHARED_REFS.test(params.command) && !sharedRefUpdatesAreOwned(params.command, startDir, agent, peers)) {
3304
+ try {
3305
+ const decision = assessSharedCheckoutUpdate(this.refHost(params.agentId), params.command, startDir);
3306
+ if (decision.action === "allow") return { safe: true };
3307
+ if (decision.action === "defer") return { safe: true, deferred: true };
3308
+ if (decision.action === "block" && decision.reason) return { safe: false, reason: decision.reason };
3309
+ } catch {
3310
+ return refuse("The shared-checkout update could not be verified.");
3311
+ }
3312
+ return refuse();
3313
+ }
3314
+ if (sharesCheckout && DESTRUCTIVE_SHARED_TREE.test(params.command)) {
3315
+ return refuse();
1669
3316
  }
1670
3317
  return { safe: true };
1671
3318
  }
3319
+ /**
3320
+ * Post-hook half of a deferred shared-checkout update-ref. Literal SHAs are decided in
3321
+ * checkCommandSafety; shell variables are checked against the commit that landed.
3322
+ */
3323
+ settleDeferredRefUpdate(params) {
3324
+ return settleDeferredRefUpdate(this.refHost(params.agentId), params.command);
3325
+ }
3326
+ refHost(agentId) {
3327
+ const agent = this.fencing.getAgent(agentId);
3328
+ return {
3329
+ repoRoot: this.coordDb.repoRoot,
3330
+ coordDir: this.coordDb.coordDir,
3331
+ agentId,
3332
+ agent,
3333
+ locks: this.lockEngine.listLocks(),
3334
+ tasks: this.recordedTasks(),
3335
+ presenceTouched: presenceTouchedFor(this.coordDb.commonGitDir, agent),
3336
+ logEvent: (id, type, payload) => this.coordDb.logEvent(id, type, payload)
3337
+ };
3338
+ }
3339
+ recordedTasks() {
3340
+ try {
3341
+ const rows = this.coordDb.db.prepare(
3342
+ `SELECT owner_agent_id, status, scope_globs_json FROM tasks`
3343
+ ).all();
3344
+ return rows.map((row) => ({
3345
+ owner_agent_id: row.owner_agent_id,
3346
+ status: row.status,
3347
+ scope_globs: parseScopeGlobs(row.scope_globs_json)
3348
+ }));
3349
+ } catch {
3350
+ return [];
3351
+ }
3352
+ }
1672
3353
  getSnapshotFilePath(agentId) {
1673
3354
  const epoch = this.fencing.assertSession(agentId);
1674
- const safeId = crypto5.createHash("sha256").update(`${agentId}:${epoch}`).digest("hex");
1675
- return path6.join(this.coordDb.coordDir, "snapshots", `${safeId}.json`);
3355
+ const safeId = crypto6.createHash("sha256").update(`${agentId}:${epoch}`).digest("hex");
3356
+ return path7.join(this.coordDb.coordDir, "snapshots", `${safeId}.json`);
1676
3357
  }
1677
3358
  /**
1678
3359
  * Captures a Merkle snapshot of workspace files before a Bash tool execution.
@@ -1683,9 +3364,9 @@ var BashMerkleGuard = class _BashMerkleGuard {
1683
3364
  const activeLocks = this.lockEngine.listLocks().filter((l) => l.owner_agent_id !== agentId);
1684
3365
  const snapPath = this.getSnapshotFilePath(agentId);
1685
3366
  let prevEntries = {};
1686
- if (fs6.existsSync(snapPath)) {
3367
+ if (fs7.existsSync(snapPath)) {
1687
3368
  try {
1688
- const parsed = JSON.parse(fs6.readFileSync(snapPath, "utf8"));
3369
+ const parsed = JSON.parse(fs7.readFileSync(snapPath, "utf8"));
1689
3370
  if (parsed.rootDir === rootDir && parsed.entries) prevEntries = parsed.entries;
1690
3371
  } catch {
1691
3372
  }
@@ -1694,8 +3375,8 @@ var BashMerkleGuard = class _BashMerkleGuard {
1694
3375
  const entries = {};
1695
3376
  const files = this.walkWorkspaceFiles(rootDir);
1696
3377
  for (const absPath of files) {
1697
- const relPath = path6.relative(rootDir, absPath).replace(/\\/g, "/");
1698
- const stat = fs6.statSync(absPath);
3378
+ const relPath = path7.relative(rootDir, absPath).replace(/\\/g, "/");
3379
+ const stat = fs7.statSync(absPath);
1699
3380
  if (stat.size > 5 * 1024 * 1024) continue;
1700
3381
  const lockedByOther = activeLocks.some(
1701
3382
  (l) => LockEngine.patternsOverlap(relPath, l.pattern)
@@ -1710,8 +3391,8 @@ var BashMerkleGuard = class _BashMerkleGuard {
1710
3391
  };
1711
3392
  continue;
1712
3393
  }
1713
- const buf = fs6.readFileSync(absPath);
1714
- const sha256 = unchanged ? cached.sha256 : crypto5.createHash("sha256").update(buf).digest("hex");
3394
+ const buf = fs7.readFileSync(absPath);
3395
+ const sha256 = unchanged ? cached.sha256 : crypto6.createHash("sha256").update(buf).digest("hex");
1715
3396
  entries[relPath] = {
1716
3397
  relPath,
1717
3398
  mtimeMs: stat.mtimeMs,
@@ -1721,7 +3402,7 @@ var BashMerkleGuard = class _BashMerkleGuard {
1721
3402
  backupContentBase64: lockedByOther ? buf.toString("base64") : void 0
1722
3403
  };
1723
3404
  }
1724
- fs6.writeFileSync(
3405
+ fs7.writeFileSync(
1725
3406
  snapPath,
1726
3407
  JSON.stringify({ timestamp: Date.now(), rootDir, entries }),
1727
3408
  { encoding: "utf8", mode: 384 }
@@ -1735,10 +3416,10 @@ var BashMerkleGuard = class _BashMerkleGuard {
1735
3416
  */
1736
3417
  verifyPostBashAndQuarantine(params) {
1737
3418
  const snapPath = this.getSnapshotFilePath(params.agentId);
1738
- if (!fs6.existsSync(snapPath)) {
3419
+ if (!fs7.existsSync(snapPath)) {
1739
3420
  return { allowed: true, authorizedModifiedFiles: [], quarantinedViolations: [] };
1740
3421
  }
1741
- const rawSnap = JSON.parse(fs6.readFileSync(snapPath, "utf8"));
3422
+ const rawSnap = JSON.parse(fs7.readFileSync(snapPath, "utf8"));
1742
3423
  const rootDir = params.rootDir ?? rawSnap.rootDir ?? this.coordDb.repoRoot;
1743
3424
  const beforeEntries = rawSnap.entries;
1744
3425
  const currentFiles = this.walkWorkspaceFiles(rootDir);
@@ -1747,16 +3428,16 @@ var BashMerkleGuard = class _BashMerkleGuard {
1747
3428
  const authorizedModifiedFiles = [];
1748
3429
  const quarantinedViolations = [];
1749
3430
  for (const absPath of currentFiles) {
1750
- const relPath = path6.relative(rootDir, absPath).replace(/\\/g, "/");
3431
+ const relPath = path7.relative(rootDir, absPath).replace(/\\/g, "/");
1751
3432
  seenCurrentRelPaths.add(relPath);
1752
- const stat = fs6.statSync(absPath);
3433
+ const stat = fs7.statSync(absPath);
1753
3434
  if (stat.size > 5 * 1024 * 1024) continue;
1754
3435
  const prev = beforeEntries[relPath];
1755
3436
  if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
1756
3437
  continue;
1757
3438
  }
1758
- const buf = fs6.readFileSync(absPath);
1759
- const sha256 = crypto5.createHash("sha256").update(buf).digest("hex");
3439
+ const buf = fs7.readFileSync(absPath);
3440
+ const sha256 = crypto6.createHash("sha256").update(buf).digest("hex");
1760
3441
  if (prev && prev.sha256 === sha256) {
1761
3442
  continue;
1762
3443
  }
@@ -1810,14 +3491,14 @@ var BashMerkleGuard = class _BashMerkleGuard {
1810
3491
  }
1811
3492
  }
1812
3493
  try {
1813
- fs6.unlinkSync(snapPath);
3494
+ fs7.unlinkSync(snapPath);
1814
3495
  } catch {
1815
3496
  }
1816
3497
  if (authorizedModifiedFiles.length > 0) {
1817
3498
  for (const relFile of authorizedModifiedFiles) {
1818
- const absFile = path6.join(rootDir, relFile);
1819
- if (fs6.existsSync(absFile) && /\.(ts|tsx|js|jsx|mjs|py)$/.test(relFile)) {
1820
- this.depGraph.recordFileModification(params.agentId, relFile, fs6.readFileSync(absFile, "utf8"));
3499
+ const absFile = path7.join(rootDir, relFile);
3500
+ if (fs7.existsSync(absFile) && /\.(ts|tsx|js|jsx|mjs|py)$/.test(relFile)) {
3501
+ this.depGraph.recordFileModification(params.agentId, relFile, fs7.readFileSync(absFile, "utf8"));
1821
3502
  }
1822
3503
  }
1823
3504
  this.shadowGit.probeAllActiveConflicts(
@@ -1833,31 +3514,31 @@ var BashMerkleGuard = class _BashMerkleGuard {
1833
3514
  };
1834
3515
  }
1835
3516
  quarantineAndRevertFile(params) {
1836
- const id = `quar_${crypto5.randomBytes(6).toString("hex")}`;
3517
+ const id = `quar_${crypto6.randomBytes(6).toString("hex")}`;
1837
3518
  const now = Date.now();
1838
3519
  const safeName = params.relPath.replace(/[^a-zA-Z0-9._-]/g, "_");
1839
- const patchPath = path6.join(
3520
+ const patchPath = path7.join(
1840
3521
  this.coordDb.coordDir,
1841
3522
  "quarantine",
1842
3523
  `${id}_${safeName}.quarantine`
1843
3524
  );
1844
3525
  if (params.unauthorizedBuf) {
1845
- fs6.writeFileSync(patchPath, params.unauthorizedBuf, { mode: 384 });
3526
+ fs7.writeFileSync(patchPath, params.unauthorizedBuf, { mode: 384 });
1846
3527
  } else {
1847
- fs6.writeFileSync(patchPath, `[DELETED BY COMMAND: ${params.command}]
3528
+ fs7.writeFileSync(patchPath, `[DELETED BY COMMAND: ${params.command}]
1848
3529
  `, { encoding: "utf8", mode: 384 });
1849
3530
  }
1850
3531
  if (params.prevEntry?.backupContentBase64 !== void 0) {
1851
- fs6.writeFileSync(patchPath + ".before", Buffer.from(params.prevEntry.backupContentBase64, "base64"), { mode: 384 });
3532
+ fs7.writeFileSync(patchPath + ".before", Buffer.from(params.prevEntry.backupContentBase64, "base64"), { mode: 384 });
1852
3533
  }
1853
- const absTarget = path6.join(params.rootDir, params.relPath);
3534
+ const absTarget = path7.join(params.rootDir, params.relPath);
1854
3535
  if (params.restoreLockedFiles && params.prevEntry === null) {
1855
- if (fs6.existsSync(absTarget)) {
1856
- fs6.unlinkSync(absTarget);
3536
+ if (fs7.existsSync(absTarget)) {
3537
+ fs7.unlinkSync(absTarget);
1857
3538
  }
1858
3539
  } else if (params.restoreLockedFiles && params.prevEntry?.backupContentBase64 !== void 0) {
1859
- fs6.mkdirSync(path6.dirname(absTarget), { recursive: true });
1860
- fs6.writeFileSync(
3540
+ fs7.mkdirSync(path7.dirname(absTarget), { recursive: true });
3541
+ fs7.writeFileSync(
1861
3542
  absTarget,
1862
3543
  Buffer.from(params.prevEntry.backupContentBase64, "base64")
1863
3544
  );
@@ -1916,12 +3597,36 @@ var BashMerkleGuard = class _BashMerkleGuard {
1916
3597
  return this.coordDb.db.prepare(`SELECT * FROM quarantine ORDER BY created_at DESC`).all();
1917
3598
  }
1918
3599
  };
3600
+ function parseScopeGlobs(raw) {
3601
+ try {
3602
+ const parsed = JSON.parse(raw);
3603
+ return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : [];
3604
+ } catch {
3605
+ return [];
3606
+ }
3607
+ }
3608
+ function presenceTouchedFor(commonGitDir, agent) {
3609
+ if (!commonGitDir || !agent) return [];
3610
+ try {
3611
+ const { listRepoPresence: listRepoPresence2, ownedByCaller: ownedByCaller2 } = require2("../cli/auto-session.js");
3612
+ const peers = listRepoPresence2(void 0, commonGitDir);
3613
+ const touched = /* @__PURE__ */ new Set();
3614
+ for (const peer of peers) {
3615
+ if (peer.agentId === agent.id) for (const file of peer.touchedFiles) touched.add(file);
3616
+ }
3617
+ const byPid = peers.filter((peer) => ownedByCaller2(peer.pid, agent.pid));
3618
+ if (byPid.length === 1) for (const file of byPid[0].touchedFiles) touched.add(file);
3619
+ return [...touched];
3620
+ } catch {
3621
+ return [];
3622
+ }
3623
+ }
1919
3624
 
1920
3625
  // src/core/broker.ts
1921
- import { fork } from "child_process";
1922
- import fs7 from "fs";
3626
+ import { execFileSync as execFileSync8, fork } from "child_process";
3627
+ import fs8 from "fs";
1923
3628
  import { fileURLToPath } from "url";
1924
- import crypto6 from "crypto";
3629
+ import crypto7 from "crypto";
1925
3630
  import net from "net";
1926
3631
  var ResourceBroker = class _ResourceBroker {
1927
3632
  constructor(coordDb, fencing) {
@@ -1979,7 +3684,7 @@ var ResourceBroker = class _ResourceBroker {
1979
3684
  id, type, name, value, owner_agent_id, fencing_token, queue_json, acquired_at, expires_at
1980
3685
  ) VALUES (?, 'port', ?, ?, ?, ?, '[]', ?, ?)
1981
3686
  `).run(
1982
- `res_${crypto6.randomBytes(6).toString("hex")}`,
3687
+ `res_${crypto7.randomBytes(6).toString("hex")}`,
1983
3688
  resourceKey,
1984
3689
  String(candidatePort),
1985
3690
  params.agentId,
@@ -2046,7 +3751,7 @@ var ResourceBroker = class _ResourceBroker {
2046
3751
  this.coordDb.db.prepare(`INSERT OR REPLACE INTO resources
2047
3752
  (id, type, name, value, owner_agent_id, fencing_token, queue_json, acquired_at, expires_at)
2048
3753
  VALUES (?, 'mutex', ?, 'locked', ?, ?, '[]', ?, ?)
2049
- `).run(existing?.id ?? `res_${crypto6.randomBytes(6).toString("hex")}`, params.mutexName, params.agentId, token, now, now + leaseMs);
3754
+ `).run(existing?.id ?? `res_${crypto7.randomBytes(6).toString("hex")}`, params.mutexName, params.agentId, token, now, now + leaseMs);
2050
3755
  this.coordDb.db.prepare("DELETE FROM mutex_waiters WHERE mutex_name=? AND request_id=?").run(params.mutexName, requestId);
2051
3756
  this.coordDb.logEvent(params.agentId, "mutex_acquired", { mutexName: params.mutexName, fencingToken: token });
2052
3757
  return { acquired: true, fencingToken: token, holderAgentId: params.agentId, queuePosition: 0 };
@@ -2125,9 +3830,10 @@ var ResourceBroker = class _ResourceBroker {
2125
3830
  }
2126
3831
  if (params.maxOutputBytes !== void 0 && (!Number.isSafeInteger(params.maxOutputBytes) || params.maxOutputBytes <= 0)) throw new Error("maxOutputBytes must be a positive integer");
2127
3832
  const epoch = this.fencing.assertSession(params.agentId);
2128
- const requestId = crypto6.randomUUID();
3833
+ const requestId = crypto7.randomUUID();
2129
3834
  const started = Date.now();
2130
3835
  let run = null;
3836
+ let groupReaped = false;
2131
3837
  const abortError = () => new DOMException("Mutex command cancelled", "AbortError");
2132
3838
  this.activeExecutions++;
2133
3839
  try {
@@ -2162,7 +3868,7 @@ var ResourceBroker = class _ResourceBroker {
2162
3868
  const prepared = await lifecycle?.prepare();
2163
3869
  if (params.signal?.aborted) throw abortError();
2164
3870
  const candidates = ["./command-worker.js", "../command-worker.js", "../../dist/command-worker.js"].map((name) => fileURLToPath(new URL(name, import.meta.url)));
2165
- const script = candidates.find((name) => fs7.existsSync(name));
3871
+ const script = candidates.find((name) => fs8.existsSync(name));
2166
3872
  if (!script) throw new Error("Missing command worker. Build Kith before running supervised commands.");
2167
3873
  const worker = fork(script, [], { detached: true, stdio: ["ignore", "pipe", "pipe", "ipc"], execArgv: [] });
2168
3874
  const workerPid = worker.pid;
@@ -2171,7 +3877,7 @@ var ResourceBroker = class _ResourceBroker {
2171
3877
  });
2172
3878
  throw new Error("Could not start command supervisor");
2173
3879
  }
2174
- let workerIdentity = FencingAndAgentManager.getProcessStartTime(workerPid);
3880
+ let workerIdentity = null;
2175
3881
  let failure;
2176
3882
  let outcome;
2177
3883
  const stdout = [];
@@ -2199,11 +3905,19 @@ var ResourceBroker = class _ResourceBroker {
2199
3905
  };
2200
3906
  const onAbort = () => stop(abortError());
2201
3907
  params.signal?.addEventListener("abort", onAbort, { once: true });
3908
+ const renew = () => {
3909
+ this.fencing.heartbeat(params.agentId);
3910
+ this.renewMutex({ ...params, fencingToken: run.fencing_token });
3911
+ lifecycle?.renew();
3912
+ };
3913
+ try {
3914
+ renew();
3915
+ } catch (err) {
3916
+ stop(err instanceof Error ? err : new Error(String(err)));
3917
+ }
2202
3918
  const interval = setInterval(() => {
2203
3919
  try {
2204
- this.fencing.heartbeat(params.agentId);
2205
- this.renewMutex({ ...params, fencingToken: run.fencing_token });
2206
- lifecycle?.renew();
3920
+ renew();
2207
3921
  } catch (err) {
2208
3922
  stop(err instanceof Error ? err : new Error(String(err)));
2209
3923
  }
@@ -2217,26 +3931,43 @@ var ResourceBroker = class _ResourceBroker {
2217
3931
  };
2218
3932
  worker.stdout.on("data", capture(stdout, params.onStdout));
2219
3933
  worker.stderr.on("data", capture(stderr, params.onStderr));
3934
+ let launchStarted = false;
2220
3935
  worker.on("message", (message) => {
2221
3936
  if (disposed) return;
2222
3937
  if (message.ready) {
2223
- try {
2224
- if (params.signal?.aborted) throw abortError();
2225
- this.coordDb.withTransaction(() => {
2226
- this.fencing.assertSession(params.agentId);
2227
- const identity = FencingAndAgentManager.getProcessStartTime(workerPid);
3938
+ if (launchStarted || failure) return;
3939
+ launchStarted = true;
3940
+ void (async () => {
3941
+ try {
3942
+ if (params.signal?.aborted) throw abortError();
3943
+ try {
3944
+ renew();
3945
+ } catch (err) {
3946
+ throw err instanceof Error ? err : new Error(String(err));
3947
+ }
3948
+ const identity = await FencingAndAgentManager.waitForProcessStartTime(
3949
+ workerPid,
3950
+ 5e3,
3951
+ () => disposed || Boolean(failure) || Boolean(params.signal?.aborted)
3952
+ );
3953
+ if (disposed || failure) return;
3954
+ if (params.signal?.aborted) throw abortError();
2228
3955
  if (!identity) throw new Error("Cannot inspect command worker");
2229
- this.coordDb.db.prepare("UPDATE mutex_runs SET worker_pid=?, worker_start=? WHERE run_id=?").run(workerPid, identity, requestId);
2230
- run.worker_pid = workerPid;
2231
- run.worker_start = identity;
2232
- workerIdentity = identity;
2233
- this.renewMutex({ ...params, fencingToken: run.fencing_token });
2234
- lifecycle?.renew();
2235
- });
2236
- worker.send({ command: prepared?.command ?? params.command, env: prepared?.env, cwd: params.cwd ?? this.coordDb.repoRoot, mutexName: params.mutexName });
2237
- } catch (err) {
2238
- stop(err instanceof Error ? err : new Error(String(err)));
2239
- }
3956
+ this.coordDb.withTransaction(() => {
3957
+ this.fencing.assertSession(params.agentId);
3958
+ this.coordDb.db.prepare("UPDATE mutex_runs SET worker_pid=?, worker_start=? WHERE run_id=?").run(workerPid, identity, requestId);
3959
+ run.worker_pid = workerPid;
3960
+ run.worker_start = identity;
3961
+ workerIdentity = identity;
3962
+ this.renewMutex({ ...params, fencingToken: run.fencing_token });
3963
+ lifecycle?.renew();
3964
+ });
3965
+ if (params.signal?.aborted || failure) throw abortError();
3966
+ worker.send({ command: prepared?.command ?? params.command, env: prepared?.env, cwd: params.cwd ?? this.coordDb.repoRoot, mutexName: params.mutexName });
3967
+ } catch (err) {
3968
+ if (!disposed && !failure) stop(err instanceof Error ? err : new Error(String(err)));
3969
+ }
3970
+ })();
2240
3971
  } else {
2241
3972
  outcome = { exitCode: message.exitCode ?? 1, error: message.error };
2242
3973
  }
@@ -2262,12 +3993,22 @@ var ResourceBroker = class _ResourceBroker {
2262
3993
  const killError = signalGroup(workerPid, "SIGKILL", workerIdentity);
2263
3994
  failure ??= killError;
2264
3995
  const deadline = stopDeadline ?? Date.now() + 5e3;
2265
- while (groupIsAlive(workerPid, workerIdentity) && Date.now() < deadline) await delay(20);
3996
+ let lastZombieCheck = 0;
3997
+ while (groupIsAlive(workerPid, workerIdentity) && Date.now() < deadline) {
3998
+ if (process.platform === "darwin" && Date.now() - lastZombieCheck >= 200) {
3999
+ lastZombieCheck = Date.now();
4000
+ if (darwinGroupHasLiveMember(workerPid) === false) {
4001
+ groupReaped = true;
4002
+ break;
4003
+ }
4004
+ }
4005
+ await delay(20);
4006
+ }
2266
4007
  }
2267
4008
  disposed = true;
2268
4009
  if (killTimer) clearTimeout(killTimer);
2269
4010
  if (stopTimer) clearTimeout(stopTimer);
2270
- if (groupIsAlive(workerPid, workerIdentity)) {
4011
+ if (!groupReaped && groupIsAlive(workerPid, workerIdentity)) {
2271
4012
  worker.stdout?.destroy();
2272
4013
  worker.stderr?.destroy();
2273
4014
  if (worker.connected) worker.disconnect();
@@ -2279,7 +4020,7 @@ var ResourceBroker = class _ResourceBroker {
2279
4020
  try {
2280
4021
  this.coordDb.withTransaction(() => {
2281
4022
  this.coordDb.db.prepare("DELETE FROM mutex_waiters WHERE mutex_name=? AND request_id=? AND session_epoch=?").run(params.mutexName, requestId, epoch);
2282
- if (run && !this.runIsAlive(run)) this.clearRun(run);
4023
+ if (run && (groupReaped || !this.runIsAlive(run))) this.clearRun(run);
2283
4024
  if (run && run.worker_pid === null) this.clearRun(run);
2284
4025
  if (!this.getRun(params.mutexName)) lifecycle?.release();
2285
4026
  });
@@ -2334,6 +4075,29 @@ var ResourceBroker = class _ResourceBroker {
2334
4075
  };
2335
4076
  }
2336
4077
  };
4078
+ function darwinGroupHasLiveMember(pgid) {
4079
+ try {
4080
+ const out = execFileSync8("ps", ["-ax", "-o", "pid=,pgid=,stat="], {
4081
+ encoding: "utf8",
4082
+ timeout: 1e3,
4083
+ stdio: ["ignore", "pipe", "ignore"],
4084
+ env: { ...process.env, LC_ALL: "C" }
4085
+ });
4086
+ let sawMember = false;
4087
+ for (const line of out.split("\n")) {
4088
+ const parts = line.trim().split(/\s+/);
4089
+ if (parts.length < 3) continue;
4090
+ const pid = Number(parts[0]);
4091
+ const group = Number(parts[1]);
4092
+ if (pid !== pgid && group !== pgid) continue;
4093
+ sawMember = true;
4094
+ if (!parts.slice(2).join(" ").startsWith("Z")) return true;
4095
+ }
4096
+ return sawMember ? false : null;
4097
+ } catch {
4098
+ return null;
4099
+ }
4100
+ }
2337
4101
  function groupIsAlive(pgid, expectedStart) {
2338
4102
  if (expectedStart) {
2339
4103
  const currentStart = FencingAndAgentManager.getProcessStartTime(pgid);
@@ -2346,10 +4110,10 @@ function groupIsAlive(pgid, expectedStart) {
2346
4110
  }
2347
4111
  if (process.platform === "linux") {
2348
4112
  try {
2349
- for (const pid of fs7.readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
4113
+ for (const pid of fs8.readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
2350
4114
  let stat;
2351
4115
  try {
2352
- stat = fs7.readFileSync(`/proc/${pid}/stat`, "utf8");
4116
+ stat = fs8.readFileSync(`/proc/${pid}/stat`, "utf8");
2353
4117
  } catch (err) {
2354
4118
  if (err.code === "ENOENT" || err.code === "ESRCH") continue;
2355
4119
  return true;
@@ -2377,13 +4141,13 @@ function delay(ms) {
2377
4141
  }
2378
4142
 
2379
4143
  // src/core/db.ts
2380
- import { createRequire } from "module";
2381
- import fs8 from "fs";
2382
- import path7 from "path";
2383
- var require2 = createRequire(import.meta.url);
4144
+ import { createRequire as createRequire2 } from "module";
4145
+ import fs9 from "fs";
4146
+ import path8 from "path";
4147
+ var require3 = createRequire2(import.meta.url);
2384
4148
  var sqlite;
2385
4149
  function sqliteDatabase() {
2386
- return (sqlite ??= require2("node:sqlite")).DatabaseSync;
4150
+ return (sqlite ??= require3("node:sqlite")).DatabaseSync;
2387
4151
  }
2388
4152
  var CoordDatabase = class _CoordDatabase {
2389
4153
  db;
@@ -2398,26 +4162,26 @@ var CoordDatabase = class _CoordDatabase {
2398
4162
  this.repoRoot = layout.checkoutRoot;
2399
4163
  this.commonGitDir = layout.commonGitDir;
2400
4164
  this.isLinkedWorktree = layout.isLinkedWorktree;
2401
- for (let current = fs8.realpathSync.native(repoRoot); isWithin(this.repoRoot, current); current = path7.dirname(current)) {
2402
- const local = path7.join(current, ".coord");
2403
- if (local !== layout.coordDir && fs8.existsSync(path7.join(local, "state.db"))) {
4165
+ for (let current = fs9.realpathSync.native(repoRoot); isWithin(this.repoRoot, current); current = path8.dirname(current)) {
4166
+ const local = path8.join(current, ".coord");
4167
+ if (local !== layout.coordDir && fs9.existsSync(path8.join(local, "state.db"))) {
2404
4168
  throw new Error(`Legacy checkout-local coordination state found at ${local}. Stop clients and preserve that directory before consolidating shared state.`);
2405
4169
  }
2406
4170
  if (current === this.repoRoot) break;
2407
4171
  }
2408
4172
  this.coordDir = layout.coordDir;
2409
4173
  if (physicalPath(this.coordDir) !== this.coordDir) throw new Error("Coordination directory must not be a symlink");
2410
- this.dbPath = customDbPath ?? path7.join(this.coordDir, "state.db");
4174
+ this.dbPath = customDbPath ?? path8.join(this.coordDir, "state.db");
2411
4175
  if (!customDbPath && physicalPath(this.dbPath) !== this.dbPath) throw new Error("Coordination database must not be a symlink");
2412
- const recoveryFiles = !customDbPath && (fs8.existsSync(path7.join(this.coordDir, "merge-train.lock")) || fs8.existsSync(path7.join(this.coordDir, "setup.lock")) || ["shadow-index", "quarantine", "snapshots", "worktrees", "setup"].some((name) => {
2413
- const dir = path7.join(this.coordDir, name);
2414
- return fs8.existsSync(dir) && (!fs8.lstatSync(dir).isDirectory() || fs8.readdirSync(dir).length > 0);
4176
+ const recoveryFiles = !customDbPath && (fs9.existsSync(path8.join(this.coordDir, "merge-train.lock")) || fs9.existsSync(path8.join(this.coordDir, "setup.lock")) || ["shadow-index", "quarantine", "snapshots", "worktrees", "setup"].some((name) => {
4177
+ const dir = path8.join(this.coordDir, name);
4178
+ return fs9.existsSync(dir) && (!fs9.lstatSync(dir).isDirectory() || fs9.readdirSync(dir).length > 0);
2415
4179
  }));
2416
- const sidecars = ["-wal", "-shm", "-journal"].some((suffix) => fs8.existsSync(this.dbPath + suffix));
2417
- if (!fs8.existsSync(this.dbPath) && (recoveryFiles || sidecars)) {
4180
+ const sidecars = ["-wal", "-shm", "-journal"].some((suffix) => fs9.existsSync(this.dbPath + suffix));
4181
+ if (!fs9.existsSync(this.dbPath) && (recoveryFiles || sidecars)) {
2418
4182
  throw new Error("Missing coordination database with existing recovery state. Stop clients and preserve the database, sidecars and worktrees before repair.");
2419
4183
  }
2420
- if (fs8.existsSync(this.dbPath)) {
4184
+ if (fs9.existsSync(this.dbPath)) {
2421
4185
  const probe = new (sqliteDatabase())(this.dbPath, { readOnly: true });
2422
4186
  try {
2423
4187
  probe.exec("PRAGMA busy_timeout=10000; BEGIN");
@@ -2428,13 +4192,13 @@ var CoordDatabase = class _CoordDatabase {
2428
4192
  probe.close();
2429
4193
  }
2430
4194
  }
2431
- fs8.mkdirSync(this.coordDir, { recursive: true, mode: 448 });
4195
+ fs9.mkdirSync(this.coordDir, { recursive: true, mode: 448 });
2432
4196
  for (const name of ["shadow-index", "quarantine", "snapshots", "worktrees"]) {
2433
- const target = path7.join(this.coordDir, name);
4197
+ const target = path8.join(this.coordDir, name);
2434
4198
  if (!isWithin(this.coordDir, physicalPath(target)) || physicalPath(target) !== target) {
2435
4199
  throw new Error(`Coordination subdirectory must not be a symlink: ${name}`);
2436
4200
  }
2437
- fs8.mkdirSync(target, { recursive: true });
4201
+ fs9.mkdirSync(target, { recursive: true });
2438
4202
  }
2439
4203
  this.db = new (sqliteDatabase())(this.dbPath);
2440
4204
  try {
@@ -2714,6 +4478,20 @@ var CoordDatabase = class _CoordDatabase {
2714
4478
  CREATE INDEX IF NOT EXISTS idx_handoffs_task ON handoffs(task_id);
2715
4479
  CREATE INDEX IF NOT EXISTS idx_handoffs_created ON handoffs(created_at DESC);
2716
4480
  `);
4481
+ this.db.exec(`
4482
+ CREATE TABLE IF NOT EXISTS worktree_registrations (
4483
+ agent_id TEXT PRIMARY KEY,
4484
+ worktree_path TEXT NOT NULL,
4485
+ provenance TEXT NOT NULL,
4486
+ source TEXT NOT NULL,
4487
+ branch TEXT,
4488
+ head TEXT,
4489
+ detached INTEGER NOT NULL DEFAULT 0,
4490
+ dirty INTEGER NOT NULL DEFAULT 0,
4491
+ branch_elsewhere INTEGER NOT NULL DEFAULT 0,
4492
+ registered_at INTEGER NOT NULL
4493
+ );
4494
+ `);
2717
4495
  if (version < 2) {
2718
4496
  this.db.exec(`
2719
4497
  UPDATE tasks SET status='queued', owner_agent_id=NULL, fencing_token=NULL
@@ -2813,7 +4591,7 @@ var CoordDatabase = class _CoordDatabase {
2813
4591
  };
2814
4592
 
2815
4593
  // src/core/dep-graph.ts
2816
- import crypto7 from "crypto";
4594
+ import crypto8 from "crypto";
2817
4595
  var DependencyAndContractEngine = class _DependencyAndContractEngine {
2818
4596
  constructor(coordDb, lockEngine, fencing) {
2819
4597
  this.coordDb = coordDb;
@@ -2945,7 +4723,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
2945
4723
  };
2946
4724
  breakingChanges.push(alert);
2947
4725
  if (agentId && affectedLock) {
2948
- const conflictId = `conf_${crypto7.randomBytes(6).toString("hex")}`;
4726
+ const conflictId = `conf_${crypto8.randomBytes(6).toString("hex")}`;
2949
4727
  this.coordDb.db.prepare(`
2950
4728
  INSERT OR REPLACE INTO conflicts (
2951
4729
  id, agent_a, agent_b, file_path, severity, details_json, detected_at
@@ -2994,7 +4772,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
2994
4772
  publishExplicitContract(params) {
2995
4773
  const relPath = LockEngine.normalizeFile(this.coordDb.repoRoot, params.filePath);
2996
4774
  const now = Date.now();
2997
- const astHash = crypto7.createHash("sha256").update(params.signature).digest("hex").slice(0, 16);
4775
+ const astHash = crypto8.createHash("sha256").update(params.signature).digest("hex").slice(0, 16);
2998
4776
  return this.coordDb.withTransaction(() => {
2999
4777
  this.fencing.assertSession(params.agentId);
3000
4778
  const prevRow = this.coordDb.db.prepare(`SELECT * FROM contracts WHERE file_path = ? AND symbol_name = ?`).get(relPath, params.symbolName);
@@ -3025,7 +4803,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
3025
4803
  });
3026
4804
  }
3027
4805
  upsertContractInternal(params) {
3028
- const id = params.prev?.id ?? `ctr_${crypto7.randomBytes(6).toString("hex")}`;
4806
+ const id = params.prev?.id ?? `ctr_${crypto8.randomBytes(6).toString("hex")}`;
3029
4807
  const version = params.prev ? params.prev.ast_hash !== params.symbol.astHash ? params.prev.version + 1 : params.prev.version : 1;
3030
4808
  this.coordDb.db.prepare(`
3031
4809
  INSERT OR REPLACE INTO contracts (
@@ -3115,7 +4893,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
3115
4893
  };
3116
4894
 
3117
4895
  // src/core/intents.ts
3118
- import crypto8 from "crypto";
4896
+ import crypto9 from "crypto";
3119
4897
  var IntentAndTaskEngine = class {
3120
4898
  constructor(coordDb, fencing, lockEngine) {
3121
4899
  this.coordDb = coordDb;
@@ -3137,7 +4915,7 @@ var IntentAndTaskEngine = class {
3137
4915
  const activeTasks = this.listTasks({ status: "active" }).filter(
3138
4916
  (t) => t.owner_agent_id !== params.agentId
3139
4917
  );
3140
- const taskId = `task_${crypto8.randomBytes(6).toString("hex")}`;
4918
+ const taskId = `task_${crypto9.randomBytes(6).toString("hex")}`;
3141
4919
  const lockRes = this.lockEngine.acquireLocks({
3142
4920
  agentId: params.agentId,
3143
4921
  patterns: params.scopeGlobs,
@@ -3195,7 +4973,7 @@ var IntentAndTaskEngine = class {
3195
4973
  * Orchestrator Mode: Adds a task to the DAG queue with optional dependencies and priority.
3196
4974
  */
3197
4975
  addTask(params) {
3198
- const id = params.id ?? `task_${crypto8.randomBytes(6).toString("hex")}`;
4976
+ const id = params.id ?? `task_${crypto9.randomBytes(6).toString("hex")}`;
3199
4977
  const dependsOn = params.dependsOn ?? [];
3200
4978
  const scopeGlobs = (params.scopeGlobs ?? []).map(
3201
4979
  (g) => LockEngine.normalizePattern(this.coordDb.repoRoot, g)
@@ -3389,12 +5167,12 @@ var IntentAndTaskEngine = class {
3389
5167
  };
3390
5168
 
3391
5169
  // src/core/handoffs.ts
3392
- import { execFileSync as execFileSync5 } from "child_process";
3393
- import fs9 from "fs";
5170
+ import { execFileSync as execFileSync9 } from "child_process";
5171
+ import fs10 from "fs";
3394
5172
  var RELEVANT_WINDOW_MS = 14 * 24 * 3600 * 1e3;
3395
5173
  function gitChangedFiles(worktree, repoRoot) {
3396
- if (!worktree || !fs9.existsSync(worktree)) return [];
3397
- const run = (cwd, ...args) => execFileSync5("git", args, {
5174
+ if (!worktree || !fs10.existsSync(worktree)) return [];
5175
+ const run = (cwd, ...args) => execFileSync9("git", args, {
3398
5176
  cwd,
3399
5177
  encoding: "utf8",
3400
5178
  stdio: ["ignore", "pipe", "ignore"],
@@ -3621,24 +5399,476 @@ function buildBrief(input, options = {}) {
3621
5399
  const empty = !active.length && !blockers.length && !queued.count && !queued.stale && !handoffs.length && !conflicts.length;
3622
5400
  return { ...base, state: "ready", active, blockers, queued, handoffs, conflicts, empty };
3623
5401
  }
3624
-
3625
- // src/core/commit.ts
3626
- import { execFileSync as execFileSync8 } from "child_process";
3627
- import crypto10 from "crypto";
3628
- import fs12 from "fs";
3629
- import path10 from "path";
5402
+
5403
+ // src/core/commit.ts
5404
+ import { execFileSync as execFileSync13 } from "child_process";
5405
+ import crypto11 from "crypto";
5406
+ import fs14 from "fs";
5407
+ import path12 from "path";
5408
+
5409
+ // src/cli/auto-session.ts
5410
+ import crypto10 from "crypto";
5411
+ import { execFileSync as execFileSync11 } from "child_process";
5412
+ import fs12 from "fs";
5413
+ import { createRequire as createRequire3 } from "module";
5414
+ import os from "os";
5415
+ import path10 from "path";
5416
+
5417
+ // src/core/worktree-adopt.ts
5418
+ import { execFileSync as execFileSync10 } from "child_process";
5419
+ import fs11 from "fs";
5420
+ import path9 from "path";
5421
+ var REGISTRATION_SQL = `SELECT agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at
5422
+ FROM worktree_registrations`;
5423
+ function detachedIntegrationError() {
5424
+ return "Adopted worktree HEAD is detached. Check out a branch before integrating. The worktree was left unchanged.";
5425
+ }
5426
+ function branchElsewhereError(branch) {
5427
+ return `Branch '${branch}' is checked out in another worktree. Integration and kith commit are refused until this worktree is the only checkout of that branch. The worktree was left unchanged.`;
5428
+ }
5429
+ function parseWorktreePorcelain(output) {
5430
+ const entries = [];
5431
+ let current = null;
5432
+ const push = () => {
5433
+ if (current) entries.push(current);
5434
+ };
5435
+ for (const line of output.split(/\r?\n/)) {
5436
+ if (!line) continue;
5437
+ if (line.startsWith("worktree ")) {
5438
+ push();
5439
+ current = { path: line.slice("worktree ".length).trim(), head: "", branch: null, detached: false, locked: false, lockReason: null };
5440
+ } else if (!current) {
5441
+ continue;
5442
+ } else if (line.startsWith("HEAD ")) {
5443
+ current.head = line.slice("HEAD ".length).trim();
5444
+ } else if (line.startsWith("branch ")) {
5445
+ current.branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim() || null;
5446
+ } else if (line === "detached") {
5447
+ current.detached = true;
5448
+ current.branch = null;
5449
+ } else if (line === "locked" || line.startsWith("locked ")) {
5450
+ current.locked = true;
5451
+ const reason = line.slice("locked".length).trim();
5452
+ current.lockReason = reason || null;
5453
+ }
5454
+ }
5455
+ push();
5456
+ return entries;
5457
+ }
5458
+ function listGitWorktrees(repoRoot) {
5459
+ try {
5460
+ const out = execFileSync10("git", ["worktree", "list", "--porcelain"], {
5461
+ cwd: repoRoot,
5462
+ encoding: "utf8",
5463
+ timeout: 5e3,
5464
+ stdio: ["ignore", "pipe", "pipe"]
5465
+ });
5466
+ return parseWorktreePorcelain(out);
5467
+ } catch {
5468
+ return [];
5469
+ }
5470
+ }
5471
+ function branchIsCheckedOutElsewhere(entries, worktreePath, branch) {
5472
+ if (!branch) return false;
5473
+ let here;
5474
+ try {
5475
+ here = physicalPath(worktreePath);
5476
+ } catch {
5477
+ here = path9.resolve(worktreePath);
5478
+ }
5479
+ return entries.some((entry) => {
5480
+ if (entry.branch !== branch) return false;
5481
+ try {
5482
+ return physicalPath(entry.path) !== here;
5483
+ } catch {
5484
+ return path9.resolve(entry.path) !== here;
5485
+ }
5486
+ });
5487
+ }
5488
+ function kithWorktreesRoot(coord) {
5489
+ return physicalPath(path9.join(coord.coordDir, "worktrees"));
5490
+ }
5491
+ function isKithOwnedWorktree(coord, worktreePath) {
5492
+ try {
5493
+ const root = kithWorktreesRoot(coord);
5494
+ const target = physicalPath(worktreePath);
5495
+ return target !== root && isWithin(root, target);
5496
+ } catch {
5497
+ return false;
5498
+ }
5499
+ }
5500
+ function primaryCheckoutOf(start) {
5501
+ const layout = discoverRepository(start);
5502
+ if (!layout.commonGitDir || !layout.isLinkedWorktree) return layout.checkoutRoot;
5503
+ for (const entry of listGitWorktrees(layout.checkoutRoot)) {
5504
+ try {
5505
+ const item = discoverRepository(entry.path);
5506
+ if (!item.isLinkedWorktree && item.commonGitDir === layout.commonGitDir) return item.checkoutRoot;
5507
+ } catch {
5508
+ }
5509
+ }
5510
+ return layout.checkoutRoot;
5511
+ }
5512
+ function registrationFromRow(row) {
5513
+ const source = row.source === "kith" || row.source === "claude-code" ? row.source : "external";
5514
+ return {
5515
+ agentId: row.agent_id,
5516
+ worktreePath: row.worktree_path,
5517
+ provenance: row.provenance === "created" ? "created" : "adopted",
5518
+ source,
5519
+ branch: row.branch,
5520
+ head: row.head,
5521
+ detached: Boolean(row.detached),
5522
+ dirty: Boolean(row.dirty),
5523
+ branchCheckedOutElsewhere: Boolean(row.branch_elsewhere),
5524
+ registeredAt: Number(row.registered_at)
5525
+ };
5526
+ }
5527
+ function registrationsTable(coord) {
5528
+ return Boolean(coord.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='worktree_registrations'").get());
5529
+ }
5530
+ function readRegistration(coord, agentId) {
5531
+ if (!registrationsTable(coord)) return null;
5532
+ const row = coord.db.prepare(`${REGISTRATION_SQL} WHERE agent_id = ?`).get(agentId);
5533
+ return row ? registrationFromRow(row) : null;
5534
+ }
5535
+ function listRegistrations(coord) {
5536
+ if (!registrationsTable(coord)) return [];
5537
+ return coord.db.prepare(`${REGISTRATION_SQL} ORDER BY registered_at`).all().map(registrationFromRow);
5538
+ }
5539
+ function clearRegistration(coord, agentId) {
5540
+ if (!registrationsTable(coord)) return;
5541
+ coord.db.prepare("DELETE FROM worktree_registrations WHERE agent_id = ?").run(agentId);
5542
+ }
5543
+ function worktreeDirty(cwd) {
5544
+ try {
5545
+ const out = execFileSync10("git", ["status", "--porcelain", "--untracked-files=normal"], {
5546
+ cwd,
5547
+ encoding: "utf8",
5548
+ timeout: 5e3,
5549
+ stdio: ["ignore", "pipe", "pipe"]
5550
+ });
5551
+ return out.trim().length > 0;
5552
+ } catch {
5553
+ throw new Error(`Cannot inspect worktree status at ${cwd}.`);
5554
+ }
5555
+ }
5556
+ function claudeMarker(worktreePath) {
5557
+ let admin = null;
5558
+ try {
5559
+ const text = fs11.readFileSync(path9.join(worktreePath, ".git"), "utf8");
5560
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(text);
5561
+ if (match?.[1]) admin = path9.resolve(worktreePath, match[1].trim());
5562
+ } catch {
5563
+ return { marker: false, lockReason: null };
5564
+ }
5565
+ if (!admin) return { marker: false, lockReason: null };
5566
+ let lockReason = null;
5567
+ try {
5568
+ lockReason = fs11.readFileSync(path9.join(admin, "locked"), "utf8").trim() || null;
5569
+ } catch {
5570
+ }
5571
+ const names = ["claude", "claude.json", "claude-worktree"];
5572
+ const marker = names.some((name) => {
5573
+ try {
5574
+ return fs11.existsSync(path9.join(admin, name));
5575
+ } catch {
5576
+ return false;
5577
+ }
5578
+ }) || Boolean(lockReason && /claude/i.test(lockReason));
5579
+ return { marker, lockReason };
5580
+ }
5581
+ function pathHasClaudeWorktrees(worktreePath) {
5582
+ const parts = worktreePath.split(path9.sep);
5583
+ for (let i = 0; i < parts.length - 1; i++) {
5584
+ if (parts[i] === ".claude" && parts[i + 1] === "worktrees" && parts.length >= i + 3) return true;
5585
+ }
5586
+ return false;
5587
+ }
5588
+ function classifySource(coord, worktreePath, lockReason) {
5589
+ if (isKithOwnedWorktree(coord, worktreePath)) return "kith";
5590
+ const marker = claudeMarker(worktreePath);
5591
+ if (pathHasClaudeWorktrees(worktreePath) || marker.marker || lockReason && /claude/i.test(lockReason)) return "claude-code";
5592
+ return "external";
5593
+ }
5594
+ function inspectLinkedWorktree(coord, requested) {
5595
+ if (!fs11.existsSync(requested)) throw new Error(`Not a linked worktree of this repository: ${requested}`);
5596
+ const dir = fs11.statSync(requested).isDirectory() ? requested : path9.dirname(requested);
5597
+ let layout;
5598
+ try {
5599
+ layout = discoverRepository(dir);
5600
+ } catch {
5601
+ throw new Error(`Not a linked worktree of this repository: ${requested}`);
5602
+ }
5603
+ if (!layout.commonGitDir || layout.commonGitDir !== coord.commonGitDir) {
5604
+ throw new Error(`Not a linked worktree of this repository: ${requested}`);
5605
+ }
5606
+ if (!layout.isLinkedWorktree) {
5607
+ throw new Error("Cannot adopt the primary checkout. Pass a linked worktree from git worktree list.");
5608
+ }
5609
+ const entries = listGitWorktrees(coord.repoRoot);
5610
+ const checkoutRoot = physicalPath(layout.checkoutRoot);
5611
+ const match = entries.find((entry) => {
5612
+ try {
5613
+ return physicalPath(entry.path) === checkoutRoot;
5614
+ } catch {
5615
+ return false;
5616
+ }
5617
+ });
5618
+ if (!match) throw new Error(`Not a linked worktree of this repository: ${checkoutRoot}`);
5619
+ const detached = match.detached || !match.branch;
5620
+ const branch = detached ? null : match.branch;
5621
+ return {
5622
+ checkoutRoot,
5623
+ branch,
5624
+ head: match.head,
5625
+ detached,
5626
+ dirty: worktreeDirty(checkoutRoot),
5627
+ branchCheckedOutElsewhere: branchIsCheckedOutElsewhere(entries, checkoutRoot, branch),
5628
+ source: classifySource(coord, checkoutRoot, match.lockReason),
5629
+ provenance: isKithOwnedWorktree(coord, checkoutRoot) ? "created" : "adopted",
5630
+ locked: match.locked,
5631
+ lockReason: match.lockReason
5632
+ };
5633
+ }
5634
+ function adoptionNotes(inspected) {
5635
+ if (inspected.provenance !== "adopted") return [];
5636
+ const notes = [
5637
+ "Kith did not create this worktree and will not delete it. Unregister with `kith worktree forget`, or remove it explicitly with `kith worktree remove --delete-adopted`."
5638
+ ];
5639
+ if (inspected.dirty) notes.unshift("Adopted worktree has uncommitted changes. They were left as they are.");
5640
+ if (inspected.detached) notes.unshift(detachedIntegrationError());
5641
+ else if (inspected.branchCheckedOutElsewhere && inspected.branch) notes.unshift(branchElsewhereError(inspected.branch));
5642
+ return notes;
5643
+ }
5644
+ function bindingFrom(agentId, inspected, started, alreadyRegistered) {
5645
+ return {
5646
+ agentId,
5647
+ worktreePath: inspected.checkoutRoot,
5648
+ branch: inspected.branch,
5649
+ hydrationMethod: "none",
5650
+ hydratedDirs: [],
5651
+ durationMs: Date.now() - started,
5652
+ provenance: inspected.provenance,
5653
+ source: inspected.source,
5654
+ detached: inspected.detached,
5655
+ dirty: inspected.dirty,
5656
+ branchCheckedOutElsewhere: inspected.branchCheckedOutElsewhere,
5657
+ alreadyRegistered,
5658
+ notes: adoptionNotes(inspected)
5659
+ };
5660
+ }
5661
+ function writeRegistration(coord, fencing, agentId, inspected, already, log = true) {
5662
+ coord.withTransaction(() => {
5663
+ fencing.assertSession(agentId);
5664
+ coord.db.prepare(`
5665
+ INSERT INTO worktree_registrations (
5666
+ agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at
5667
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5668
+ ON CONFLICT(agent_id) DO UPDATE SET
5669
+ worktree_path = excluded.worktree_path, provenance = excluded.provenance, source = excluded.source,
5670
+ branch = excluded.branch, head = excluded.head, detached = excluded.detached,
5671
+ branch_elsewhere = excluded.branch_elsewhere,
5672
+ dirty = CASE WHEN worktree_registrations.worktree_path = excluded.worktree_path THEN worktree_registrations.dirty ELSE excluded.dirty END,
5673
+ registered_at = CASE WHEN worktree_registrations.worktree_path = excluded.worktree_path THEN worktree_registrations.registered_at ELSE excluded.registered_at END
5674
+ `).run(
5675
+ agentId,
5676
+ inspected.checkoutRoot,
5677
+ inspected.provenance,
5678
+ inspected.source,
5679
+ inspected.branch,
5680
+ inspected.head,
5681
+ inspected.detached ? 1 : 0,
5682
+ inspected.dirty ? 1 : 0,
5683
+ inspected.branchCheckedOutElsewhere ? 1 : 0,
5684
+ Date.now()
5685
+ );
5686
+ coord.db.prepare("UPDATE agents SET worktree_path = ?, branch = ? WHERE id = ?").run(inspected.checkoutRoot, inspected.branch, agentId);
5687
+ const changed = !already || physicalPath(already.worktreePath) !== inspected.checkoutRoot || already.branch !== inspected.branch || already.detached !== inspected.detached || already.branchCheckedOutElsewhere !== inspected.branchCheckedOutElsewhere || already.source !== inspected.source;
5688
+ if (log && changed) {
5689
+ coord.logEvent(agentId, inspected.provenance === "created" ? "worktree_spawned" : "worktree_adopted", {
5690
+ worktreePath: inspected.checkoutRoot,
5691
+ branch: inspected.branch,
5692
+ source: inspected.source,
5693
+ provenance: inspected.provenance,
5694
+ detached: inspected.detached,
5695
+ dirty: inspected.dirty,
5696
+ branchCheckedOutElsewhere: inspected.branchCheckedOutElsewhere
5697
+ });
5698
+ }
5699
+ });
5700
+ }
5701
+ function adoptWorktree(coord, fencing, params) {
5702
+ fencing.assertSession(params.agentId);
5703
+ const started = Date.now();
5704
+ const requested = params.path ? path9.resolve(params.path) : process.cwd();
5705
+ const inspected = inspectLinkedWorktree(coord, requested);
5706
+ const agent = fencing.getAgent(params.agentId);
5707
+ if (agent?.worktree_path && physicalPath(agent.worktree_path) !== inspected.checkoutRoot) {
5708
+ throw new Error(`This session already has a different worktree at ${agent.worktree_path}. Forget it with \`kith worktree forget\` before adopting another.`);
5709
+ }
5710
+ const peer = fencing.listAgents(true).find((other) => other.id !== params.agentId && other.worktree_path && physicalPath(other.worktree_path) === inspected.checkoutRoot);
5711
+ if (peer) throw new Error(`Worktree is already registered to active agent '${peer.id}'.`);
5712
+ const already = readRegistration(coord, params.agentId);
5713
+ const same = Boolean(already && physicalPath(already.worktreePath) === inspected.checkoutRoot && already.branch === inspected.branch && already.detached === inspected.detached && already.branchCheckedOutElsewhere === inspected.branchCheckedOutElsewhere && already.source === inspected.source && already.provenance === inspected.provenance);
5714
+ if (!same) writeRegistration(coord, fencing, params.agentId, inspected, already);
5715
+ return bindingFrom(params.agentId, inspected, started, Boolean(already && physicalPath(already.worktreePath) === inspected.checkoutRoot));
5716
+ }
5717
+ function recordCreatedWorktree(coord, fencing, params) {
5718
+ const inspected = {
5719
+ checkoutRoot: physicalPath(params.worktreePath),
5720
+ branch: params.branch,
5721
+ head: params.head ?? "",
5722
+ detached: false,
5723
+ dirty: false,
5724
+ branchCheckedOutElsewhere: false,
5725
+ source: "kith",
5726
+ provenance: "created",
5727
+ locked: false,
5728
+ lockReason: null
5729
+ };
5730
+ writeRegistration(coord, fencing, params.agentId, inspected, readRegistration(coord, params.agentId), false);
5731
+ }
5732
+ function syncRegistration(coord, fencing, agentId) {
5733
+ const agent = fencing.getAgent(agentId);
5734
+ if (!agent?.worktree_path) return null;
5735
+ const existing = readRegistration(coord, agentId);
5736
+ if (existing) {
5737
+ try {
5738
+ if (physicalPath(existing.worktreePath) === physicalPath(agent.worktree_path)) return existing;
5739
+ } catch {
5740
+ return existing;
5741
+ }
5742
+ }
5743
+ try {
5744
+ adoptWorktree(coord, fencing, { agentId, path: agent.worktree_path, explicit: false });
5745
+ } catch {
5746
+ return readRegistration(coord, agentId);
5747
+ }
5748
+ return readRegistration(coord, agentId);
5749
+ }
5750
+ function adoptIfUnambiguous(coord, fencing, params) {
5751
+ const agent = fencing.getAgent(params.agentId);
5752
+ if (!agent || agent.status !== "active") return null;
5753
+ let layout;
5754
+ try {
5755
+ layout = discoverRepository(params.cwd);
5756
+ } catch {
5757
+ return null;
5758
+ }
5759
+ if (!layout.isLinkedWorktree || !layout.commonGitDir || layout.commonGitDir !== coord.commonGitDir) return null;
5760
+ if (agent.worktree_path) {
5761
+ try {
5762
+ if (physicalPath(agent.worktree_path) !== physicalPath(layout.checkoutRoot)) return null;
5763
+ } catch {
5764
+ return null;
5765
+ }
5766
+ }
5767
+ const peer = fencing.listAgents(true).some((other) => other.id !== params.agentId && other.worktree_path && (() => {
5768
+ try {
5769
+ return physicalPath(other.worktree_path) === physicalPath(layout.checkoutRoot);
5770
+ } catch {
5771
+ return false;
5772
+ }
5773
+ })());
5774
+ if (peer) return null;
5775
+ try {
5776
+ return adoptWorktree(coord, fencing, { agentId: params.agentId, path: layout.checkoutRoot, explicit: false });
5777
+ } catch {
5778
+ return null;
5779
+ }
5780
+ }
5781
+ function liveAdoption(coord, fencing, agent) {
5782
+ if (!agent?.worktree_path) return null;
5783
+ const registration = readRegistration(coord, agent.id);
5784
+ const adopted = registration?.provenance === "adopted" || !registration && !isKithOwnedWorktree(coord, agent.worktree_path);
5785
+ if (!adopted) return null;
5786
+ let inspected;
5787
+ try {
5788
+ inspected = inspectLinkedWorktree(coord, agent.worktree_path);
5789
+ } catch {
5790
+ return {
5791
+ worktreePath: agent.worktree_path,
5792
+ branch: agent.branch,
5793
+ detached: registration?.detached ?? !agent.branch,
5794
+ dirty: registration?.dirty ?? false,
5795
+ branchCheckedOutElsewhere: registration?.branchCheckedOutElsewhere ?? false,
5796
+ source: registration?.source ?? "external",
5797
+ provenance: "adopted",
5798
+ integrationError: registration?.detached || !agent.branch ? detachedIntegrationError() : registration?.branchCheckedOutElsewhere && agent.branch ? branchElsewhereError(agent.branch) : null,
5799
+ commitError: registration?.branchCheckedOutElsewhere && agent.branch ? branchElsewhereError(agent.branch) : null
5800
+ };
5801
+ }
5802
+ if (registration?.branch !== inspected.branch || registration?.detached !== inspected.detached || registration?.branchCheckedOutElsewhere !== inspected.branchCheckedOutElsewhere) {
5803
+ try {
5804
+ writeRegistration(coord, fencing, agent.id, inspected, registration);
5805
+ } catch {
5806
+ }
5807
+ }
5808
+ const integrationError = inspected.detached ? detachedIntegrationError() : inspected.branchCheckedOutElsewhere && inspected.branch ? branchElsewhereError(inspected.branch) : null;
5809
+ return {
5810
+ worktreePath: inspected.checkoutRoot,
5811
+ branch: inspected.branch,
5812
+ detached: inspected.detached,
5813
+ dirty: inspected.dirty,
5814
+ branchCheckedOutElsewhere: inspected.branchCheckedOutElsewhere,
5815
+ source: inspected.source,
5816
+ provenance: "adopted",
5817
+ integrationError,
5818
+ commitError: inspected.branchCheckedOutElsewhere && inspected.branch ? branchElsewhereError(inspected.branch) : null
5819
+ };
5820
+ }
5821
+ function transferWorktreeRegistration(coord, fromId, toId) {
5822
+ if (fromId === toId) return false;
5823
+ const from = coord.db.prepare("SELECT worktree_path, branch FROM agents WHERE id = ?").get(fromId);
5824
+ const to = coord.db.prepare("SELECT worktree_path FROM agents WHERE id = ?").get(toId);
5825
+ if (!from?.worktree_path || !to || to.worktree_path) return false;
5826
+ coord.db.prepare("UPDATE agents SET worktree_path = ?, branch = ? WHERE id = ?").run(from.worktree_path, from.branch, toId);
5827
+ coord.db.prepare("UPDATE agents SET worktree_path = NULL, branch = NULL WHERE id = ?").run(fromId);
5828
+ if (!registrationsTable(coord)) return true;
5829
+ const row = coord.db.prepare(`${REGISTRATION_SQL} WHERE agent_id = ?`).get(fromId);
5830
+ if (!row) return true;
5831
+ coord.db.prepare("DELETE FROM worktree_registrations WHERE agent_id = ?").run(fromId);
5832
+ coord.db.prepare(`
5833
+ INSERT INTO worktree_registrations (
5834
+ agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at
5835
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5836
+ ON CONFLICT(agent_id) DO UPDATE SET
5837
+ worktree_path = excluded.worktree_path, provenance = excluded.provenance, source = excluded.source,
5838
+ branch = excluded.branch, head = excluded.head, detached = excluded.detached, dirty = excluded.dirty,
5839
+ branch_elsewhere = excluded.branch_elsewhere, registered_at = excluded.registered_at
5840
+ `).run(
5841
+ toId,
5842
+ row.worktree_path,
5843
+ row.provenance,
5844
+ row.source,
5845
+ row.branch,
5846
+ row.head,
5847
+ Number(row.detached),
5848
+ Number(row.dirty),
5849
+ Number(row.branch_elsewhere),
5850
+ row.registered_at
5851
+ );
5852
+ return true;
5853
+ }
5854
+ function forgetWorktree(coord, fencing, agentId) {
5855
+ fencing.assertSession(agentId);
5856
+ const agent = fencing.getAgent(agentId);
5857
+ const had = Boolean(agent?.worktree_path || readRegistration(coord, agentId));
5858
+ coord.withTransaction(() => {
5859
+ fencing.assertSession(agentId);
5860
+ clearRegistration(coord, agentId);
5861
+ coord.db.prepare("UPDATE agents SET worktree_path = NULL, branch = NULL WHERE id = ?").run(agentId);
5862
+ coord.logEvent(agentId, "worktree_forgotten", { worktreePath: agent?.worktree_path ?? null });
5863
+ });
5864
+ return had;
5865
+ }
3630
5866
 
3631
5867
  // src/cli/auto-session.ts
3632
- import crypto9 from "crypto";
3633
- import { execFileSync as execFileSync6 } from "child_process";
3634
- import fs10 from "fs";
3635
- import { createRequire as createRequire2 } from "module";
3636
- import os from "os";
3637
- import path8 from "path";
3638
5868
  var PRESENCE_TTL_MS = 12 * 60 * 60 * 1e3;
3639
- var require3 = createRequire2(import.meta.url);
5869
+ var require4 = createRequire3(import.meta.url);
3640
5870
  function openSqlite(filePath) {
3641
- const { DatabaseSync } = require3("node:sqlite");
5871
+ const { DatabaseSync } = require4("node:sqlite");
3642
5872
  const db = new DatabaseSync(filePath);
3643
5873
  db.exec("PRAGMA busy_timeout = 3000; PRAGMA journal_mode = WAL;");
3644
5874
  const existingCols = db.prepare("PRAGMA table_info(presence)").all();
@@ -3701,17 +5931,17 @@ function resolveHomeDir(explicitHome) {
3701
5931
  return physicalPath(raw);
3702
5932
  }
3703
5933
  function presenceDbPath(home) {
3704
- return path8.join(resolveHomeDir(home), ".local/share/kith/presence.db");
5934
+ return path10.join(resolveHomeDir(home), ".local/share/kith/presence.db");
3705
5935
  }
3706
5936
  function withPresenceDb(home, create, fn) {
3707
5937
  const file = presenceDbPath(home);
3708
- if (!create && !fs10.existsSync(file)) return null;
3709
- const dir = path8.dirname(file);
5938
+ if (!create && !fs12.existsSync(file)) return null;
5939
+ const dir = path10.dirname(file);
3710
5940
  if (create) {
3711
- fs10.mkdirSync(dir, { recursive: true, mode: 448 });
5941
+ fs12.mkdirSync(dir, { recursive: true, mode: 448 });
3712
5942
  }
3713
5943
  if (physicalPath(dir) !== dir) return null;
3714
- if (fs10.existsSync(file) && physicalPath(file) !== file) return null;
5944
+ if (fs12.existsSync(file) && physicalPath(file) !== file) return null;
3715
5945
  const db = openSqlite(file);
3716
5946
  try {
3717
5947
  return fn(db);
@@ -3798,7 +6028,7 @@ function listRepoPresence(home, repoCommonDir) {
3798
6028
  }
3799
6029
  function deterministicAgentId(client, sessionKey) {
3800
6030
  const cleanClient = client.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase() || "agent";
3801
- const hash = crypto9.createHash("sha1").update(sessionKey).digest("hex").slice(0, 8);
6031
+ const hash = crypto10.createHash("sha1").update(sessionKey).digest("hex").slice(0, 8);
3802
6032
  return `auto-${cleanClient}-${hash}`;
3803
6033
  }
3804
6034
  function ancestorChain(pid) {
@@ -3807,7 +6037,7 @@ function ancestorChain(pid) {
3807
6037
  let current = pid;
3808
6038
  for (let hop = 0; hop < 16; hop++) {
3809
6039
  try {
3810
- const line = execFileSync6("ps", ["-o", "ppid=", "-p", String(current)], {
6040
+ const line = execFileSync11("ps", ["-o", "ppid=", "-p", String(current)], {
3811
6041
  encoding: "utf8",
3812
6042
  stdio: ["ignore", "pipe", "ignore"],
3813
6043
  timeout: 500
@@ -3829,12 +6059,12 @@ function ownedByCaller(agentPid, callerPid) {
3829
6059
  }
3830
6060
 
3831
6061
  // src/core/gc.ts
3832
- import fs11 from "fs";
3833
- import path9 from "path";
3834
- import { execFileSync as execFileSync7 } from "child_process";
6062
+ import fs13 from "fs";
6063
+ import path11 from "path";
6064
+ import { execFileSync as execFileSync12 } from "child_process";
3835
6065
  function gitStatusDirty(dir) {
3836
6066
  try {
3837
- const out = execFileSync7("git", ["status", "--porcelain"], {
6067
+ const out = execFileSync12("git", ["status", "--porcelain"], {
3838
6068
  cwd: dir,
3839
6069
  encoding: "utf8",
3840
6070
  stdio: ["ignore", "pipe", "pipe"]
@@ -3847,7 +6077,7 @@ function gitStatusDirty(dir) {
3847
6077
  function gitIsMerged(repoRoot, commit) {
3848
6078
  if (!commit) return false;
3849
6079
  try {
3850
- execFileSync7("git", ["merge-base", "--is-ancestor", commit, "HEAD"], {
6080
+ execFileSync12("git", ["merge-base", "--is-ancestor", commit, "HEAD"], {
3851
6081
  cwd: repoRoot,
3852
6082
  stdio: ["ignore", "ignore", "ignore"]
3853
6083
  });
@@ -3856,10 +6086,37 @@ function gitIsMerged(repoRoot, commit) {
3856
6086
  return false;
3857
6087
  }
3858
6088
  }
6089
+ function removeCreatedWorktree(repoRoot, wtPath, force) {
6090
+ let admin = null;
6091
+ try {
6092
+ const text = fs13.readFileSync(path11.join(wtPath, ".git"), "utf8");
6093
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(text);
6094
+ if (match?.[1]) admin = path11.resolve(wtPath, match[1].trim());
6095
+ } catch {
6096
+ }
6097
+ try {
6098
+ execFileSync12("git", ["worktree", "remove", ...force ? ["--force"] : [], wtPath], {
6099
+ cwd: repoRoot,
6100
+ stdio: ["ignore", "pipe", "pipe"]
6101
+ });
6102
+ return;
6103
+ } catch {
6104
+ }
6105
+ fs13.rmSync(wtPath, { recursive: true, force: true });
6106
+ if (!admin) return;
6107
+ try {
6108
+ const layout = discoverRepository(repoRoot);
6109
+ if (!layout.commonGitDir) return;
6110
+ const adminPath = physicalPath(admin);
6111
+ const worktreesAdmin = physicalPath(path11.join(layout.commonGitDir, "worktrees"));
6112
+ if (isWithin(worktreesAdmin, adminPath) && adminPath !== worktreesAdmin) fs13.rmSync(adminPath, { recursive: true, force: true });
6113
+ } catch {
6114
+ }
6115
+ }
3859
6116
  function gitHasCommitSince(repoRoot, sinceMs, files) {
3860
6117
  if (!files.length) return false;
3861
6118
  try {
3862
- const out = execFileSync7(
6119
+ const out = execFileSync12(
3863
6120
  "git",
3864
6121
  ["log", "-1", "--format=%H", `--since=@${Math.floor(sinceMs / 1e3)}`, "--", ...files],
3865
6122
  { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
@@ -3872,7 +6129,7 @@ function gitHasCommitSince(repoRoot, sinceMs, files) {
3872
6129
  function resyncStaleIndexEntries(repoRoot) {
3873
6130
  let cachedPaths = [];
3874
6131
  try {
3875
- const out = execFileSync7("git", ["diff", "--cached", "--name-only", "-z", "HEAD"], {
6132
+ const out = execFileSync12("git", ["diff", "--cached", "--name-only", "-z", "HEAD"], {
3876
6133
  cwd: repoRoot,
3877
6134
  encoding: "utf8",
3878
6135
  stdio: ["ignore", "pipe", "ignore"]
@@ -3883,7 +6140,7 @@ function resyncStaleIndexEntries(repoRoot) {
3883
6140
  }
3884
6141
  if (cachedPaths.length === 0) return 0;
3885
6142
  try {
3886
- execFileSync7("git", ["reset", "-q", "HEAD"], {
6143
+ execFileSync12("git", ["reset", "-q", "HEAD"], {
3887
6144
  cwd: repoRoot,
3888
6145
  stdio: ["ignore", "ignore", "ignore"]
3889
6146
  });
@@ -3897,7 +6154,7 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3897
6154
  const force = Boolean(options.force);
3898
6155
  const staleDays = Number.isFinite(options.staleDays) ? Math.max(0, options.staleDays) : 14;
3899
6156
  const layout = discoverRepository(directory);
3900
- const dbPath = path9.join(layout.coordDir, "state.db");
6157
+ const dbPath = path11.join(layout.coordDir, "state.db");
3901
6158
  const report = {
3902
6159
  ok: true,
3903
6160
  dryRun,
@@ -3915,7 +6172,7 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3915
6172
  prunedDeadAgents: 0,
3916
6173
  prunedArtifacts: 0
3917
6174
  };
3918
- if (!fs11.existsSync(dbPath)) {
6175
+ if (!fs13.existsSync(dbPath)) {
3919
6176
  report.nothingToClean = true;
3920
6177
  return report;
3921
6178
  }
@@ -3959,18 +6216,25 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3959
6216
  const pinnedTaskIds = new Set(
3960
6217
  openHandoffs.map((h) => h.task_id).filter((id) => Boolean(id))
3961
6218
  );
3962
- const worktreesDir = physicalPath(path9.join(layout.coordDir, "worktrees"));
3963
- if (fs11.existsSync(worktreesDir)) {
3964
- if (!dryRun) {
6219
+ const worktreesDir = physicalPath(path11.join(layout.coordDir, "worktrees"));
6220
+ const adoptedPaths = new Set(
6221
+ engine.worktrees.listRegistrations().filter((row) => row.provenance === "adopted").map((row) => {
3965
6222
  try {
3966
- execFileSync7("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
6223
+ return physicalPath(row.worktreePath);
3967
6224
  } catch {
6225
+ return row.worktreePath;
3968
6226
  }
3969
- }
6227
+ })
6228
+ );
6229
+ if (fs13.existsSync(worktreesDir)) {
3970
6230
  const listed = engine.worktrees.listWorktrees();
3971
6231
  for (const wt of listed) {
3972
6232
  const wtPath = physicalPath(wt.path);
3973
6233
  if (!isWithin(worktreesDir, wtPath) || wtPath === worktreesDir) continue;
6234
+ if (adoptedPaths.has(wtPath)) {
6235
+ report.preservedWorktrees.push({ path: wtPath, branch: wt.branch, reason: "adopted" });
6236
+ continue;
6237
+ }
3974
6238
  if (activeWorktreePaths.has(wtPath)) {
3975
6239
  report.preservedWorktrees.push({ path: wtPath, branch: wt.branch, reason: "active-session" });
3976
6240
  continue;
@@ -3991,44 +6255,33 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3991
6255
  const removeBranch = Boolean(wt.branch && wt.branch.startsWith("kith/") && (!handoffBranches.has(wt.branch) || force));
3992
6256
  if (removeBranch) report.deletedBranches.push(wt.branch);
3993
6257
  if (!dryRun) {
3994
- try {
3995
- execFileSync7("git", ["worktree", "remove", ...force ? ["--force"] : [], wtPath], {
3996
- cwd: layout.checkoutRoot,
3997
- stdio: ["ignore", "pipe", "pipe"]
3998
- });
3999
- } catch {
4000
- fs11.rmSync(wtPath, { recursive: true, force: true });
4001
- try {
4002
- execFileSync7("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
4003
- } catch {
4004
- }
4005
- }
6258
+ removeCreatedWorktree(layout.checkoutRoot, wtPath, force);
4006
6259
  if (removeBranch && wt.branch) {
4007
6260
  try {
4008
- execFileSync7("git", ["branch", "-D", wt.branch], { cwd: layout.checkoutRoot, stdio: ["ignore", "pipe", "pipe"] });
6261
+ execFileSync12("git", ["branch", "-D", wt.branch], { cwd: layout.checkoutRoot, stdio: ["ignore", "pipe", "pipe"] });
4009
6262
  } catch {
4010
6263
  }
4011
6264
  }
4012
6265
  }
4013
6266
  }
4014
6267
  const remaining = new Set(engine.worktrees.listWorktrees().map((w) => physicalPath(w.path)));
4015
- for (const entry of fs11.readdirSync(worktreesDir)) {
4016
- const orphan = physicalPath(path9.join(worktreesDir, entry));
4017
- if (remaining.has(orphan) || activeWorktreePaths.has(orphan) || !force && handoffWorktrees.has(orphan)) continue;
6268
+ for (const entry of fs13.readdirSync(worktreesDir)) {
6269
+ const orphan = physicalPath(path11.join(worktreesDir, entry));
6270
+ if (remaining.has(orphan) || activeWorktreePaths.has(orphan) || adoptedPaths.has(orphan) || !force && handoffWorktrees.has(orphan)) continue;
4018
6271
  report.removedWorktrees.push(orphan);
4019
- if (!dryRun) fs11.rmSync(orphan, { recursive: true, force: true });
6272
+ if (!dryRun) fs13.rmSync(orphan, { recursive: true, force: true });
4020
6273
  }
4021
6274
  }
4022
6275
  for (const dirName of ["snapshots", "quarantine"]) {
4023
- const dir = path9.join(layout.coordDir, dirName);
4024
- if (!fs11.existsSync(dir)) continue;
4025
- for (const entry of fs11.readdirSync(dir)) {
4026
- const full = path9.join(dir, entry);
6276
+ const dir = path11.join(layout.coordDir, dirName);
6277
+ if (!fs13.existsSync(dir)) continue;
6278
+ for (const entry of fs13.readdirSync(dir)) {
6279
+ const full = path11.join(dir, entry);
4027
6280
  try {
4028
- const stat = fs11.lstatSync(full);
6281
+ const stat = fs13.lstatSync(full);
4029
6282
  if (stat.mtimeMs < cutoff) {
4030
6283
  report.prunedArtifacts++;
4031
- if (!dryRun) fs11.rmSync(full, { recursive: true, force: true });
6284
+ if (!dryRun) fs13.rmSync(full, { recursive: true, force: true });
4032
6285
  }
4033
6286
  } catch {
4034
6287
  }
@@ -4103,26 +6356,26 @@ function sleepSync(ms) {
4103
6356
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
4104
6357
  }
4105
6358
  function withCommitLock(coordDir, fn, timeoutMs = 15e3) {
4106
- fs12.mkdirSync(coordDir, { recursive: true, mode: 448 });
4107
- const lockPath = path10.join(coordDir, "commit.lock");
6359
+ fs14.mkdirSync(coordDir, { recursive: true, mode: 448 });
6360
+ const lockPath = path12.join(coordDir, "commit.lock");
4108
6361
  const started = Date.now();
4109
6362
  let fd;
4110
6363
  while (true) {
4111
6364
  try {
4112
- fd = fs12.openSync(lockPath, "wx", 384);
4113
- fs12.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
6365
+ fd = fs14.openSync(lockPath, "wx", 384);
6366
+ fs14.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
4114
6367
  break;
4115
6368
  } catch (err) {
4116
6369
  if (err.code !== "EEXIST") throw err;
4117
6370
  try {
4118
- const raw = JSON.parse(fs12.readFileSync(lockPath, "utf8"));
6371
+ const raw = JSON.parse(fs14.readFileSync(lockPath, "utf8"));
4119
6372
  if (raw.pid && raw.pid > 0) {
4120
6373
  try {
4121
6374
  process.kill(raw.pid, 0);
4122
6375
  } catch (killErr) {
4123
6376
  if (killErr.code === "ESRCH") {
4124
6377
  try {
4125
- fs12.unlinkSync(lockPath);
6378
+ fs14.unlinkSync(lockPath);
4126
6379
  continue;
4127
6380
  } catch {
4128
6381
  }
@@ -4142,40 +6395,16 @@ function withCommitLock(coordDir, fn, timeoutMs = 15e3) {
4142
6395
  } finally {
4143
6396
  if (fd !== void 0) {
4144
6397
  try {
4145
- fs12.closeSync(fd);
6398
+ fs14.closeSync(fd);
4146
6399
  } catch {
4147
6400
  }
4148
6401
  }
4149
6402
  try {
4150
- fs12.unlinkSync(lockPath);
6403
+ fs14.unlinkSync(lockPath);
4151
6404
  } catch {
4152
6405
  }
4153
6406
  }
4154
6407
  }
4155
- function listDirtyFiles(rootDir) {
4156
- try {
4157
- const out = execFileSync8("git", ["status", "--porcelain", "-z", "--untracked-files=all"], {
4158
- cwd: rootDir,
4159
- encoding: "utf8",
4160
- stdio: ["ignore", "pipe", "ignore"]
4161
- });
4162
- const tokens = out.split("\0");
4163
- const files = [];
4164
- for (let i = 0; i < tokens.length; i++) {
4165
- const entry = tokens[i];
4166
- if (!entry || entry.length < 4) continue;
4167
- const status = entry.slice(0, 2);
4168
- const file = entry.slice(3);
4169
- if (file) files.push(file);
4170
- if ((status.startsWith("R") || status.startsWith("C")) && i + 1 < tokens.length && tokens[i + 1]) {
4171
- files.push(tokens[++i]);
4172
- }
4173
- }
4174
- return Array.from(new Set(files));
4175
- } catch {
4176
- return [];
4177
- }
4178
- }
4179
6408
  function commitScopedFiles(engine, params) {
4180
6409
  const message = (params.message ?? "").trim();
4181
6410
  if (!message) {
@@ -4224,7 +6453,7 @@ function commitScopedFiles(engine, params) {
4224
6453
  }
4225
6454
  }
4226
6455
  for (const peer of presencePeers) {
4227
- const digest = crypto10.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
6456
+ const digest = crypto11.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
4228
6457
  const autoId = `auto-${peer.client}-${digest}`;
4229
6458
  if (!params.agentId || params.agentId === autoId) {
4230
6459
  callerAgentIds.add(autoId);
@@ -4247,8 +6476,21 @@ function commitScopedFiles(engine, params) {
4247
6476
  }
4248
6477
  const primaryAgentId = params.agentId ?? [...callerAgentIds][0] ?? null;
4249
6478
  const worktreeRoot = (primaryAgentId ? engine.fencing.getAgent(primaryAgentId)?.worktree_path : null) ?? engine.coordDb.repoRoot;
6479
+ if (primaryAgentId) {
6480
+ const adoption = engine.worktrees.liveAdoption(engine.fencing.getAgent(primaryAgentId));
6481
+ if (adoption?.commitError) {
6482
+ return {
6483
+ ok: false,
6484
+ commit: null,
6485
+ branch: null,
6486
+ files: [],
6487
+ agentId: primaryAgentId,
6488
+ message,
6489
+ error: adoption.commitError
6490
+ };
6491
+ }
6492
+ }
4250
6493
  const dirtyFiles = listDirtyFiles(worktreeRoot);
4251
- const dirtySet = new Set(dirtyFiles);
4252
6494
  const activeLocks = engine.locks.listLocks();
4253
6495
  let targetFiles = [];
4254
6496
  if (params.files && params.files.length > 0) {
@@ -4256,42 +6498,14 @@ function commitScopedFiles(engine, params) {
4256
6498
  new Set(params.files.map((f) => LockEngine.normalizeFile(worktreeRoot, f)))
4257
6499
  );
4258
6500
  } else {
4259
- const collected = /* @__PURE__ */ new Set();
4260
- for (const lock of activeLocks) {
4261
- if (!callerAgentIds.has(lock.owner_agent_id)) continue;
4262
- if (lock.lock_type === "file" || !/[?*]/.test(lock.pattern)) {
4263
- const rel = lock.pattern.startsWith("file:") ? lock.pattern.slice(5) : lock.pattern;
4264
- if (!rel.startsWith("symbol:")) collected.add(rel);
4265
- } else if (lock.pattern !== "**") {
4266
- for (const df of dirtyFiles) {
4267
- if (LockEngine.patternsOverlap(LockEngine.literalScope(df), lock.pattern)) {
4268
- collected.add(df);
4269
- }
4270
- }
4271
- }
4272
- }
4273
- for (const peer of presencePeers) {
4274
- for (const touched of peer.touchedFiles) {
4275
- try {
4276
- collected.add(LockEngine.normalizeFile(worktreeRoot, touched));
4277
- } catch {
4278
- }
4279
- }
4280
- }
4281
- for (const task of engine.intents.listTasks()) {
4282
- if (task.status !== "active" || !task.owner_agent_id || !callerAgentIds.has(task.owner_agent_id)) continue;
4283
- for (const glob of task.scope_globs) {
4284
- if (glob === "**") continue;
4285
- for (const df of dirtyFiles) {
4286
- if (LockEngine.patternsOverlap(LockEngine.literalScope(df), glob)) {
4287
- collected.add(df);
4288
- }
4289
- }
4290
- }
4291
- }
4292
- const candidates = [...collected].filter((f) => dirtySet.has(f));
4293
- const ignored = candidates.length ? ignoredPaths(worktreeRoot, candidates) : /* @__PURE__ */ new Set();
4294
- targetFiles = candidates.filter((f) => !ignored.has(f));
6501
+ targetFiles = collectRecordedFiles({
6502
+ worktreeRoot,
6503
+ callerAgentIds,
6504
+ locks: activeLocks,
6505
+ tasks: engine.intents.listTasks(),
6506
+ presenceTouched: presencePeers.flatMap((peer) => peer.touchedFiles),
6507
+ dirtyFiles
6508
+ });
4295
6509
  }
4296
6510
  if (targetFiles.length === 0) {
4297
6511
  return {
@@ -4321,10 +6535,22 @@ function commitScopedFiles(engine, params) {
4321
6535
  }
4322
6536
  }
4323
6537
  }
6538
+ const leaseError = waitForSharedRefLease(engine.coordDb.coordDir, primaryAgentId);
6539
+ if (leaseError) {
6540
+ return {
6541
+ ok: false,
6542
+ commit: null,
6543
+ branch: null,
6544
+ files: [],
6545
+ agentId: primaryAgentId,
6546
+ message,
6547
+ error: leaseError
6548
+ };
6549
+ }
4324
6550
  return withCommitLock(engine.coordDb.coordDir, () => {
4325
6551
  let headBefore = null;
4326
6552
  try {
4327
- headBefore = execFileSync8("git", ["rev-parse", "--verify", "HEAD"], {
6553
+ headBefore = execFileSync13("git", ["rev-parse", "--verify", "HEAD"], {
4328
6554
  cwd: worktreeRoot,
4329
6555
  encoding: "utf8",
4330
6556
  stdio: ["ignore", "pipe", "ignore"]
@@ -4334,7 +6560,7 @@ function commitScopedFiles(engine, params) {
4334
6560
  }
4335
6561
  let branch = null;
4336
6562
  try {
4337
- branch = execFileSync8("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
6563
+ branch = execFileSync13("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
4338
6564
  cwd: worktreeRoot,
4339
6565
  encoding: "utf8",
4340
6566
  stdio: ["ignore", "pipe", "ignore"]
@@ -4342,32 +6568,32 @@ function commitScopedFiles(engine, params) {
4342
6568
  } catch {
4343
6569
  branch = null;
4344
6570
  }
4345
- const tempIndex = path10.join(
6571
+ const tempIndex = path12.join(
4346
6572
  engine.coordDb.coordDir,
4347
6573
  "shadow-index",
4348
- `commit-${process.pid}-${crypto10.randomBytes(6).toString("hex")}.index`
6574
+ `commit-${process.pid}-${crypto11.randomBytes(6).toString("hex")}.index`
4349
6575
  );
4350
- fs12.mkdirSync(path10.dirname(tempIndex), { recursive: true, mode: 448 });
6576
+ fs14.mkdirSync(path12.dirname(tempIndex), { recursive: true, mode: 448 });
4351
6577
  const gitEnv = { ...process.env, GIT_INDEX_FILE: tempIndex };
4352
6578
  try {
4353
6579
  if (headBefore) {
4354
- execFileSync8("git", ["read-tree", headBefore], {
6580
+ execFileSync13("git", ["read-tree", headBefore], {
4355
6581
  cwd: worktreeRoot,
4356
6582
  env: gitEnv,
4357
6583
  stdio: ["ignore", "pipe", "pipe"]
4358
6584
  });
4359
6585
  }
4360
- execFileSync8("git", ["add", "-A", "--", ...targetFiles], {
6586
+ execFileSync13("git", ["add", "-A", "--", ...targetFiles], {
4361
6587
  cwd: worktreeRoot,
4362
6588
  env: gitEnv,
4363
6589
  stdio: ["ignore", "pipe", "pipe"]
4364
6590
  });
4365
- const diffOut = headBefore ? execFileSync8("git", ["diff-index", "--cached", "--name-only", "-z", headBefore], {
6591
+ const diffOut = headBefore ? execFileSync13("git", ["diff-index", "--cached", "--name-only", "-z", headBefore], {
4366
6592
  cwd: worktreeRoot,
4367
6593
  env: gitEnv,
4368
6594
  encoding: "utf8",
4369
6595
  stdio: ["ignore", "pipe", "pipe"]
4370
- }) : execFileSync8("git", ["ls-files", "--cached", "-z"], {
6596
+ }) : execFileSync13("git", ["ls-files", "--cached", "-z"], {
4371
6597
  cwd: worktreeRoot,
4372
6598
  env: gitEnv,
4373
6599
  encoding: "utf8",
@@ -4385,28 +6611,28 @@ function commitScopedFiles(engine, params) {
4385
6611
  error: "Specified files have no changes relative to HEAD."
4386
6612
  };
4387
6613
  }
4388
- const treeSha = execFileSync8("git", ["write-tree"], {
6614
+ const treeSha = execFileSync13("git", ["write-tree"], {
4389
6615
  cwd: worktreeRoot,
4390
6616
  env: gitEnv,
4391
6617
  encoding: "utf8",
4392
6618
  stdio: ["ignore", "pipe", "pipe"]
4393
6619
  }).trim();
4394
6620
  const commitArgs = ["commit-tree", treeSha, ...headBefore ? ["-p", headBefore] : [], "-m", message];
4395
- const commitSha = execFileSync8("git", commitArgs, {
6621
+ const commitSha = execFileSync13("git", commitArgs, {
4396
6622
  cwd: worktreeRoot,
4397
6623
  env: gitEnv,
4398
6624
  encoding: "utf8",
4399
6625
  stdio: ["ignore", "pipe", "pipe"]
4400
6626
  }).trim();
4401
- const subject = message.split(/\r?\n/, 1)[0];
6627
+ const subject2 = message.split(/\r?\n/, 1)[0];
4402
6628
  const oldRef = headBefore ?? "0000000000000000000000000000000000000000";
4403
- execFileSync8("git", ["update-ref", "-m", `commit: ${subject}`, "HEAD", commitSha, oldRef], {
6629
+ execFileSync13("git", ["update-ref", "-m", `commit: ${subject2}`, "HEAD", commitSha, oldRef], {
4404
6630
  cwd: worktreeRoot,
4405
6631
  stdio: ["ignore", "pipe", "pipe"]
4406
6632
  });
4407
6633
  for (let attempt = 0; attempt < 5; attempt++) {
4408
6634
  try {
4409
- execFileSync8("git", ["reset", "-q", "HEAD", "--", ...committedFiles], {
6635
+ execFileSync13("git", ["reset", "-q", "HEAD", "--", ...committedFiles], {
4410
6636
  cwd: worktreeRoot,
4411
6637
  stdio: ["ignore", "pipe", "pipe"]
4412
6638
  });
@@ -4420,7 +6646,7 @@ function commitScopedFiles(engine, params) {
4420
6646
  commit: commitSha,
4421
6647
  branch,
4422
6648
  files: committedFiles,
4423
- message: subject
6649
+ message: subject2
4424
6650
  });
4425
6651
  return {
4426
6652
  ok: true,
@@ -4432,7 +6658,7 @@ function commitScopedFiles(engine, params) {
4432
6658
  };
4433
6659
  } finally {
4434
6660
  try {
4435
- fs12.unlinkSync(tempIndex);
6661
+ fs14.unlinkSync(tempIndex);
4436
6662
  } catch {
4437
6663
  }
4438
6664
  }
@@ -4442,6 +6668,7 @@ function commitScopedFiles(engine, params) {
4442
6668
  // src/core/mode.ts
4443
6669
  var WORKFLOW_MODES = ["worktrees", "main"];
4444
6670
  var MAIN_MODE_NOTE = "isolateWorktree was ignored: this repository works in the main checkout. Change the mode with `kith mode worktrees`.";
6671
+ var ADOPT_MAIN_MODE_NOTE = "Main-checkout mode: this adopted worktree is the workspace for claims and kith commit. Completion can run verification there and does not integrate the branch. Change the mode with `kith mode worktrees`.";
4445
6672
  var workflowModeFrom = (value) => value === "main" ? "main" : "worktrees";
4446
6673
  function parseWorkflowMode(value) {
4447
6674
  if (!WORKFLOW_MODES.includes(value)) throw new Error(`Mode must be one of: ${WORKFLOW_MODES.join(", ")}.`);
@@ -4449,10 +6676,10 @@ function parseWorkflowMode(value) {
4449
6676
  }
4450
6677
 
4451
6678
  // src/core/merge-train.ts
4452
- import { execFileSync as execFileSync9, execSync } from "child_process";
4453
- import crypto11 from "crypto";
4454
- import fs13 from "fs";
4455
- import path11 from "path";
6679
+ import { execFileSync as execFileSync14, execSync } from "child_process";
6680
+ import crypto12 from "crypto";
6681
+ import fs15 from "fs";
6682
+ import path13 from "path";
4456
6683
  function runVerificationCommand(command, cwd, env, timeoutMs = Number(process.env.KITH_MERGE_VERIFY_TIMEOUT_MS) || 3e5) {
4457
6684
  try {
4458
6685
  const out = execSync(command, {
@@ -4489,7 +6716,7 @@ var SpeculativeMergeTrain = class {
4489
6716
  this.fencing.assertSession(params.agentId);
4490
6717
  const sessionEnv = this.fencing.sessionEnvironment(params.agentId);
4491
6718
  const now = Date.now();
4492
- const id = `mrg_${crypto11.randomBytes(6).toString("hex")}`;
6719
+ const id = `mrg_${crypto12.randomBytes(6).toString("hex")}`;
4493
6720
  const token = this.coordDb.nextFencingToken();
4494
6721
  this.coordDb.withTransaction(() => {
4495
6722
  this.fencing.assertSession(params.agentId);
@@ -4511,16 +6738,16 @@ var SpeculativeMergeTrain = class {
4511
6738
  now
4512
6739
  );
4513
6740
  });
4514
- const stageDir = path11.join(this.coordDb.coordDir, "worktrees", `_merge_train_${id}`);
4515
- const lockPath = path11.join(this.coordDb.coordDir, "merge-train.lock");
6741
+ const stageDir = path13.join(this.coordDb.coordDir, "worktrees", `_merge_train_${id}`);
6742
+ const lockPath = path13.join(this.coordDb.coordDir, "merge-train.lock");
4516
6743
  let lockFd;
4517
6744
  const waitMs = Math.max(0, params.waitTimeoutMs ?? 0);
4518
6745
  const lockDeadline = Date.now() + waitMs;
4519
6746
  try {
4520
6747
  while (lockFd === void 0) {
4521
6748
  try {
4522
- lockFd = fs13.openSync(lockPath, "wx", 384);
4523
- fs13.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, entryId: id }));
6749
+ lockFd = fs15.openSync(lockPath, "wx", 384);
6750
+ fs15.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, entryId: id }));
4524
6751
  } catch {
4525
6752
  if (Date.now() >= lockDeadline) {
4526
6753
  throw new Error("Merge train is busy. If its owner crashed, inspect .coord/merge-train.lock before removing it.");
@@ -4542,13 +6769,13 @@ var SpeculativeMergeTrain = class {
4542
6769
  }
4543
6770
  }
4544
6771
  if (params.worktreePath) {
4545
- const statusOut = execFileSync9("git", ["status", "--porcelain"], {
6772
+ const statusOut = execFileSync14("git", ["status", "--porcelain"], {
4546
6773
  cwd: params.worktreePath,
4547
6774
  encoding: "utf8"
4548
6775
  }).trim();
4549
6776
  if (statusOut.length > 0) {
4550
- execFileSync9("git", ["add", "-A"], { cwd: params.worktreePath, env: sessionEnv, stdio: "ignore" });
4551
- execFileSync9(
6777
+ execFileSync14("git", ["add", "-A"], { cwd: params.worktreePath, env: sessionEnv, stdio: "ignore" });
6778
+ execFileSync14(
4552
6779
  "git",
4553
6780
  [
4554
6781
  "commit",
@@ -4559,25 +6786,25 @@ var SpeculativeMergeTrain = class {
4559
6786
  );
4560
6787
  }
4561
6788
  }
4562
- const sourceSha = execFileSync9("git", ["rev-parse", "--verify", "--end-of-options", `${params.branch}^{commit}`], {
6789
+ const sourceSha = execFileSync14("git", ["rev-parse", "--verify", "--end-of-options", `${params.branch}^{commit}`], {
4563
6790
  cwd: this.coordDb.repoRoot,
4564
6791
  encoding: "utf8",
4565
6792
  stdio: ["ignore", "pipe", "pipe"]
4566
6793
  }).trim();
4567
6794
  this.requireNoTargetOverlap(this.pathsChangedBySource(sourceSha));
4568
6795
  this.cleanupStageWorktree(stageDir);
4569
- execFileSync9("git", ["worktree", "add", "--detach", stageDir, baseHead], {
6796
+ execFileSync14("git", ["worktree", "add", "--detach", stageDir, baseHead], {
4570
6797
  cwd: this.coordDb.repoRoot,
4571
6798
  stdio: "ignore"
4572
6799
  });
4573
- const rootNodeModules = path11.join(this.coordDb.repoRoot, "node_modules");
4574
- const stageNodeModules = path11.join(stageDir, "node_modules");
4575
- const hydratedNodeModules = fs13.existsSync(rootNodeModules) && !fs13.existsSync(stageNodeModules);
6800
+ const rootNodeModules = path13.join(this.coordDb.repoRoot, "node_modules");
6801
+ const stageNodeModules = path13.join(stageDir, "node_modules");
6802
+ const hydratedNodeModules = fs15.existsSync(rootNodeModules) && !fs15.existsSync(stageNodeModules);
4576
6803
  if (hydratedNodeModules) {
4577
- fs13.symlinkSync(rootNodeModules, stageNodeModules, process.platform === "win32" ? "junction" : "dir");
6804
+ fs15.symlinkSync(rootNodeModules, stageNodeModules, process.platform === "win32" ? "junction" : "dir");
4578
6805
  }
4579
6806
  try {
4580
- execFileSync9(
6807
+ execFileSync14(
4581
6808
  "git",
4582
6809
  ["merge", "--no-ff", "-m", `Merge branch '${params.branch}' (${params.agentId})`, sourceSha],
4583
6810
  {
@@ -4588,7 +6815,7 @@ var SpeculativeMergeTrain = class {
4588
6815
  }
4589
6816
  );
4590
6817
  } catch {
4591
- const conflictedFiles = execFileSync9("git", ["diff", "--name-only", "--diff-filter=U", "-z"], {
6818
+ const conflictedFiles = execFileSync14("git", ["diff", "--name-only", "--diff-filter=U", "-z"], {
4592
6819
  cwd: stageDir,
4593
6820
  encoding: "utf8"
4594
6821
  }).split("\0").filter(Boolean);
@@ -4599,11 +6826,11 @@ var SpeculativeMergeTrain = class {
4599
6826
  if (params.verificationCmd) {
4600
6827
  diagnostics = runVerificationCommand(params.verificationCmd, stageDir, sessionEnv, params.verificationTimeoutMs);
4601
6828
  }
4602
- const stageChanges = execFileSync9("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6829
+ const stageChanges = execFileSync14("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
4603
6830
  cwd: stageDir,
4604
6831
  encoding: "utf8"
4605
6832
  }).split("\0").filter(Boolean);
4606
- const unchangedHydration = hydratedNodeModules && fs13.lstatSync(stageNodeModules, { throwIfNoEntry: false })?.isSymbolicLink() && physicalPath(stageNodeModules) === physicalPath(rootNodeModules);
6833
+ const unchangedHydration = hydratedNodeModules && fs15.lstatSync(stageNodeModules, { throwIfNoEntry: false })?.isSymbolicLink() && physicalPath(stageNodeModules) === physicalPath(rootNodeModules);
4607
6834
  if (this.gitHead(stageDir) !== verifiedSha || stageChanges.some((change) => !(unchangedHydration && change === "?? node_modules"))) {
4608
6835
  throw new Error("Verification changed the staging checkout. Apply fixes in the source worktree and retry with a read-only check.");
4609
6836
  }
@@ -4612,7 +6839,7 @@ var SpeculativeMergeTrain = class {
4612
6839
  }
4613
6840
  this.fencing.assertSession(params.agentId);
4614
6841
  this.requireNoTargetOverlap(this.pathsBetween(baseHead, verifiedSha));
4615
- execFileSync9("git", ["merge", "--ff-only", verifiedSha], {
6842
+ execFileSync14("git", ["merge", "--ff-only", verifiedSha], {
4616
6843
  cwd: this.coordDb.repoRoot,
4617
6844
  stdio: "ignore"
4618
6845
  });
@@ -4660,16 +6887,16 @@ var SpeculativeMergeTrain = class {
4660
6887
  };
4661
6888
  } finally {
4662
6889
  if (lockFd !== void 0) {
4663
- fs13.closeSync(lockFd);
4664
- fs13.unlinkSync(lockPath);
6890
+ fs15.closeSync(lockFd);
6891
+ fs15.unlinkSync(lockPath);
4665
6892
  }
4666
6893
  }
4667
6894
  }
4668
6895
  gitHead(cwd) {
4669
- return execFileSync9("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
6896
+ return execFileSync14("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
4670
6897
  }
4671
6898
  gitBranch(cwd) {
4672
- return execFileSync9("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
6899
+ return execFileSync14("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
4673
6900
  cwd,
4674
6901
  encoding: "utf8",
4675
6902
  stdio: ["ignore", "pipe", "ignore"]
@@ -4677,7 +6904,7 @@ var SpeculativeMergeTrain = class {
4677
6904
  }
4678
6905
  /** Paths with uncommitted changes in the target checkout. Untracked directories end in `/`. Kith's own state is excluded. */
4679
6906
  dirtyTargetPaths() {
4680
- const records = execFileSync9("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6907
+ const records = execFileSync14("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
4681
6908
  cwd: this.coordDb.repoRoot,
4682
6909
  encoding: "utf8"
4683
6910
  }).split("\0").filter(Boolean);
@@ -4690,7 +6917,7 @@ var SpeculativeMergeTrain = class {
4690
6917
  return paths;
4691
6918
  }
4692
6919
  diffNames(...refs) {
4693
- return execFileSync9("git", ["diff", "--name-only", "-z", "--no-renames", ...refs], {
6920
+ return execFileSync14("git", ["diff", "--name-only", "-z", "--no-renames", ...refs], {
4694
6921
  cwd: this.coordDb.repoRoot,
4695
6922
  encoding: "utf8"
4696
6923
  }).split("\0").filter(Boolean);
@@ -4698,7 +6925,7 @@ var SpeculativeMergeTrain = class {
4698
6925
  /** Paths a merge of `sourceSha` will bring into the target: the source's own changes since the merge base. */
4699
6926
  pathsChangedBySource(sourceSha) {
4700
6927
  try {
4701
- const base = execFileSync9("git", ["merge-base", "HEAD", sourceSha], {
6928
+ const base = execFileSync14("git", ["merge-base", "HEAD", sourceSha], {
4702
6929
  cwd: this.coordDb.repoRoot,
4703
6930
  encoding: "utf8",
4704
6931
  stdio: ["ignore", "pipe", "ignore"]
@@ -4727,18 +6954,18 @@ var SpeculativeMergeTrain = class {
4727
6954
  }
4728
6955
  }
4729
6956
  cleanupStageWorktree(stageDir) {
4730
- if (!fs13.existsSync(stageDir)) return;
6957
+ if (!fs15.existsSync(stageDir)) return;
4731
6958
  try {
4732
- execFileSync9("git", ["worktree", "remove", "--force", stageDir], {
6959
+ execFileSync14("git", ["worktree", "remove", "--force", stageDir], {
4733
6960
  cwd: this.coordDb.repoRoot,
4734
6961
  stdio: "ignore"
4735
6962
  });
4736
6963
  } catch {
4737
- if (fs13.existsSync(stageDir)) {
4738
- fs13.rmSync(stageDir, { recursive: true, force: true });
6964
+ if (fs15.existsSync(stageDir)) {
6965
+ fs15.rmSync(stageDir, { recursive: true, force: true });
4739
6966
  }
4740
6967
  try {
4741
- execFileSync9("git", ["worktree", "prune"], {
6968
+ execFileSync14("git", ["worktree", "prune"], {
4742
6969
  cwd: this.coordDb.repoRoot,
4743
6970
  stdio: "ignore"
4744
6971
  });
@@ -4756,10 +6983,19 @@ var SpeculativeMergeTrain = class {
4756
6983
  };
4757
6984
 
4758
6985
  // src/core/shadow-git.ts
4759
- import { execFileSync as execFileSync10 } from "child_process";
4760
- import crypto12 from "crypto";
4761
- import fs14 from "fs";
4762
- import path12 from "path";
6986
+ import { execFileSync as execFileSync15 } from "child_process";
6987
+ import crypto13 from "crypto";
6988
+ import fs16 from "fs";
6989
+ import os2 from "os";
6990
+ import path14 from "path";
6991
+ function isGitBlob(value) {
6992
+ return typeof value === "string" && /^[0-9a-f]{40,64}$/i.test(value);
6993
+ }
6994
+ function sameIdSet(left, right) {
6995
+ if (left.length !== right.length) return false;
6996
+ const have = new Set(left);
6997
+ return right.every((id) => have.has(id));
6998
+ }
4763
6999
  var ShadowGitEngine = class {
4764
7000
  constructor(coordDb, fencing) {
4765
7001
  this.coordDb = coordDb;
@@ -4769,7 +7005,7 @@ var ShadowGitEngine = class {
4769
7005
  fencing;
4770
7006
  isGitRepository(dir = this.coordDb.repoRoot) {
4771
7007
  try {
4772
- execFileSync10("git", ["rev-parse", "--is-inside-work-tree"], {
7008
+ execFileSync15("git", ["rev-parse", "--is-inside-work-tree"], {
4773
7009
  cwd: dir,
4774
7010
  stdio: "ignore"
4775
7011
  });
@@ -4780,7 +7016,7 @@ var ShadowGitEngine = class {
4780
7016
  }
4781
7017
  blobAt(commit, filePath) {
4782
7018
  try {
4783
- const out = execFileSync10("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", filePath], { cwd: this.coordDb.repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
7019
+ const out = execFileSync15("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", filePath], { cwd: this.coordDb.repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
4784
7020
  return /^\d+ blob ([0-9a-f]+)\t/.exec(out)?.[1] ?? null;
4785
7021
  } catch {
4786
7022
  return null;
@@ -4788,7 +7024,7 @@ var ShadowGitEngine = class {
4788
7024
  }
4789
7025
  getHeadCommit(dir = this.coordDb.repoRoot) {
4790
7026
  try {
4791
- return execFileSync10("git", ["rev-parse", "HEAD"], {
7027
+ return execFileSync15("git", ["rev-parse", "HEAD"], {
4792
7028
  cwd: dir,
4793
7029
  encoding: "utf8",
4794
7030
  stdio: ["ignore", "pipe", "ignore"]
@@ -4800,7 +7036,7 @@ var ShadowGitEngine = class {
4800
7036
  getShadowIndexPath(agentId) {
4801
7037
  const safeId = agentId.replace(/[^a-zA-Z0-9_-]/g, "_");
4802
7038
  const epoch = this.fencing.assertSession(agentId);
4803
- return path12.join(this.coordDb.coordDir, "shadow-index", `${safeId}-${epoch}.index`);
7039
+ return path14.join(this.coordDb.coordDir, "shadow-index", `${safeId}-${epoch}.index`);
4804
7040
  }
4805
7041
  /**
4806
7042
  * Updates an agent's ephemeral shadow Git index (`.coord/shadow-index/<agent-id>.index`)
@@ -4816,23 +7052,23 @@ var ShadowGitEngine = class {
4816
7052
  if (!headCommit) return null;
4817
7053
  const shadowIndex = this.getShadowIndexPath(params.agentId);
4818
7054
  const env = { ...process.env, GIT_INDEX_FILE: shadowIndex };
4819
- if (!fs14.existsSync(shadowIndex)) {
4820
- execFileSync10("git", ["read-tree", headCommit], {
7055
+ if (!fs16.existsSync(shadowIndex)) {
7056
+ execFileSync15("git", ["read-tree", headCommit], {
4821
7057
  cwd: targetDir,
4822
7058
  env,
4823
7059
  stdio: "ignore"
4824
7060
  });
4825
- fs14.writeFileSync(`${shadowIndex}.base`, headCommit);
7061
+ fs16.writeFileSync(`${shadowIndex}.base`, headCommit);
4826
7062
  } else {
4827
7063
  this.rebaseShadowIndex(shadowIndex, targetDir, env, headCommit);
4828
7064
  }
4829
7065
  if (params.worktreeDir && (!params.modifiedFiles || params.modifiedFiles.length === 0)) {
4830
- execFileSync10("git", ["read-tree", headCommit], {
7066
+ execFileSync15("git", ["read-tree", headCommit], {
4831
7067
  cwd: targetDir,
4832
7068
  env,
4833
7069
  stdio: "ignore"
4834
7070
  });
4835
- execFileSync10("git", ["add", "-A"], {
7071
+ execFileSync15("git", ["add", "-A"], {
4836
7072
  cwd: targetDir,
4837
7073
  env,
4838
7074
  stdio: "ignore"
@@ -4842,34 +7078,34 @@ var ShadowGitEngine = class {
4842
7078
  for (const mod of params.modifiedFiles) {
4843
7079
  const relPath = LockEngine.normalizeFile(targetDir, mod.filePath);
4844
7080
  if (ignored.has(relPath)) continue;
4845
- const absPath = path12.join(targetDir, relPath);
4846
- const content = mod.content ?? (fs14.existsSync(absPath) ? fs14.readFileSync(absPath, "utf8") : null);
7081
+ const absPath = path14.join(targetDir, relPath);
7082
+ const content = mod.content ?? (fs16.existsSync(absPath) ? fs16.readFileSync(absPath, "utf8") : null);
4847
7083
  if (content === null) {
4848
7084
  {
4849
- execFileSync10("git", ["--literal-pathspecs", "update-index", "--force-remove", "--", relPath], {
7085
+ execFileSync15("git", ["--literal-pathspecs", "update-index", "--force-remove", "--", relPath], {
4850
7086
  cwd: targetDir,
4851
7087
  env,
4852
7088
  stdio: "ignore"
4853
7089
  });
4854
7090
  }
4855
7091
  } else {
4856
- const tracked = execFileSync10("git", ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", relPath], {
7092
+ const tracked = execFileSync15("git", ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", relPath], {
4857
7093
  cwd: targetDir,
4858
7094
  env,
4859
7095
  encoding: "utf8"
4860
7096
  }).split("\0").find(Boolean);
4861
7097
  const trackedMode = tracked?.split(" ")[0];
4862
- const stat = fs14.existsSync(absPath) ? fs14.lstatSync(absPath) : null;
7098
+ const stat = fs16.existsSync(absPath) ? fs16.lstatSync(absPath) : null;
4863
7099
  if (trackedMode && !["100644", "100755"].includes(trackedMode) || stat?.isSymbolicLink()) {
4864
7100
  throw new Error(`Cannot report symlinks or special entries as source content: ${relPath}`);
4865
7101
  }
4866
7102
  const mode = trackedMode ?? (stat && stat.mode & 73 ? "100755" : "100644");
4867
- const blobSha = execFileSync10("git", ["hash-object", "-w", "--stdin"], {
7103
+ const blobSha = execFileSync15("git", ["hash-object", "-w", "--stdin"], {
4868
7104
  cwd: targetDir,
4869
7105
  input: content,
4870
7106
  encoding: "utf8"
4871
7107
  }).trim();
4872
- execFileSync10(
7108
+ execFileSync15(
4873
7109
  "git",
4874
7110
  ["update-index", "--add", "--cacheinfo", `${mode},${blobSha},${relPath}`],
4875
7111
  {
@@ -4881,12 +7117,12 @@ var ShadowGitEngine = class {
4881
7117
  }
4882
7118
  }
4883
7119
  }
4884
- const treeSha = execFileSync10("git", ["write-tree"], {
7120
+ const treeSha = execFileSync15("git", ["write-tree"], {
4885
7121
  cwd: targetDir,
4886
7122
  env,
4887
7123
  encoding: "utf8"
4888
7124
  }).trim();
4889
- const shadowCommitSha = execFileSync10(
7125
+ const shadowCommitSha = execFileSync15(
4890
7126
  "git",
4891
7127
  ["commit-tree", treeSha, "-p", headCommit, "-m", `kith-shadow:${params.agentId}`],
4892
7128
  {
@@ -4909,15 +7145,15 @@ var ShadowGitEngine = class {
4909
7145
  const baseFile = `${shadowIndex}.base`;
4910
7146
  let base = "";
4911
7147
  try {
4912
- base = fs14.readFileSync(baseFile, "utf8").trim();
7148
+ base = fs16.readFileSync(baseFile, "utf8").trim();
4913
7149
  } catch {
4914
7150
  }
4915
7151
  if (base === head) return;
4916
7152
  try {
4917
7153
  if (base) {
4918
- const raw = execFileSync10("git", ["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head], { cwd: dir, encoding: "utf8" }).split("\0");
7154
+ const raw = execFileSync15("git", ["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head], { cwd: dir, encoding: "utf8" }).split("\0");
4919
7155
  const staged = /* @__PURE__ */ new Map();
4920
- for (const line of execFileSync10("git", ["ls-files", "--stage", "-z"], { cwd: dir, env, encoding: "utf8" }).split("\0")) {
7156
+ for (const line of execFileSync15("git", ["ls-files", "--stage", "-z"], { cwd: dir, env, encoding: "utf8" }).split("\0")) {
4921
7157
  const m = /^\d+ ([0-9a-f]+) \d\t([\s\S]+)$/.exec(line);
4922
7158
  if (m) staged.set(m[2], m[1]);
4923
7159
  }
@@ -4932,9 +7168,9 @@ var ShadowGitEngine = class {
4932
7168
  const untouched = oldSha === zero ? mine === void 0 : mine === oldSha;
4933
7169
  if (untouched) info.push(newSha === zero ? `0 ${zero} ${file}` : `${newMode} ${newSha} ${file}`);
4934
7170
  }
4935
- if (info.length) execFileSync10("git", ["update-index", "--index-info", "-z"], { cwd: dir, env, input: info.join("\0") + "\0", stdio: ["pipe", "ignore", "ignore"] });
7171
+ if (info.length) execFileSync15("git", ["update-index", "--index-info", "-z"], { cwd: dir, env, input: info.join("\0") + "\0", stdio: ["pipe", "ignore", "ignore"] });
4936
7172
  }
4937
- fs14.writeFileSync(baseFile, head);
7173
+ fs16.writeFileSync(baseFile, head);
4938
7174
  } catch {
4939
7175
  }
4940
7176
  }
@@ -4980,7 +7216,7 @@ var ShadowGitEngine = class {
4980
7216
  probePairConflict(agentA, commitA, agentB, commitB) {
4981
7217
  this.fencing.assertSession(agentA);
4982
7218
  try {
4983
- const stdout = execFileSync10(
7219
+ const stdout = execFileSync15(
4984
7220
  "git",
4985
7221
  ["merge-tree", "--write-tree", "-z", commitA, commitB],
4986
7222
  {
@@ -5023,7 +7259,7 @@ var ShadowGitEngine = class {
5023
7259
  if (committed && (stages.stage2 === committed || stages.stage3 === committed)) continue;
5024
7260
  const severity = "text_conflict";
5025
7261
  const record = {
5026
- id: `conf_${crypto12.randomBytes(6).toString("hex")}`,
7262
+ id: `conf_${crypto13.randomBytes(6).toString("hex")}`,
5027
7263
  agent_a: agentA,
5028
7264
  agent_b: agentB,
5029
7265
  file_path: filePath,
@@ -5072,8 +7308,8 @@ var ShadowGitEngine = class {
5072
7308
  }
5073
7309
  /** Remove orphaned shadow Git index files left behind by dead or completed sessions. */
5074
7310
  pruneStaleShadowIndexes(dryRun = false) {
5075
- const indexDir = path12.join(this.coordDb.coordDir, "shadow-index");
5076
- if (!fs14.existsSync(indexDir)) return 0;
7311
+ const indexDir = path14.join(this.coordDb.coordDir, "shadow-index");
7312
+ if (!fs16.existsSync(indexDir)) return 0;
5077
7313
  const activeRows = this.coordDb.db.prepare(`
5078
7314
  SELECT a.id AS agent_id, s.epoch AS epoch
5079
7315
  FROM agents a JOIN agent_sessions s ON a.id = s.agent_id
@@ -5081,22 +7317,210 @@ var ShadowGitEngine = class {
5081
7317
  `).all();
5082
7318
  const keep = new Set(activeRows.map((r) => `${r.agent_id.replace(/[^a-zA-Z0-9_-]/g, "_")}-${r.epoch}.index`));
5083
7319
  let removed = 0;
5084
- for (const entry of fs14.readdirSync(indexDir, { withFileTypes: true })) {
7320
+ for (const entry of fs16.readdirSync(indexDir, { withFileTypes: true })) {
5085
7321
  if (!entry.isFile() || !entry.name.endsWith(".index") || keep.has(entry.name)) continue;
5086
7322
  if (dryRun) {
5087
7323
  removed++;
5088
7324
  continue;
5089
7325
  }
5090
7326
  try {
5091
- fs14.unlinkSync(path12.join(indexDir, entry.name));
7327
+ fs16.unlinkSync(path14.join(indexDir, entry.name));
5092
7328
  removed++;
5093
7329
  } catch {
5094
7330
  }
5095
7331
  }
5096
7332
  return removed;
5097
7333
  }
7334
+ /** Counts from the most recent {@link pruneFalseConflicts} call. Tests assert the probe budget. */
7335
+ lastConflictHygiene = {
7336
+ mergeFileProbes: 0,
7337
+ headReads: 0,
7338
+ removed: 0,
7339
+ probeDir: null
7340
+ };
7341
+ /**
7342
+ * Drop stored conflicts that are no longer real. 0.1.8 already refuses to record a side equal
7343
+ * to HEAD, or two identical sides, while probing. Rows written before that commit, or before
7344
+ * HEAD moved, stay until something reads them. `git merge-file` runs only for triples not
7345
+ * already settled, at most `maxMergeProbes` per call, and the decision is cached by HEAD sha
7346
+ * plus conflict id so a later status read does not spawn those processes again. Probe files
7347
+ * live in the system temp directory and are removed before this returns.
7348
+ */
7349
+ pruneFalseConflicts(maxMergeProbes = 100) {
7350
+ const stats = { mergeFileProbes: 0, headReads: 0, removed: 0, probeDir: null };
7351
+ this.lastConflictHygiene = stats;
7352
+ const rows = this.coordDb.db.prepare("SELECT * FROM conflicts").all();
7353
+ if (!rows.length) return 0;
7354
+ const parsed = rows.map((row) => {
7355
+ let details = { reason: "" };
7356
+ try {
7357
+ details = JSON.parse(String(row.details_json));
7358
+ } catch {
7359
+ }
7360
+ return {
7361
+ id: String(row.id),
7362
+ file: String(row.file_path),
7363
+ severity: String(row.severity),
7364
+ details
7365
+ };
7366
+ });
7367
+ const doomed = /* @__PURE__ */ new Set();
7368
+ for (const row of parsed) {
7369
+ const { blobA, blobB } = row.details;
7370
+ if (row.severity === "text_conflict" && isGitBlob(blobA) && blobA === blobB) doomed.add(row.id);
7371
+ }
7372
+ const cache = this.readHygieneCache();
7373
+ const head = this.getHeadCommit();
7374
+ const headChecked = new Set(cache.head === head ? cache.headChecked : []);
7375
+ const mergeSettled = new Set(cache.mergeSettled);
7376
+ const needHead = parsed.filter((row) => !doomed.has(row.id) && row.severity === "text_conflict" && (isGitBlob(row.details.blobA) || isGitBlob(row.details.blobB)) && !headChecked.has(row.id));
7377
+ if (needHead.length) {
7378
+ const atHead = head ? this.blobsAtCommit(head, [...new Set(needHead.map((row) => row.file))], stats) : null;
7379
+ if (atHead) {
7380
+ for (const row of needHead) {
7381
+ const committed = atHead.get(row.file) ?? null;
7382
+ if (committed && (row.details.blobA === committed || row.details.blobB === committed)) doomed.add(row.id);
7383
+ headChecked.add(row.id);
7384
+ }
7385
+ }
7386
+ }
7387
+ const needMerge = parsed.filter((row) => !doomed.has(row.id) && row.severity === "text_conflict" && isGitBlob(row.details.baseBlob) && isGitBlob(row.details.blobA) && isGitBlob(row.details.blobB) && !mergeSettled.has(row.id));
7388
+ const batch = needMerge.slice(0, Math.max(0, maxMergeProbes));
7389
+ if (batch.length) {
7390
+ const dir = fs16.mkdtempSync(path14.join(this.mergeProbeParent(), "kith-merge-probe-"));
7391
+ stats.probeDir = dir;
7392
+ try {
7393
+ for (const row of batch) {
7394
+ stats.mergeFileProbes++;
7395
+ const merged = this.blobsMergeCleanly(dir, row.details.baseBlob, row.details.blobA, row.details.blobB);
7396
+ if (merged === "clean") doomed.add(row.id);
7397
+ else if (merged === "conflict") mergeSettled.add(row.id);
7398
+ }
7399
+ } finally {
7400
+ fs16.rmSync(dir, { recursive: true, force: true });
7401
+ }
7402
+ }
7403
+ for (const row of parsed) {
7404
+ if (doomed.has(row.id)) continue;
7405
+ const probeable = row.severity === "text_conflict" && isGitBlob(row.details.baseBlob) && isGitBlob(row.details.blobA) && isGitBlob(row.details.blobB);
7406
+ if (!probeable) mergeSettled.add(row.id);
7407
+ }
7408
+ if (doomed.size) {
7409
+ this.coordDb.withTransaction(() => {
7410
+ const del = this.coordDb.db.prepare("DELETE FROM conflicts WHERE id = ?");
7411
+ for (const id of doomed) del.run(id);
7412
+ });
7413
+ }
7414
+ stats.removed = doomed.size;
7415
+ const remain = new Set(parsed.filter((row) => !doomed.has(row.id)).map((row) => row.id));
7416
+ const nextCache = {
7417
+ head,
7418
+ headChecked: [...headChecked].filter((id) => remain.has(id)),
7419
+ mergeSettled: [...mergeSettled].filter((id) => remain.has(id))
7420
+ };
7421
+ if (doomed.size || !sameIdSet(cache.headChecked, nextCache.headChecked) || !sameIdSet(cache.mergeSettled, nextCache.mergeSettled) || cache.head !== head) {
7422
+ this.writeHygieneCache(nextCache);
7423
+ }
7424
+ return doomed.size;
7425
+ }
7426
+ blobsAtCommit(commit, files, stats) {
7427
+ const found = /* @__PURE__ */ new Map();
7428
+ try {
7429
+ for (let offset = 0; offset < files.length; offset += 200) {
7430
+ const chunk = files.slice(offset, offset + 200);
7431
+ stats.headReads++;
7432
+ const out = execFileSync15("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", ...chunk], {
7433
+ cwd: this.coordDb.repoRoot,
7434
+ encoding: "utf8",
7435
+ stdio: ["ignore", "pipe", "ignore"],
7436
+ maxBuffer: 8 * 1024 * 1024
7437
+ });
7438
+ for (const line of out.split("\0")) {
7439
+ const match = /^\d+ blob ([0-9a-f]+)\t([\s\S]+)$/.exec(line);
7440
+ if (match) found.set(match[2], match[1]);
7441
+ }
7442
+ }
7443
+ } catch {
7444
+ return null;
7445
+ }
7446
+ for (const file of files) if (!found.has(file)) found.set(file, null);
7447
+ return found;
7448
+ }
7449
+ /** `conflict` is a real overlap. `error` is not cached, so a later read can retry the probe. */
7450
+ blobsMergeCleanly(dir, base, blobA, blobB) {
7451
+ const show = (sha, name) => {
7452
+ const file = path14.join(dir, name);
7453
+ const bytes = execFileSync15("git", ["cat-file", "blob", sha], {
7454
+ cwd: this.coordDb.repoRoot,
7455
+ stdio: ["ignore", "pipe", "ignore"],
7456
+ maxBuffer: 16 * 1024 * 1024
7457
+ });
7458
+ fs16.writeFileSync(file, bytes);
7459
+ return file;
7460
+ };
7461
+ try {
7462
+ const ours = show(blobA, "a");
7463
+ const baseFile = show(base, "base");
7464
+ const theirs = show(blobB, "b");
7465
+ try {
7466
+ execFileSync15("git", ["merge-file", ours, baseFile, theirs], { cwd: dir, stdio: "ignore" });
7467
+ return "clean";
7468
+ } catch (err) {
7469
+ const status = err.status;
7470
+ return typeof status === "number" && status > 0 ? "conflict" : "error";
7471
+ }
7472
+ } catch {
7473
+ return "error";
7474
+ }
7475
+ }
7476
+ /** Prefer the system temp dir. If that lives inside this checkout, step outside it. */
7477
+ mergeProbeParent() {
7478
+ const repo = fs16.realpathSync(this.coordDb.repoRoot);
7479
+ for (const candidate of [os2.tmpdir(), "/tmp", os2.homedir()]) {
7480
+ try {
7481
+ const real = fs16.realpathSync(candidate);
7482
+ const relative = path14.relative(repo, real);
7483
+ if (relative.startsWith("..") || path14.isAbsolute(relative)) return real;
7484
+ } catch {
7485
+ }
7486
+ }
7487
+ return fs16.realpathSync(os2.tmpdir());
7488
+ }
7489
+ hygieneCachePath() {
7490
+ return path14.join(this.coordDb.coordDir, "conflict-hygiene.json");
7491
+ }
7492
+ readHygieneCache() {
7493
+ try {
7494
+ const raw = JSON.parse(fs16.readFileSync(this.hygieneCachePath(), "utf8"));
7495
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
7496
+ return {
7497
+ head: typeof raw.head === "string" || raw.head === null ? raw.head : null,
7498
+ headChecked: strings(raw.headChecked),
7499
+ mergeSettled: strings(raw.mergeSettled)
7500
+ };
7501
+ } catch {
7502
+ return { head: null, headChecked: [], mergeSettled: [] };
7503
+ }
7504
+ }
7505
+ writeHygieneCache(cache) {
7506
+ const file = this.hygieneCachePath();
7507
+ const tmp = `${file}.${process.pid}.tmp`;
7508
+ try {
7509
+ fs16.writeFileSync(tmp, JSON.stringify(cache));
7510
+ fs16.renameSync(tmp, file);
7511
+ } catch {
7512
+ try {
7513
+ fs16.unlinkSync(tmp);
7514
+ } catch {
7515
+ }
7516
+ }
7517
+ }
5098
7518
  listConflicts() {
5099
7519
  this.fencing.reapDeadAgents();
7520
+ try {
7521
+ this.pruneFalseConflicts();
7522
+ } catch {
7523
+ }
5100
7524
  const rows = this.coordDb.db.prepare(`SELECT * FROM conflicts ORDER BY detected_at DESC`).all();
5101
7525
  return rows.map((r) => ({
5102
7526
  id: String(r.id),
@@ -5111,15 +7535,15 @@ var ShadowGitEngine = class {
5111
7535
  };
5112
7536
 
5113
7537
  // src/core/workspace-contracts.ts
5114
- import { execFileSync as execFileSync11 } from "child_process";
5115
- import fs16 from "fs";
5116
- import path14 from "path";
7538
+ import { execFileSync as execFileSync16 } from "child_process";
7539
+ import fs18 from "fs";
7540
+ import path16 from "path";
5117
7541
 
5118
7542
  // src/core/observation.ts
5119
- import crypto13 from "crypto";
5120
- import fs15 from "fs";
5121
- import os2 from "os";
5122
- import path13 from "path";
7543
+ import crypto14 from "crypto";
7544
+ import fs17 from "fs";
7545
+ import os3 from "os";
7546
+ import path15 from "path";
5123
7547
  function extractRecentAgentFiles(rows) {
5124
7548
  const result = {};
5125
7549
  for (const row of rows) {
@@ -5178,40 +7602,41 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5178
7602
  workspaces: [],
5179
7603
  handoffs: [],
5180
7604
  workflowMode: "worktrees",
5181
- workflowModeConfigured: false
7605
+ workflowModeConfigured: false,
7606
+ worktreeRegistrations: []
5182
7607
  };
5183
7608
  let scratch, db;
5184
7609
  try {
5185
- const file = path13.join(layout.coordDir, "state.db");
7610
+ const file = path15.join(layout.coordDir, "state.db");
5186
7611
  if (physicalPath(layout.coordDir) !== layout.coordDir || physicalPath(file) !== file) throw new Error("Coordination state must not be a symlink");
5187
- for (let current = fs15.realpathSync.native(directory); isWithin(layout.checkoutRoot, current); current = path13.dirname(current)) {
5188
- const local = path13.join(current, ".coord");
5189
- if (local !== layout.coordDir && fs15.existsSync(path13.join(local, "state.db"))) throw new Error(`Legacy independent state at ${local}; preserve it before consolidation`);
7612
+ for (let current = fs17.realpathSync.native(directory); isWithin(layout.checkoutRoot, current); current = path15.dirname(current)) {
7613
+ const local = path15.join(current, ".coord");
7614
+ if (local !== layout.coordDir && fs17.existsSync(path15.join(local, "state.db"))) throw new Error(`Legacy independent state at ${local}; preserve it before consolidation`);
5190
7615
  if (current === layout.checkoutRoot) break;
5191
7616
  }
5192
- if (!fs15.existsSync(file)) {
5193
- if (["setup.lock", "merge-train.lock"].some((name) => fs15.existsSync(path13.join(layout.coordDir, name))) || ["-wal", "-shm", "-journal"].some((s) => fs15.existsSync(file + s)) || ["worktrees", "quarantine", "snapshots", "shadow-index", "setup"].some((name) => {
5194
- const p = path13.join(layout.coordDir, name);
5195
- return fs15.existsSync(p) && (!fs15.lstatSync(p).isDirectory() || fs15.readdirSync(p).length > 0);
7617
+ if (!fs17.existsSync(file)) {
7618
+ if (["setup.lock", "merge-train.lock"].some((name) => fs17.existsSync(path15.join(layout.coordDir, name))) || ["-wal", "-shm", "-journal"].some((s) => fs17.existsSync(file + s)) || ["worktrees", "quarantine", "snapshots", "shadow-index", "setup"].some((name) => {
7619
+ const p = path15.join(layout.coordDir, name);
7620
+ return fs17.existsSync(p) && (!fs17.lstatSync(p).isDirectory() || fs17.readdirSync(p).length > 0);
5196
7621
  })) throw new Error("Missing database with retained sidecars; preserve the recovery set");
5197
7622
  return empty;
5198
7623
  }
5199
7624
  const files = ["", "-wal", "-shm", "-journal"].map((s) => file + s);
5200
7625
  const identity = (f) => {
5201
- if (!fs15.existsSync(f)) return null;
5202
- if (physicalPath(f) !== f || !fs15.lstatSync(f).isFile()) throw new Error("Database or sidecar is redirected or not a regular file");
5203
- const s = fs15.statSync(f, { bigint: true });
7626
+ if (!fs17.existsSync(f)) return null;
7627
+ if (physicalPath(f) !== f || !fs17.lstatSync(f).isFile()) throw new Error("Database or sidecar is redirected or not a regular file");
7628
+ const s = fs17.statSync(f, { bigint: true });
5204
7629
  return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
5205
7630
  };
5206
7631
  const before = files.map(identity);
5207
- scratch = fs15.mkdtempSync(path13.join(os2.tmpdir(), "kith-observe-"));
7632
+ scratch = fs17.mkdtempSync(path15.join(os3.tmpdir(), "kith-observe-"));
5208
7633
  for (let i = 0; i < files.length; i++) if (before[i]) {
5209
- const target = path13.join(scratch, path13.basename(files[i]));
5210
- fs15.copyFileSync(files[i], target);
5211
- fs15.chmodSync(target, 384);
7634
+ const target = path15.join(scratch, path15.basename(files[i]));
7635
+ fs17.copyFileSync(files[i], target);
7636
+ fs17.chmodSync(target, 384);
5212
7637
  }
5213
7638
  if (JSON.stringify(before) !== JSON.stringify(files.map(identity))) throw new Error("Coordination state changed during snapshot; stop writers or retry");
5214
- db = new (sqliteDatabase())(path13.join(scratch, "state.db"), { readOnly: true });
7639
+ db = new (sqliteDatabase())(path15.join(scratch, "state.db"), { readOnly: true });
5215
7640
  db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN");
5216
7641
  const schemaVersion = CoordDatabase.inspectSchema(db);
5217
7642
  if (schemaVersion < 2) throw new Error("Offline observation requires schema 2 or newer; preserve state and upgrade with clients stopped");
@@ -5221,6 +7646,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5221
7646
  const rawMode = db.prepare("SELECT value FROM meta WHERE key='workflow_mode'").get()?.value;
5222
7647
  const workflowModeConfigured = rawMode === "main" || rawMode === "worktrees";
5223
7648
  const workflowMode = workflowModeFrom(rawMode);
7649
+ const worktreeRegistrations = hasTable("worktree_registrations") ? all("SELECT agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at FROM worktree_registrations ORDER BY registered_at").map(registrationFromRow) : [];
5224
7650
  const agents = all("SELECT * FROM agents ORDER BY registered_at DESC" + (options.coordinationOnly ? " LIMIT 201" : ""));
5225
7651
  const recentAgentFiles = !options.ownersOnly ? extractRecentAgentFiles(all("SELECT agent_id, event_type, payload_json FROM events WHERE event_type IN ('locks_acquired','contracts_updated','contract_breaking_change') ORDER BY id DESC LIMIT 200")) : {};
5226
7652
  if (options.coordinationOnly) {
@@ -5250,12 +7676,13 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5250
7676
  commandGuards,
5251
7677
  mergeQueue,
5252
7678
  recentAgentFiles,
7679
+ worktreeRegistrations,
5253
7680
  truncated: [agents, tasks, resources, mutexWaiters, commandGuards, mergeQueue].some((rows) => rows.length > 200) || locks.length > 500
5254
7681
  };
5255
7682
  }
5256
7683
  if (options.ownersOnly) {
5257
7684
  db.exec("COMMIT");
5258
- return { ...empty, state: "ready", schemaVersion, agents };
7685
+ return { ...empty, state: "ready", schemaVersion, agents, worktreeRegistrations };
5259
7686
  }
5260
7687
  const state = {
5261
7688
  ...empty,
@@ -5264,6 +7691,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5264
7691
  handoffs,
5265
7692
  workflowMode,
5266
7693
  workflowModeConfigured,
7694
+ worktreeRegistrations,
5267
7695
  fencingEpoch: Number(db.prepare("SELECT value FROM meta WHERE key='fencing_epoch'").get().value),
5268
7696
  agents,
5269
7697
  tasks: all("SELECT * FROM tasks ORDER BY priority DESC,created_at").map(({ depends_on_json, scope_globs_json, ...r }) => ({ ...r, depends_on: JSON.parse(String(depends_on_json)), scope_globs: JSON.parse(String(scope_globs_json)) })),
@@ -5285,7 +7713,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5285
7713
  return { ...empty, state: "unavailable", error: error instanceof Error ? error.message : String(error) };
5286
7714
  } finally {
5287
7715
  db?.close();
5288
- if (scratch) fs15.rmSync(scratch, { recursive: true, force: true });
7716
+ if (scratch) fs17.rmSync(scratch, { recursive: true, force: true });
5289
7717
  }
5290
7718
  }
5291
7719
  function readBrief(directory = process.cwd(), options = {}) {
@@ -5346,7 +7774,7 @@ function readBrief(directory = process.cwd(), options = {}) {
5346
7774
  if (peers.length) {
5347
7775
  for (const peer of peers) {
5348
7776
  const cleanClient = peer.client.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase() || "agent";
5349
- const hash = crypto13.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
7777
+ const hash = crypto14.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
5350
7778
  const autoId = `auto-${cleanClient}-${hash}`;
5351
7779
  const resolvedId = peer.agentId || autoId;
5352
7780
  if (seenAgentIds.has(resolvedId) || seenAgentIds.has(autoId) || seenPids.has(peer.pid) || [...seenPids].some((pid) => ownedByCaller(pid, peer.pid))) {
@@ -5379,19 +7807,19 @@ function readBrief(directory = process.cwd(), options = {}) {
5379
7807
  }, { ...options, scopeGlobs });
5380
7808
  }
5381
7809
  function recoveryReport(directory = process.cwd()) {
5382
- const state = readCoordinationState(directory), retainedRoot = path13.join(state.repository.coordDir, "worktrees");
5383
- const retained = physicalPath(retainedRoot) === retainedRoot && fs15.existsSync(retainedRoot) && fs15.lstatSync(retainedRoot).isDirectory() && !fs15.lstatSync(retainedRoot).isSymbolicLink() ? fs15.readdirSync(retainedRoot, { withFileTypes: true }).map((entry) => ({
5384
- path: path13.join(retainedRoot, entry.name),
7810
+ const state = readCoordinationState(directory), retainedRoot = path15.join(state.repository.coordDir, "worktrees");
7811
+ const retained = physicalPath(retainedRoot) === retainedRoot && fs17.existsSync(retainedRoot) && fs17.lstatSync(retainedRoot).isDirectory() && !fs17.lstatSync(retainedRoot).isSymbolicLink() ? fs17.readdirSync(retainedRoot, { withFileTypes: true }).map((entry) => ({
7812
+ path: path15.join(retainedRoot, entry.name),
5385
7813
  symlink: entry.isSymbolicLink(),
5386
- agentIds: state.agents.filter((a) => a.worktree_path === path13.join(retainedRoot, entry.name)).map((a) => a.id)
7814
+ agentIds: state.agents.filter((a) => a.worktree_path === path15.join(retainedRoot, entry.name)).map((a) => a.id)
5387
7815
  })) : [];
5388
7816
  return {
5389
7817
  ...state,
5390
7818
  retainedWorktrees: retained,
5391
7819
  expiredClaims: state.locks.filter((lock) => Number(lock.expires_at) <= state.observedAt),
5392
7820
  unfinishedIntegrations: state.mergeQueue.filter((entry) => entry.status !== "merged"),
5393
- setupLock: { path: path13.join(state.repository.coordDir, "setup.lock"), present: fs15.existsSync(path13.join(state.repository.coordDir, "setup.lock")) },
5394
- integrationLock: { path: path13.join(state.repository.coordDir, "merge-train.lock"), present: fs15.existsSync(path13.join(state.repository.coordDir, "merge-train.lock")) }
7821
+ setupLock: { path: path15.join(state.repository.coordDir, "setup.lock"), present: fs17.existsSync(path15.join(state.repository.coordDir, "setup.lock")) },
7822
+ integrationLock: { path: path15.join(state.repository.coordDir, "merge-train.lock"), present: fs17.existsSync(path15.join(state.repository.coordDir, "merge-train.lock")) }
5395
7823
  };
5396
7824
  }
5397
7825
 
@@ -5467,8 +7895,8 @@ var MAX_SOURCE_BYTES = 64 * 1024;
5467
7895
  var MAX_REPLY_BYTES = 16 * 1024;
5468
7896
  var MAX_LINKS = 8;
5469
7897
  var MAX_SYMBOLS = 64;
5470
- function git2(root, ...args) {
5471
- return execFileSync11("git", ["-c", "core.fsmonitor=false", ...args], {
7898
+ function git3(root, ...args) {
7899
+ return execFileSync16("git", ["-c", "core.fsmonitor=false", ...args], {
5472
7900
  cwd: root,
5473
7901
  encoding: "utf8",
5474
7902
  stdio: ["ignore", "pipe", "pipe"],
@@ -5478,21 +7906,21 @@ function git2(root, ...args) {
5478
7906
  }).trim();
5479
7907
  }
5480
7908
  function readBounded(file) {
5481
- const fd = fs16.openSync(file, "r");
7909
+ const fd = fs18.openSync(file, "r");
5482
7910
  try {
5483
- const stat = fs16.fstatSync(fd);
7911
+ const stat = fs18.fstatSync(fd);
5484
7912
  if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) throw new Error("Contract/config file exceeds inspection limit or is not a regular file");
5485
7913
  const bytes = Buffer.alloc(MAX_SOURCE_BYTES + 1);
5486
- const size = fs16.readSync(fd, bytes, 0, bytes.length, 0);
7914
+ const size = fs18.readSync(fd, bytes, 0, bytes.length, 0);
5487
7915
  if (size > MAX_SOURCE_BYTES) throw new Error("Contract/config file exceeds inspection limit");
5488
7916
  return bytes.subarray(0, size).toString("utf8");
5489
7917
  } finally {
5490
- fs16.closeSync(fd);
7918
+ fs18.closeSync(fd);
5491
7919
  }
5492
7920
  }
5493
7921
  function resolveFile(base) {
5494
- for (const name of [base, `${base}.ts`, `${base}.tsx`, `${base}.d.ts`, `${base}.js`, `${base}.jsx`, path14.join(base, "index.ts"), path14.join(base, "index.js")]) {
5495
- if (fs16.existsSync(name) && fs16.statSync(name).isFile()) return physicalPath(name);
7922
+ for (const name of [base, `${base}.ts`, `${base}.tsx`, `${base}.d.ts`, `${base}.js`, `${base}.jsx`, path16.join(base, "index.ts"), path16.join(base, "index.js")]) {
7923
+ if (fs18.existsSync(name) && fs18.statSync(name).isFile()) return physicalPath(name);
5496
7924
  }
5497
7925
  }
5498
7926
  function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
@@ -5507,8 +7935,8 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5507
7935
  const activeRoot = layout.checkoutRoot;
5508
7936
  let config = null;
5509
7937
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
5510
- const file = path14.join(activeRoot, name);
5511
- if (!fs16.existsSync(file)) continue;
7938
+ const file = path16.join(activeRoot, name);
7939
+ if (!fs18.existsSync(file)) continue;
5512
7940
  repositoryFile(activeRoot, file);
5513
7941
  config = parseJsoncObject(readBounded(file));
5514
7942
  if (!config) unavailable(`Cannot parse ${name}; aliases were not inspected.`);
@@ -5526,11 +7954,11 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5526
7954
  unavailable("Worktree repository identity differs from the caller.");
5527
7955
  return report;
5528
7956
  }
5529
- const bases = [.../* @__PURE__ */ new Set([activeRoot, caller.checkoutRoot])].map((root) => path14.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : "."));
7957
+ const bases = [.../* @__PURE__ */ new Set([activeRoot, caller.checkoutRoot])].map((root) => path16.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : "."));
5530
7958
  let symbolBudget = MAX_SYMBOLS;
5531
7959
  const aliases = Object.entries(options.paths).sort(([a], [b]) => b.length - a.length);
5532
7960
  if (aliases.length > 32) unavailable("Alias limit reached; inspection is partial.");
5533
- const externalTargets = (targets) => Array.isArray(targets) && targets.slice(0, 8).some((target) => typeof target === "string" && !isWithin(caller.checkoutRoot, physicalPath(path14.resolve(bases[bases.length - 1], target.replace("*", "")))));
7961
+ const externalTargets = (targets) => Array.isArray(targets) && targets.slice(0, 8).some((target) => typeof target === "string" && !isWithin(caller.checkoutRoot, physicalPath(path16.resolve(bases[bases.length - 1], target.replace("*", "")))));
5534
7962
  const selected = imports ? [...new Set(imports)].slice(0, 32) : aliases.slice(0, 32).filter(([a]) => !a.includes("*")).map(([a]) => a);
5535
7963
  if (imports && imports.length > 32) unavailable("Import limit reached; inspection is partial.");
5536
7964
  if (!imports && aliases.some(([a, targets]) => a.includes("*") && externalTargets(targets))) unavailable("Wildcard aliases are checked for concrete imports after edits; not enumerated by status.");
@@ -5553,7 +7981,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5553
7981
  for (const target of targets.slice(0, 8)) {
5554
7982
  if (typeof target !== "string" || (target.match(/\*/g)?.length ?? 0) > 1) continue;
5555
7983
  for (const base of bases) {
5556
- externalFile = resolveFile(path14.resolve(base, target.replace("*", substitution)));
7984
+ externalFile = resolveFile(path16.resolve(base, target.replace("*", substitution)));
5557
7985
  if (externalFile) break;
5558
7986
  }
5559
7987
  if (externalFile) break;
@@ -5563,14 +7991,14 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5563
7991
  continue;
5564
7992
  }
5565
7993
  if (isWithin(activeRoot, externalFile)) continue;
5566
- const sibling = discoverRepository(path14.dirname(externalFile));
7994
+ const sibling = discoverRepository(path16.dirname(externalFile));
5567
7995
  if (!sibling.commonGitDir || sibling.commonGitDir === layout.commonGitDir) {
5568
7996
  unavailable(`'${specifier}' does not select a separate Git repository; no external source was read.`);
5569
7997
  continue;
5570
7998
  }
5571
7999
  const siblingRoot = sibling.checkoutRoot;
5572
8000
  const relative = repositoryFile(siblingRoot, externalFile);
5573
- git2(siblingRoot, "ls-files", "--error-unmatch", "--", relative);
8001
+ git3(siblingRoot, "ls-files", "--error-unmatch", "--", relative);
5574
8002
  if (report.linkedContracts.length >= MAX_LINKS || symbolBudget <= 0) {
5575
8003
  unavailable("Contract/symbol limit reached; inspection is partial.");
5576
8004
  break;
@@ -5588,7 +8016,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5588
8016
  if (!exportsComplete) unavailable(`'${specifier}' exports are partial or re-exported; missing-export checks are unavailable.`);
5589
8017
  let dirtyInCheckout = null;
5590
8018
  try {
5591
- dirtyInCheckout = Boolean(git2(siblingRoot, "status", "--porcelain=v1", "--", relative));
8019
+ dirtyInCheckout = Boolean(git3(siblingRoot, "status", "--porcelain=v1", "--", relative));
5592
8020
  } catch {
5593
8021
  unavailable(`'${specifier}' Git status is unavailable.`);
5594
8022
  }
@@ -5603,7 +8031,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5603
8031
  try {
5604
8032
  const wt = discoverRepository(agent.worktree_path);
5605
8033
  if (wt.checkoutRoot !== physicalPath(agent.worktree_path) || wt.commonGitDir !== sibling.commonGitDir) throw new Error("Worktree identity changed");
5606
- const file = path14.join(wt.checkoutRoot, relative);
8034
+ const file = path16.join(wt.checkoutRoot, relative);
5607
8035
  repositoryFile(wt.checkoutRoot, file);
5608
8036
  const current = AstAnalyzer.extractExports(readBounded(file));
5609
8037
  const original = new Map(extracted.map((s) => [s.symbolName, s.astHash]));
@@ -5617,7 +8045,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5617
8045
  }
5618
8046
  }
5619
8047
  if (agents.length > 8) unavailable(`'${specifier}' owner/worktree inspection limit reached.`);
5620
- const link = { alias: specifier, sourceRepo: siblingRoot, sourceRepoName: path14.basename(siblingRoot), filePath: relative, absolutePath: externalFile, symbols, exportsComplete, ownershipAvailable, dirtyInCheckout, lockedByAgent: locked ? String(locked.owner_agent_id) : null, activeWorktreeDrifts: drifts };
8048
+ const link = { alias: specifier, sourceRepo: siblingRoot, sourceRepoName: path16.basename(siblingRoot), filePath: relative, absolutePath: externalFile, symbols, exportsComplete, ownershipAvailable, dirtyInCheckout, lockedByAgent: locked ? String(locked.owner_agent_id) : null, activeWorktreeDrifts: drifts };
5621
8049
  report.linkedContracts.push(link);
5622
8050
  if (Buffer.byteLength(JSON.stringify(report)) > MAX_REPLY_BYTES - 3e3) {
5623
8051
  report.linkedContracts.pop();
@@ -5659,9 +8087,9 @@ function verifyCrossRepoImportsForFile(params) {
5659
8087
  }
5660
8088
 
5661
8089
  // src/core/worktree-cow.ts
5662
- import { execFileSync as execFileSync12 } from "child_process";
5663
- import fs17 from "fs";
5664
- import path15 from "path";
8090
+ import { execFileSync as execFileSync17 } from "child_process";
8091
+ import fs19 from "fs";
8092
+ import path17 from "path";
5665
8093
  var CoWWorktreeManager = class _CoWWorktreeManager {
5666
8094
  constructor(coordDb, fencing) {
5667
8095
  this.coordDb = coordDb;
@@ -5681,34 +8109,40 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5681
8109
  const safeId = params.agentId.replace(/[^a-zA-Z0-9_-]/g, "-");
5682
8110
  const branch = params.branch ?? `kith/${safeId}`;
5683
8111
  const baseRef = params.baseRef ?? "HEAD";
5684
- const worktreePath = path15.join(this.coordDb.coordDir, "worktrees", safeId);
8112
+ const worktreePath = path17.join(this.coordDb.coordDir, "worktrees", safeId);
5685
8113
  if (!this.fencing.getAgent(params.agentId)) throw new Error(`Unknown agent: ${params.agentId}`);
5686
8114
  if (!safeId || safeId === "." || safeId === "..") throw new Error("Invalid agent ID");
5687
- if (fs17.existsSync(worktreePath)) {
8115
+ if (fs19.existsSync(worktreePath)) {
5688
8116
  throw new Error(`Worktree already exists: ${worktreePath}. Commit or preserve its work before removing it.`);
5689
8117
  }
5690
- fs17.mkdirSync(path15.dirname(worktreePath), { recursive: true });
5691
- execFileSync12("git", ["worktree", "add", "-b", branch, worktreePath, baseRef], {
8118
+ fs19.mkdirSync(path17.dirname(worktreePath), { recursive: true });
8119
+ execFileSync17("git", ["worktree", "add", "-b", branch, worktreePath, baseRef], {
5692
8120
  cwd: this.coordDb.repoRoot,
5693
8121
  stdio: "ignore"
5694
8122
  });
5695
8123
  const hydratedDirs = [];
5696
8124
  let hydrationMethod = "none";
5697
8125
  for (const dirName of _CoWWorktreeManager.HYDRATABLE_DIRS) {
5698
- const srcDir = path15.join(this.coordDb.repoRoot, dirName);
5699
- const destDir = path15.join(worktreePath, dirName);
5700
- if (!fs17.existsSync(srcDir) || fs17.existsSync(destDir)) continue;
8126
+ const srcDir = path17.join(this.coordDb.repoRoot, dirName);
8127
+ const destDir = path17.join(worktreePath, dirName);
8128
+ if (!fs19.existsSync(srcDir) || fs19.existsSync(destDir)) continue;
5701
8129
  const method = this.cloneDirectoryCoW(srcDir, destDir);
5702
8130
  if (hydrationMethod !== "copy") hydrationMethod = method;
5703
8131
  hydratedDirs.push(dirName);
5704
8132
  }
5705
8133
  for (const envName of _CoWWorktreeManager.ENV_FILES) {
5706
- const srcEnv = path15.join(this.coordDb.repoRoot, envName);
5707
- const destEnv = path15.join(worktreePath, envName);
5708
- if (fs17.existsSync(srcEnv) && !fs17.existsSync(destEnv)) {
5709
- fs17.copyFileSync(srcEnv, destEnv);
8134
+ const srcEnv = path17.join(this.coordDb.repoRoot, envName);
8135
+ const destEnv = path17.join(worktreePath, envName);
8136
+ if (fs19.existsSync(srcEnv) && !fs19.existsSync(destEnv)) {
8137
+ fs19.copyFileSync(srcEnv, destEnv);
5710
8138
  }
5711
8139
  }
8140
+ let head = null;
8141
+ try {
8142
+ head = execFileSync17("git", ["rev-parse", "HEAD"], { cwd: worktreePath, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8143
+ } catch {
8144
+ head = null;
8145
+ }
5712
8146
  this.coordDb.withTransaction(() => {
5713
8147
  this.fencing.assertSession(params.agentId);
5714
8148
  this.coordDb.db.prepare(`UPDATE agents SET worktree_path = ?, branch = ? WHERE id = ?`).run(worktreePath, branch, params.agentId);
@@ -5718,6 +8152,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5718
8152
  hydrationMethod,
5719
8153
  hydratedDirs
5720
8154
  });
8155
+ recordCreatedWorktree(this.coordDb, this.fencing, { agentId: params.agentId, worktreePath, branch, head });
5721
8156
  });
5722
8157
  return {
5723
8158
  agentId: params.agentId,
@@ -5725,14 +8160,21 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5725
8160
  branch,
5726
8161
  hydrationMethod,
5727
8162
  hydratedDirs,
5728
- durationMs: Date.now() - start
8163
+ durationMs: Date.now() - start,
8164
+ provenance: "created",
8165
+ source: "kith",
8166
+ detached: false,
8167
+ dirty: false,
8168
+ branchCheckedOutElsewhere: false,
8169
+ alreadyRegistered: false,
8170
+ notes: []
5729
8171
  };
5730
8172
  }
5731
8173
  cloneDirectoryCoW(srcDir, destDir) {
5732
8174
  const cowTimeoutMs = Number(process.env.KITH_COW_TIMEOUT_MS) || 6e4;
5733
8175
  if (process.platform === "darwin") {
5734
8176
  try {
5735
- execFileSync12("cp", ["-cR", srcDir, destDir], {
8177
+ execFileSync17("cp", ["-cR", srcDir, destDir], {
5736
8178
  stdio: "ignore",
5737
8179
  timeout: cowTimeoutMs
5738
8180
  });
@@ -5741,7 +8183,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5741
8183
  }
5742
8184
  } else if (process.platform === "linux") {
5743
8185
  try {
5744
- execFileSync12("cp", ["--reflink=always", "-R", srcDir, destDir], {
8186
+ execFileSync17("cp", ["--reflink=always", "-R", srcDir, destDir], {
5745
8187
  stdio: "ignore",
5746
8188
  timeout: cowTimeoutMs
5747
8189
  });
@@ -5749,59 +8191,91 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5749
8191
  } catch {
5750
8192
  }
5751
8193
  }
5752
- fs17.rmSync(destDir, { recursive: true, force: true });
5753
- fs17.cpSync(srcDir, destDir, { recursive: true, dereference: false });
8194
+ fs19.rmSync(destDir, { recursive: true, force: true });
8195
+ fs19.cpSync(srcDir, destDir, { recursive: true, dereference: false });
5754
8196
  return "copy";
5755
8197
  }
5756
- removeWorktree(agentId) {
8198
+ removeWorktree(agentId, options) {
5757
8199
  this.fencing.assertSession(agentId);
8200
+ const registration = readRegistration(this.coordDb, agentId);
8201
+ const agentPath = this.fencing.getAgent(agentId)?.worktree_path ?? null;
8202
+ const adopted = registration?.provenance === "adopted" || Boolean(agentPath && !isKithOwnedWorktree(this.coordDb, agentPath));
8203
+ if (adopted) {
8204
+ if (!options?.deleteAdopted) {
8205
+ throw new Error(`Refusing to remove an adopted worktree Kith did not create (${agentPath ?? registration?.worktreePath}). The directory was left in place. Pass --delete-adopted to remove it explicitly, or \`kith worktree forget\` to unregister it.`);
8206
+ }
8207
+ const target = agentPath ?? registration?.worktreePath;
8208
+ if (!target || !fs19.existsSync(target)) {
8209
+ throw new Error(`Adopted worktree directory is missing (${target ?? "unknown"}). Nothing was deleted. Use \`kith worktree forget\` to drop the registration.`);
8210
+ }
8211
+ this.removeCheckout(target, true);
8212
+ this.clearAgentWorktree(agentId);
8213
+ return true;
8214
+ }
5758
8215
  const safeId = agentId.replace(/[^a-zA-Z0-9_-]/g, "-");
5759
- const worktreePath = path15.join(this.coordDb.coordDir, "worktrees", safeId);
5760
- if (!fs17.existsSync(worktreePath)) return false;
5761
- const registered = this.fencing.getAgent(agentId)?.worktree_path;
8216
+ const worktreePath = path17.join(this.coordDb.coordDir, "worktrees", safeId);
8217
+ if (!fs19.existsSync(worktreePath)) return false;
8218
+ const registered = agentPath;
5762
8219
  if (!registered || physicalPath(registered) !== physicalPath(worktreePath) || this.fencing.listAgents(true).some((agent) => agent.id !== agentId && agent.worktree_path && physicalPath(agent.worktree_path) === physicalPath(worktreePath))) {
5763
8220
  throw new Error("Refusing to remove a worktree that is not exclusively registered to this agent.");
5764
8221
  }
5765
- const status = execFileSync12("git", ["status", "--porcelain", "--untracked-files=normal", "--ignored=matching"], {
8222
+ this.removeCheckout(worktreePath, false);
8223
+ this.clearAgentWorktree(agentId);
8224
+ return true;
8225
+ }
8226
+ removeCheckout(worktreePath, adopted) {
8227
+ const status = execFileSync17("git", ["status", "--porcelain", "--untracked-files=normal", "--ignored=matching"], {
5766
8228
  cwd: worktreePath,
5767
8229
  encoding: "utf8"
5768
8230
  });
5769
8231
  if (status.trim()) {
5770
8232
  throw new Error(`Refusing to remove dirty worktree: ${worktreePath}. Commit or preserve changed, untracked, and ignored files first.`);
5771
8233
  }
5772
- execFileSync12("git", ["worktree", "remove", worktreePath], {
5773
- cwd: this.coordDb.repoRoot,
5774
- stdio: ["ignore", "pipe", "pipe"]
5775
- });
8234
+ try {
8235
+ execFileSync17("git", ["worktree", "remove", worktreePath], {
8236
+ cwd: this.coordDb.repoRoot,
8237
+ stdio: ["ignore", "pipe", "pipe"]
8238
+ });
8239
+ } catch (err) {
8240
+ if (!adopted) throw err;
8241
+ const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
8242
+ throw new Error(`git worktree remove failed; the adopted directory was left in place. ${stderr}`.trim());
8243
+ }
8244
+ }
8245
+ clearAgentWorktree(agentId) {
5776
8246
  this.coordDb.withTransaction(() => {
5777
8247
  this.fencing.assertSession(agentId);
8248
+ clearRegistration(this.coordDb, agentId);
5778
8249
  this.coordDb.db.prepare(`UPDATE agents SET worktree_path = NULL, branch = NULL WHERE id = ?`).run(agentId);
5779
8250
  });
5780
- return true;
5781
8251
  }
5782
8252
  listWorktrees() {
5783
- try {
5784
- const out = execFileSync12("git", ["worktree", "list", "--porcelain"], {
5785
- cwd: this.coordDb.repoRoot,
5786
- encoding: "utf8"
5787
- });
5788
- const entries = [];
5789
- let current = null;
5790
- for (const line of out.split(/\r?\n/)) {
5791
- if (line.startsWith("worktree ")) {
5792
- if (current) entries.push(current);
5793
- current = { path: line.slice("worktree ".length).trim(), head: "", branch: null };
5794
- } else if (line.startsWith("HEAD ") && current) {
5795
- current.head = line.slice("HEAD ".length).trim();
5796
- } else if (line.startsWith("branch ") && current) {
5797
- current.branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
5798
- }
5799
- }
5800
- if (current) entries.push(current);
5801
- return entries;
5802
- } catch {
5803
- return [];
5804
- }
8253
+ return listGitWorktrees(this.coordDb.repoRoot);
8254
+ }
8255
+ registrationFor(agentId) {
8256
+ return readRegistration(this.coordDb, agentId);
8257
+ }
8258
+ listRegistrations() {
8259
+ return listRegistrations(this.coordDb);
8260
+ }
8261
+ adoptWorktree(params) {
8262
+ return adoptWorktree(this.coordDb, this.fencing, {
8263
+ agentId: params.agentId,
8264
+ path: params.path,
8265
+ explicit: params.explicit !== false
8266
+ });
8267
+ }
8268
+ adoptIfUnambiguous(params) {
8269
+ return adoptIfUnambiguous(this.coordDb, this.fencing, params);
8270
+ }
8271
+ syncRegistration(agentId) {
8272
+ return syncRegistration(this.coordDb, this.fencing, agentId);
8273
+ }
8274
+ liveAdoption(agent) {
8275
+ return liveAdoption(this.coordDb, this.fencing, agent);
8276
+ }
8277
+ forgetWorktree(agentId) {
8278
+ return forgetWorktree(this.coordDb, this.fencing, agentId);
5805
8279
  }
5806
8280
  };
5807
8281
 
@@ -5861,7 +8335,14 @@ var KithEngine = class {
5861
8335
  return next;
5862
8336
  }
5863
8337
  commit(params) {
5864
- return commitScopedFiles(this, params);
8338
+ const result = commitScopedFiles(this, params);
8339
+ if (result.ok) {
8340
+ try {
8341
+ this.shadowGit.pruneFalseConflicts();
8342
+ } catch {
8343
+ }
8344
+ }
8345
+ return result;
5865
8346
  }
5866
8347
  /** Read-only situational summary from live state: who is active on what, open handoffs, conflicts, claims that overlap a scope. */
5867
8348
  brief(options = {}) {
@@ -5905,7 +8386,7 @@ var KithEngine = class {
5905
8386
  warnings: []
5906
8387
  };
5907
8388
  }
5908
- const content = params.content ?? (fs18.existsSync(path16.join(targetRoot, file)) ? fs18.readFileSync(path16.join(targetRoot, file), "utf8") : "");
8389
+ const content = params.content ?? (fs20.existsSync(path18.join(targetRoot, file)) ? fs20.readFileSync(path18.join(targetRoot, file), "utf8") : "");
5909
8390
  const contractReport = this.depGraph.recordFileModification(
5910
8391
  params.agentId,
5911
8392
  file,
@@ -5982,10 +8463,10 @@ var KithEngine = class {
5982
8463
  const held = this.coordDb.db.prepare(`SELECT pattern FROM locks WHERE owner_agent_id = ?`).all(agentId).map((l) => l.pattern.replace(/^file:/, ""));
5983
8464
  const mine = activeConflicts.filter((c) => c.agent_a === agentId || held.some((p) => c.file_path === p || LockEngine.patternsOverlap(p, c.file_path)));
5984
8465
  const keyOf = (c) => `${c.file_path}\0${c.agent_a === agentId ? c.agent_b : c.agent_a}`;
5985
- const seenFile = path16.join(this.coordDb.coordDir, "delta-seen", `${agentId.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`);
8466
+ const seenFile = path18.join(this.coordDb.coordDir, "delta-seen", `${agentId.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`);
5986
8467
  let seen = { keys: [], others: 0 };
5987
8468
  try {
5988
- seen = JSON.parse(fs18.readFileSync(seenFile, "utf8"));
8469
+ seen = JSON.parse(fs20.readFileSync(seenFile, "utf8"));
5989
8470
  } catch {
5990
8471
  }
5991
8472
  const seenKeys = new Set(seen.keys);
@@ -6000,8 +8481,8 @@ var KithEngine = class {
6000
8481
  try {
6001
8482
  const keys = mine.map(keyOf).sort();
6002
8483
  if (fresh.length || others !== seen.others || keys.length !== seen.keys.length) {
6003
- fs18.mkdirSync(path16.dirname(seenFile), { recursive: true });
6004
- fs18.writeFileSync(seenFile, JSON.stringify({ keys, others }));
8484
+ fs20.mkdirSync(path18.dirname(seenFile), { recursive: true });
8485
+ fs20.writeFileSync(seenFile, JSON.stringify({ keys, others }));
6005
8486
  }
6006
8487
  } catch {
6007
8488
  }
@@ -6049,7 +8530,8 @@ ${kept.join("\n")}` : "";
6049
8530
  handoffs: handoffBlock(this.handoffs.unresolved(10), { summaryMax: 300, filesMax: 5 }),
6050
8531
  mutexWaiters: this.coordDb.db.prepare("SELECT ticket,mutex_name,owner_agent_id,session_epoch,expires_at FROM mutex_waiters ORDER BY ticket").all(),
6051
8532
  commandGuards: this.coordDb.db.prepare("SELECT mutex_name,owner_agent_id,worker_pid,supervisor_pid FROM mutex_runs ORDER BY mutex_name").all(),
6052
- workspaces: observeWorkspaces(this.coordDb.repoRoot, agents)
8533
+ workspaces: observeWorkspaces(this.coordDb.repoRoot, agents),
8534
+ worktreeRegistrations: this.worktrees.listRegistrations()
6053
8535
  };
6054
8536
  }
6055
8537
  previewIntegration(agentId) {
@@ -6057,13 +8539,19 @@ ${kept.join("\n")}` : "";
6057
8539
  return previewIntegration(this.coordDb.repoRoot, this.fencing.getAgent(agentId));
6058
8540
  }
6059
8541
  beginWork(params) {
6060
- const mode = this.workflowMode(), isolate = mode === "main" ? false : params.isolateWorktree;
6061
- const notes = mode === "main" && params.isolateWorktree ? [MAIN_MODE_NOTE] : [];
8542
+ this.worktrees.syncRegistration(params.agentId);
8543
+ const mode = this.workflowMode();
8544
+ const adopting = Boolean(params.adoptWorktree || params.worktreePath);
8545
+ const isolate = mode === "main" ? false : Boolean(params.isolateWorktree) && !adopting;
8546
+ const notes = [
8547
+ ...mode === "main" && params.isolateWorktree && !adopting ? [MAIN_MODE_NOTE] : [],
8548
+ ...mode === "main" && adopting ? [ADOPT_MAIN_MODE_NOTE] : []
8549
+ ];
6062
8550
  const intent = this.intents.declareIntent(params);
6063
8551
  let worktree = null;
6064
- if (intent.ok && isolate && intent.task) {
8552
+ if (intent.ok && (isolate || adopting) && intent.task) {
6065
8553
  try {
6066
- worktree = this.worktrees.spawnWorktree({ agentId: params.agentId });
8554
+ worktree = adopting ? this.worktrees.adoptWorktree({ agentId: params.agentId, path: params.worktreePath, explicit: true }) : this.claimWorktree(params.agentId);
6067
8555
  } catch (err) {
6068
8556
  this.coordDb.withTransaction(() => {
6069
8557
  this.coordDb.db.prepare("DELETE FROM locks WHERE task_id = ?").run(intent.task.id);
@@ -6076,6 +8564,9 @@ ${kept.join("\n")}` : "";
6076
8564
  this.coordDb.repoRoot,
6077
8565
  worktree?.worktreePath ?? this.fencing.getAgent(params.agentId)?.worktree_path ?? void 0
6078
8566
  );
8567
+ if (worktree && "notes" in worktree && Array.isArray(worktree.notes)) {
8568
+ for (const note of worktree.notes) if (!notes.includes(note)) notes.push(note);
8569
+ }
6079
8570
  return {
6080
8571
  ...intent,
6081
8572
  worktree,
@@ -6088,13 +8579,19 @@ ${kept.join("\n")}` : "";
6088
8579
  };
6089
8580
  }
6090
8581
  claimNextTask(params) {
6091
- const mode = this.workflowMode(), isolate = mode === "main" ? false : params.isolateWorktree;
6092
- const notes = mode === "main" && params.isolateWorktree ? [MAIN_MODE_NOTE] : [];
8582
+ this.worktrees.syncRegistration(params.agentId);
8583
+ const mode = this.workflowMode();
8584
+ const adopting = Boolean(params.adoptWorktree || params.worktreePath);
8585
+ const isolate = mode === "main" ? false : Boolean(params.isolateWorktree) && !adopting;
8586
+ const notes = [
8587
+ ...mode === "main" && params.isolateWorktree && !adopting ? [MAIN_MODE_NOTE] : [],
8588
+ ...mode === "main" && adopting ? [ADOPT_MAIN_MODE_NOTE] : []
8589
+ ];
6093
8590
  const claimedRes = this.intents.claimNextTask(params.agentId);
6094
8591
  let worktree = null;
6095
- if (claimedRes.claimed && isolate && claimedRes.task) {
8592
+ if (claimedRes.claimed && (isolate || adopting) && claimedRes.task) {
6096
8593
  try {
6097
- worktree = this.claimWorktree(params.agentId);
8594
+ worktree = adopting ? this.worktrees.adoptWorktree({ agentId: params.agentId, path: params.worktreePath, explicit: true }) : this.claimWorktree(params.agentId);
6098
8595
  } catch (err) {
6099
8596
  this.coordDb.withTransaction(() => {
6100
8597
  this.coordDb.db.prepare("DELETE FROM locks WHERE task_id = ?").run(claimedRes.task.id);
@@ -6108,6 +8605,9 @@ ${kept.join("\n")}` : "";
6108
8605
  this.coordDb.repoRoot,
6109
8606
  worktree?.worktreePath ?? this.fencing.getAgent(params.agentId)?.worktree_path ?? void 0
6110
8607
  );
8608
+ if (worktree && "notes" in worktree && Array.isArray(worktree.notes)) {
8609
+ for (const note of worktree.notes) if (!notes.includes(note)) notes.push(note);
8610
+ }
6111
8611
  return {
6112
8612
  ...claimedRes,
6113
8613
  worktree,
@@ -6124,26 +8624,43 @@ ${kept.join("\n")}` : "";
6124
8624
  this.fencing.assertSession(agentId);
6125
8625
  const agent = this.fencing.getAgent(agentId);
6126
8626
  if (!agent.worktree_path) return this.worktrees.spawnWorktree({ agentId });
8627
+ const registration = this.worktrees.registrationFor(agentId);
8628
+ const adopted = registration?.provenance === "adopted" || !registration && !isKithOwnedWorktree(this.coordDb, agent.worktree_path);
8629
+ if (adopted) return this.worktrees.adoptWorktree({ agentId, path: agent.worktree_path, explicit: true });
6127
8630
  const root = physicalPath(agent.worktree_path);
6128
8631
  const owner = discoverRepository(this.coordDb.repoRoot);
6129
8632
  const layout = discoverRepository(root);
6130
- const git3 = (...args) => execFileSync13("git", args, {
8633
+ const git4 = (...args) => execFileSync18("git", args, {
6131
8634
  cwd: root,
6132
8635
  encoding: "utf8",
6133
8636
  stdio: ["ignore", "pipe", "pipe"],
6134
8637
  timeout: 5e3
6135
8638
  }).trim();
6136
- if (!isWithin(physicalPath(path16.join(this.coordDb.coordDir, "worktrees")), root) || !layout.isLinkedWorktree || layout.checkoutRoot !== root || layout.commonGitDir !== owner.commonGitDir || !agent.branch || git3("symbolic-ref", "--short", "HEAD") !== agent.branch || !this.worktrees.listWorktrees().some((w) => physicalPath(w.path) === root && w.branch === agent.branch) || this.fencing.listAgents(true).some((a) => a.id !== agentId && a.worktree_path && physicalPath(a.worktree_path) === root)) {
8639
+ if (!isWithin(physicalPath(path18.join(this.coordDb.coordDir, "worktrees")), root) || !layout.isLinkedWorktree || layout.checkoutRoot !== root || layout.commonGitDir !== owner.commonGitDir || !agent.branch || git4("symbolic-ref", "--short", "HEAD") !== agent.branch || !this.worktrees.listWorktrees().some((w) => physicalPath(w.path) === root && w.branch === agent.branch) || this.fencing.listAgents(true).some((a) => a.id !== agentId && a.worktree_path && physicalPath(a.worktree_path) === root)) {
6137
8640
  throw new Error("Saved worktree identity or ownership changed; inspect and preserve it before claiming another task.");
6138
8641
  }
6139
- if (git3("status", "--porcelain", "--untracked-files=normal")) {
8642
+ if (git4("status", "--porcelain", "--untracked-files=normal")) {
6140
8643
  throw new Error("Saved worktree has unfinished changes; preserve or finish them before claiming another task.");
6141
8644
  }
6142
- const head = execFileSync13("git", ["rev-parse", "HEAD"], { cwd: this.coordDb.repoRoot, encoding: "utf8" }).trim();
6143
- if (git3("rev-parse", "HEAD") !== head) {
8645
+ const head = execFileSync18("git", ["rev-parse", "HEAD"], { cwd: this.coordDb.repoRoot, encoding: "utf8" }).trim();
8646
+ if (git4("rev-parse", "HEAD") !== head) {
6144
8647
  throw new Error("Saved worktree is ahead or behind the current checkout; integrate or replace it explicitly before claiming another task.");
6145
8648
  }
6146
- return { agentId, worktreePath: root, branch: agent.branch, hydrationMethod: "none", hydratedDirs: [], durationMs: 0 };
8649
+ return {
8650
+ agentId,
8651
+ worktreePath: root,
8652
+ branch: agent.branch,
8653
+ hydrationMethod: "none",
8654
+ hydratedDirs: [],
8655
+ durationMs: 0,
8656
+ provenance: "created",
8657
+ source: "kith",
8658
+ detached: false,
8659
+ dirty: false,
8660
+ branchCheckedOutElsewhere: false,
8661
+ alreadyRegistered: true,
8662
+ notes: []
8663
+ };
6147
8664
  }
6148
8665
  async claimNextTaskWhenAvailable(params) {
6149
8666
  return this.waitForOwnedClaim(params, () => this.claimNextTask(params));
@@ -6167,7 +8684,24 @@ ${kept.join("\n")}` : "";
6167
8684
  completeWork(params) {
6168
8685
  this.fencing.assertSession(params.agentId);
6169
8686
  const agent = this.fencing.getAgent(params.agentId);
6170
- const branch = params.mergeBranch ?? agent?.branch;
8687
+ const adoption = this.worktrees.liveAdoption(agent);
8688
+ if (this.workflowMode() === "main" && adoption) {
8689
+ if (params.verificationCmd) {
8690
+ try {
8691
+ runVerificationCommand(params.verificationCmd, adoption.worktreePath, this.fencing.sessionEnvironment(params.agentId));
8692
+ } catch (err) {
8693
+ return { ok: false, mergeResult: null, error: err instanceof Error ? err.message : String(err) };
8694
+ }
8695
+ }
8696
+ const completedTasks2 = this.intents.completeTask(params);
8697
+ this.fencing.completeAgentSession(params.agentId);
8698
+ this.shadowGit.pruneStaleShadowIndexes();
8699
+ return { ok: true, completedTasks: completedTasks2, mergeResult: null, notes: [ADOPT_MAIN_MODE_NOTE] };
8700
+ }
8701
+ if (adoption?.integrationError) {
8702
+ return { ok: false, mergeResult: null, error: adoption.integrationError };
8703
+ }
8704
+ const branch = params.mergeBranch ?? adoption?.branch ?? agent?.branch;
6171
8705
  const mergeResult = branch ? this.mergeTrain.enqueueAndMerge({
6172
8706
  agentId: params.agentId,
6173
8707
  branch,
@@ -6219,27 +8753,47 @@ export {
6219
8753
  ShadowGitEngine,
6220
8754
  SpeculativeMergeTrain,
6221
8755
  StaleFencingTokenError,
8756
+ adoptIfUnambiguous,
8757
+ adoptWorktree,
8758
+ branchElsewhereError,
8759
+ branchIsCheckedOutElsewhere,
6222
8760
  buildSwarmPrompts,
6223
8761
  caseSensitivePaths,
8762
+ clearRegistration,
6224
8763
  commandTargetsFileForWrite,
6225
8764
  commitScopedFiles,
8765
+ detachedIntegrationError,
6226
8766
  discoverChildRepositories,
6227
8767
  discoverRepository,
6228
8768
  extractRecentAgentFiles,
8769
+ forgetWorktree,
6229
8770
  gcCoordination,
6230
8771
  inspectWorkspaceContracts,
8772
+ isKithOwnedWorktree,
6231
8773
  isReadOnlyShellCommand,
6232
8774
  isWithin,
8775
+ kithWorktreesRoot,
8776
+ listGitWorktrees,
8777
+ listRegistrations,
8778
+ liveAdoption,
6233
8779
  observeWorkspaces,
8780
+ parseWorktreePorcelain,
6234
8781
  physicalPath,
6235
8782
  previewIntegration,
8783
+ primaryCheckoutOf,
6236
8784
  readBrief,
6237
8785
  readCoordinationState,
8786
+ readRegistration,
8787
+ recordCreatedWorktree,
6238
8788
  recoveryReport,
8789
+ refUpdateResyncRoots,
8790
+ registrationFromRow,
6239
8791
  repositoryFile,
6240
8792
  resyncStaleIndexEntries,
6241
8793
  runVerificationCommand,
6242
8794
  sqliteDatabase,
8795
+ syncRegistration,
8796
+ transferWorktreeRegistration,
6243
8797
  verifyCrossRepoImportsForFile,
6244
8798
  worktreeChanges
6245
8799
  };