kith-coord 0.1.8 → 0.1.9

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 execFileSync16 } 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.1.9";
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 fs19 from "fs";
415
+ import path17 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";
@@ -1612,16 +1614,1567 @@ var LockEngine = class _LockEngine {
1612
1614
  return true;
1613
1615
  }
1614
1616
  }
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());
1617
+ listLocks() {
1618
+ this.fencing.reapDeadAgents();
1619
+ return this.coordDb.db.prepare(`SELECT * FROM locks WHERE expires_at > ? ORDER BY acquired_at ASC`).all(Date.now());
1620
+ }
1621
+ };
1622
+
1623
+ // src/core/shared-ref-update.ts
1624
+ import { execFileSync as execFileSync6 } from "child_process";
1625
+ import crypto5 from "crypto";
1626
+ import fs6 from "fs";
1627
+ import path6 from "path";
1628
+
1629
+ // src/core/recorded-files.ts
1630
+ import { execFileSync as execFileSync5 } from "child_process";
1631
+ function listDirtyFiles(rootDir) {
1632
+ try {
1633
+ const out = execFileSync5("git", ["status", "--porcelain", "-z", "--untracked-files=all"], {
1634
+ cwd: rootDir,
1635
+ encoding: "utf8",
1636
+ stdio: ["ignore", "pipe", "ignore"]
1637
+ });
1638
+ const tokens = out.split("\0");
1639
+ const files = [];
1640
+ for (let i = 0; i < tokens.length; i++) {
1641
+ const entry = tokens[i];
1642
+ if (!entry || entry.length < 4) continue;
1643
+ const status = entry.slice(0, 2);
1644
+ const file = entry.slice(3);
1645
+ if (file) files.push(file);
1646
+ if ((status.startsWith("R") || status.startsWith("C")) && i + 1 < tokens.length && tokens[i + 1]) {
1647
+ files.push(tokens[++i]);
1648
+ }
1649
+ }
1650
+ return Array.from(new Set(files));
1651
+ } catch {
1652
+ return [];
1653
+ }
1654
+ }
1655
+ function collectRecordedFiles(params) {
1656
+ const dirtySet = new Set(params.dirtyFiles);
1657
+ const collected = /* @__PURE__ */ new Set();
1658
+ for (const lock of params.locks) {
1659
+ if (!params.callerAgentIds.has(lock.owner_agent_id)) continue;
1660
+ if (lock.lock_type === "file" || !/[?*]/.test(lock.pattern)) {
1661
+ const rel = lock.pattern.startsWith("file:") ? lock.pattern.slice(5) : lock.pattern;
1662
+ if (!rel.startsWith("symbol:")) collected.add(rel);
1663
+ } else if (lock.pattern !== "**") {
1664
+ for (const df of params.dirtyFiles) {
1665
+ if (LockEngine.patternsOverlap(LockEngine.literalScope(df), lock.pattern)) collected.add(df);
1666
+ }
1667
+ }
1668
+ }
1669
+ for (const touched of params.presenceTouched) {
1670
+ try {
1671
+ collected.add(LockEngine.normalizeFile(params.worktreeRoot, touched));
1672
+ } catch {
1673
+ }
1674
+ }
1675
+ for (const task of params.tasks) {
1676
+ if (task.status !== "active" || !task.owner_agent_id || !params.callerAgentIds.has(task.owner_agent_id)) continue;
1677
+ for (const glob of task.scope_globs) {
1678
+ if (glob === "**") continue;
1679
+ for (const df of params.dirtyFiles) {
1680
+ if (LockEngine.patternsOverlap(LockEngine.literalScope(df), glob)) collected.add(df);
1681
+ }
1682
+ }
1683
+ }
1684
+ const candidates = [...collected].filter((f) => dirtySet.has(f));
1685
+ const ignored = candidates.length ? ignoredPaths(params.worktreeRoot, candidates) : /* @__PURE__ */ new Set();
1686
+ return candidates.filter((f) => !ignored.has(f));
1687
+ }
1688
+ function pathRecordedByCaller(params) {
1689
+ const relPath = params.relPath.replace(/\\/g, "/");
1690
+ const requested = LockEngine.literalScope(relPath);
1691
+ for (const lock of params.locks) {
1692
+ if (!params.callerAgentIds.has(lock.owner_agent_id)) continue;
1693
+ if (lock.pattern.startsWith("symbol:")) continue;
1694
+ if (lock.pattern === "**") continue;
1695
+ if (lock.lock_type === "file" || !/[?*]/.test(lock.pattern)) {
1696
+ const rel = lock.pattern.startsWith("file:") ? lock.pattern.slice(5) : lock.pattern;
1697
+ if (rel === relPath) return true;
1698
+ } else if (LockEngine.patternsOverlap(requested, lock.pattern)) {
1699
+ return true;
1700
+ }
1701
+ }
1702
+ for (const touched of params.presenceTouched) {
1703
+ try {
1704
+ if (LockEngine.normalizeFile(params.worktreeRoot, touched) === relPath) return true;
1705
+ } catch {
1706
+ }
1707
+ }
1708
+ for (const task of params.tasks) {
1709
+ if (task.status !== "active" || !task.owner_agent_id || !params.callerAgentIds.has(task.owner_agent_id)) continue;
1710
+ for (const glob of task.scope_globs) {
1711
+ if (glob === "**") continue;
1712
+ if (LockEngine.patternsOverlap(requested, glob)) return true;
1713
+ }
1714
+ }
1715
+ return false;
1716
+ }
1717
+ function peerClaimOnPath(params) {
1718
+ const requested = LockEngine.literalScope(params.relPath.replace(/\\/g, "/"));
1719
+ for (const lock of params.locks) {
1720
+ if (params.callerAgentIds.has(lock.owner_agent_id)) continue;
1721
+ if (LockEngine.patternsOverlap(requested, lock.pattern)) {
1722
+ return { agentId: lock.owner_agent_id, pattern: lock.pattern };
1723
+ }
1724
+ }
1725
+ return null;
1726
+ }
1727
+
1728
+ // src/core/shared-ref-update.ts
1729
+ var LEASE_MS = 3e4;
1730
+ var GIT_PREFIX = String.raw`\bgit(?:\s+(?:-C|-c|--git-dir|--work-tree)(?:=|\s+)(?:"[^"]*"|'[^']*'|[^\s;&|]+)|\s+--(?:no-pager|literal-pathspecs|no-optional-locks))*\s+`;
1731
+ 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`);
1732
+ var DESTRUCTIVE_SHARED_TREE = new RegExp(GIT_PREFIX + String.raw`(?:reset|clean|checkout|restore|switch|stash|merge|rebase|pull|cherry-pick|revert|am)\b`);
1733
+ var SAFE_GIT_GLOBALS = /* @__PURE__ */ new Set([
1734
+ "--no-pager",
1735
+ "-P",
1736
+ "--paginate",
1737
+ "-p",
1738
+ "--literal-pathspecs",
1739
+ "--no-optional-locks",
1740
+ "--no-replace-objects"
1741
+ ]);
1742
+ var CHECKOUT_REWRITE = /* @__PURE__ */ new Set([
1743
+ "reset",
1744
+ "clean",
1745
+ "checkout",
1746
+ "restore",
1747
+ "switch",
1748
+ "stash",
1749
+ "merge",
1750
+ "rebase",
1751
+ "pull",
1752
+ "cherry-pick",
1753
+ "revert",
1754
+ "am",
1755
+ "commit"
1756
+ ]);
1757
+ var SAFE_REV = /^(?!-)[A-Za-z0-9._/^~:@{}-]+$/;
1758
+ function commandMovesSharedCheckout(command) {
1759
+ return DESTRUCTIVE_SHARED_REFS.test(command) || DESTRUCTIVE_SHARED_TREE.test(command) || /\bgit(?:\s+\S+)*?\s+commit(?![\w-])/.test(command);
1760
+ }
1761
+ function firewallReason(suggestion, specific) {
1762
+ const detail = specific ? `${specific.endsWith(".") ? specific : `${specific}.`} ` : "";
1763
+ 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}`;
1764
+ }
1765
+ function suggestKithCommit(host, command) {
1766
+ const message = extractCommitMessage(command) ?? "<message>";
1767
+ let files = [];
1768
+ try {
1769
+ const root = checkoutOf(host).checkout;
1770
+ files = collectRecordedFiles({
1771
+ worktreeRoot: root,
1772
+ callerAgentIds: /* @__PURE__ */ new Set([host.agentId]),
1773
+ locks: host.locks,
1774
+ tasks: host.tasks,
1775
+ presenceTouched: host.presenceTouched,
1776
+ dirtyFiles: listDirtyFiles(root)
1777
+ });
1778
+ } catch {
1779
+ files = [];
1780
+ }
1781
+ const shown = files.slice(0, 20).map(quoteArg);
1782
+ const more = files.length > 20 ? " ..." : "";
1783
+ const filePart = shown.length ? ` ${shown.join(" ")}${more}` : " [files...]";
1784
+ return `kith commit -m ${quoteArg(message)}${filePart}`;
1785
+ }
1786
+ function assessSharedCheckoutUpdate(host, command, startDir) {
1787
+ const place = checkoutOf(host);
1788
+ if (!place.shared) return { action: "skip" };
1789
+ let scan;
1790
+ try {
1791
+ scan = scanCommand(command, startDir);
1792
+ } catch {
1793
+ clearSharedRefLease(host.coordDir, host.agentId);
1794
+ return block(host, command, "The ref command could not be parsed.");
1795
+ }
1796
+ if (!scan.sawUpdateRef) {
1797
+ clearSharedRefLease(host.coordDir, host.agentId);
1798
+ return { action: "skip" };
1799
+ }
1800
+ if (scan.updates.length > 1) scan.failure = scan.failure ?? "Multiple update-ref commands cannot be verified together.";
1801
+ if (scan.updates.length >= 1 && (scan.checkoutRewrite || scan.otherRefWrite)) {
1802
+ scan.failure = scan.failure ?? "The command mixes update-ref with another ref or checkout rewrite.";
1803
+ }
1804
+ if (scan.failure || scan.updates.length !== 1) {
1805
+ clearSharedRefLease(host.coordDir, host.agentId);
1806
+ return block(host, command, scan.failure ?? "The update-ref command could not be verified.");
1807
+ }
1808
+ const verdict = verifyCandidate(host, place.checkout, scan.updates[0]);
1809
+ if (!verdict.ok) {
1810
+ clearSharedRefLease(host.coordDir, host.agentId);
1811
+ return block(host, command, verdict.reason);
1812
+ }
1813
+ if (verdict.defer) {
1814
+ writeLease(host, {
1815
+ agentId: host.agentId,
1816
+ command,
1817
+ createdAt: Date.now(),
1818
+ expiresAt: Date.now() + LEASE_MS,
1819
+ updates: [{ dir: verdict.dir, ref: verdict.ref, old: verdict.old, noDeref: verdict.noDeref }]
1820
+ });
1821
+ return { action: "defer" };
1822
+ }
1823
+ clearSharedRefLease(host.coordDir, host.agentId);
1824
+ return { action: "allow" };
1825
+ }
1826
+ function casCommandDirectories(command, startDir) {
1827
+ try {
1828
+ const scan = scanCommand(command, startDir);
1829
+ if (scan.failure || scan.checkoutRewrite || scan.otherRefWrite || scan.updates.length !== 1) return [];
1830
+ return [scan.updates[0].dir];
1831
+ } catch {
1832
+ return [];
1833
+ }
1834
+ }
1835
+ function settleDeferredRefUpdate(host, command) {
1836
+ const pending = readLease(host.coordDir, host.agentId);
1837
+ if (!pending || pending.command !== command) return { warnings: [], reverted: false };
1838
+ clearSharedRefLease(host.coordDir, host.agentId);
1839
+ const warnings = [];
1840
+ let reverted = false;
1841
+ const suggestion = suggestKithCommit(host, command);
1842
+ for (const update of pending.updates) {
1843
+ if (!isSafeHeadRef(update.ref) || !isFullSha(update.old)) {
1844
+ warnings.push(`[KITH BASH FIREWALL] Dropped an unreadable shared-checkout update record for ${host.agentId}.`);
1845
+ continue;
1846
+ }
1847
+ const current = readCommitRef(update.dir, update.ref);
1848
+ if (!current) {
1849
+ 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}`);
1850
+ continue;
1851
+ }
1852
+ if (current === update.old) continue;
1853
+ const verdict = verifyFastForward(host, update.dir, current, update.old);
1854
+ if (verdict.ok) continue;
1855
+ const didRevert = revertRef(update, current);
1856
+ reverted = reverted || didRevert;
1857
+ 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`;
1858
+ warnings.push(`[KITH BASH FIREWALL] ${action}: ${verdict.reason} To commit only your own files safely while peers are active, run: ${suggestion}`);
1859
+ host.logEvent?.(host.agentId, didRevert ? "shared_ref_update_reverted" : "shared_ref_update_revert_failed", {
1860
+ ref: update.ref,
1861
+ from: current,
1862
+ to: update.old,
1863
+ reason: verdict.reason
1864
+ });
1865
+ }
1866
+ return { warnings, reverted };
1867
+ }
1868
+ function foreignRefLease(coordDir, agentId) {
1869
+ for (const pending of listLeases(coordDir)) {
1870
+ if (pending.agentId !== agentId) return { agentId: pending.agentId };
1871
+ }
1872
+ return null;
1873
+ }
1874
+ function waitForSharedRefLease(coordDir, agentId, timeoutMs = 15e3) {
1875
+ const started = Date.now();
1876
+ while (true) {
1877
+ const foreign = foreignRefLease(coordDir, agentId ?? "");
1878
+ if (!foreign) return null;
1879
+ if (Date.now() - started >= timeoutMs) {
1880
+ return `Timed out waiting for agent ${foreign.agentId} to finish verifying a shared-checkout commit. Retry shortly.`;
1881
+ }
1882
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40);
1883
+ }
1884
+ }
1885
+ function clearSharedRefLease(coordDir, agentId) {
1886
+ try {
1887
+ fs6.unlinkSync(leasePath(coordDir, agentId));
1888
+ } catch {
1889
+ }
1890
+ }
1891
+ function block(host, command, specific) {
1892
+ return { action: "block", reason: firewallReason(suggestKithCommit(host, command), specific) };
1893
+ }
1894
+ function checkoutOf(host) {
1895
+ let checkout = host.repoRoot;
1896
+ try {
1897
+ checkout = physicalPath(host.agent?.worktree_path ?? host.repoRoot);
1898
+ } catch {
1899
+ return { shared: false, checkout: host.repoRoot };
1900
+ }
1901
+ if (!host.agent?.worktree_path) return { shared: true, checkout };
1902
+ const main = mainCheckout(checkout);
1903
+ if (!main) return { shared: false, checkout };
1904
+ return { shared: main.path === checkout, checkout };
1905
+ }
1906
+ function verifyCandidate(host, checkout, update) {
1907
+ if (!directoryInside(update.dir, checkout)) {
1908
+ return { ok: false, reason: "update-ref runs outside this shared checkout" };
1909
+ }
1910
+ if (!isSafeHeadRef(update.ref)) return { ok: false, reason: "The ref must be a literal HEAD or refs/heads/<current branch>." };
1911
+ const checked = checkedOutBranch(update.dir);
1912
+ if (!checked.ok) return { ok: false, reason: "The current branch could not be read." };
1913
+ const currentBranch = checked.branch ? `refs/heads/${checked.branch}` : null;
1914
+ if (update.ref !== "HEAD" && update.ref !== currentBranch) {
1915
+ return { ok: false, reason: `Ref ${update.ref} is not HEAD or the current branch${currentBranch ? ` (${currentBranch})` : ""}.` };
1916
+ }
1917
+ if (update.noDeref && symbolicRef(update.dir, update.ref)) {
1918
+ return { ok: false, reason: "--no-deref would update the symbolic ref itself instead of fast-forwarding the branch." };
1919
+ }
1920
+ const current = readCommitRef(update.dir, update.ref);
1921
+ if (!current) return { ok: false, reason: `The current value of ${update.ref} could not be read.` };
1922
+ if (!update.oldWord.expansion) {
1923
+ const old = resolveCommit(update.dir, update.oldWord.text);
1924
+ if (!old.ok) return { ok: false, reason: `Compare-and-swap old value ${old.reason}` };
1925
+ if (old.sha !== current) {
1926
+ return { ok: false, reason: `Compare-and-swap old value ${short(old.sha)} does not equal current ${update.ref} (${short(current)}).` };
1927
+ }
1928
+ }
1929
+ if (!update.newWord.expansion) {
1930
+ const created = resolveCommit(update.dir, update.newWord.text);
1931
+ if (!created.ok) return { ok: false, reason: `New value ${created.reason}` };
1932
+ const ff = verifyFastForward(host, checkout, created.sha, current);
1933
+ if (!ff.ok) return ff;
1934
+ if (update.oldWord.expansion) {
1935
+ return { ok: true, defer: true, dir: update.dir, ref: update.ref, old: current, noDeref: update.noDeref };
1936
+ }
1937
+ return { ok: true, defer: false };
1938
+ }
1939
+ return { ok: true, defer: true, dir: update.dir, ref: update.ref, old: current, noDeref: update.noDeref };
1940
+ }
1941
+ function verifyFastForward(host, checkout, newSha, oldSha) {
1942
+ const parents = commitParents(checkout, newSha);
1943
+ if (!parents) return { ok: false, reason: "The new commit could not be read." };
1944
+ if (parents.length === 0) return { ok: false, reason: "New commit has no parent (not a one-commit fast-forward)." };
1945
+ if (parents.length > 1) {
1946
+ return { ok: false, reason: `New commit is a merge (${parents.length} parents); only a one-commit fast-forward is allowed.` };
1947
+ }
1948
+ if (parents[0] !== oldSha) {
1949
+ return { ok: false, reason: `New commit parent ${short(parents[0])} is not ${short(oldSha)} (not a one-commit fast-forward).` };
1950
+ }
1951
+ const paths = changedPaths(checkout, oldSha, newSha);
1952
+ if (!paths) return { ok: false, reason: "The commit diff could not be read." };
1953
+ const caller = /* @__PURE__ */ new Set([host.agentId]);
1954
+ const problems = [];
1955
+ for (const rel of paths) {
1956
+ const peer = peerClaimOnPath({ relPath: rel, callerAgentIds: caller, locks: host.locks });
1957
+ if (peer) {
1958
+ problems.push(`path ${rel} is claimed by agent ${peer.agentId}`);
1959
+ continue;
1960
+ }
1961
+ if (!pathRecordedByCaller({
1962
+ worktreeRoot: checkout,
1963
+ relPath: rel,
1964
+ callerAgentIds: caller,
1965
+ locks: host.locks,
1966
+ tasks: host.tasks,
1967
+ presenceTouched: host.presenceTouched
1968
+ })) {
1969
+ problems.push(`path ${rel} is not claimed, locked, or recorded by this session`);
1970
+ }
1971
+ }
1972
+ if (problems.length === 0) return { ok: true };
1973
+ const shown = problems.slice(0, 5).join("; ");
1974
+ const more = problems.length > 5 ? `; and ${problems.length - 5} more` : "";
1975
+ return { ok: false, reason: `${shown}${more}` };
1976
+ }
1977
+ function resolveCommit(dir, rev) {
1978
+ if (!isSafeRev(rev)) return { ok: false, reason: "is not a literal commit." };
1979
+ const type = git2(dir, ["cat-file", "-t", "--end-of-options", rev]);
1980
+ if (type !== "commit") {
1981
+ return { ok: false, reason: type ? `resolves to a ${type}, not a commit.` : "does not resolve to a commit." };
1982
+ }
1983
+ const sha = git2(dir, ["rev-parse", "--verify", "--end-of-options", `${rev}^{commit}`]);
1984
+ if (!sha || !isFullSha(sha)) return { ok: false, reason: "does not resolve to a commit." };
1985
+ return { ok: true, sha };
1986
+ }
1987
+ function commitParents(dir, sha) {
1988
+ if (!isFullSha(sha)) return null;
1989
+ const text = gitRaw(dir, ["cat-file", "-p", "--end-of-options", sha]);
1990
+ if (text === null) return null;
1991
+ const parents = [];
1992
+ for (const line of text.split("\n")) {
1993
+ if (line === "") break;
1994
+ if (!line.startsWith("parent ")) continue;
1995
+ const parent = line.slice("parent ".length).trim();
1996
+ if (!isFullSha(parent)) return null;
1997
+ parents.push(parent);
1998
+ }
1999
+ return parents;
2000
+ }
2001
+ function changedPaths(dir, oldSha, newSha) {
2002
+ if (!isFullSha(oldSha) || !isFullSha(newSha)) return null;
2003
+ const out = gitRaw(dir, [
2004
+ "diff-tree",
2005
+ "-r",
2006
+ "-z",
2007
+ "--name-only",
2008
+ "--no-renames",
2009
+ "--end-of-options",
2010
+ oldSha,
2011
+ newSha
2012
+ ]);
2013
+ if (out === null) return null;
2014
+ return [...new Set(out.split("\0").filter(Boolean).map((entry) => entry.replace(/\\/g, "/")))];
2015
+ }
2016
+ function revertRef(update, current) {
2017
+ if (!isSafeHeadRef(update.ref) || !isFullSha(update.old) || !isFullSha(current)) return false;
2018
+ const args = ["update-ref"];
2019
+ if (update.noDeref) args.push("--no-deref");
2020
+ args.push("-m", "kith: revert shared-checkout update that failed ownership checks", update.ref, update.old, current);
2021
+ try {
2022
+ execFileSync6("git", args, { cwd: update.dir, stdio: ["ignore", "pipe", "pipe"], timeout: 5e3 });
2023
+ return true;
2024
+ } catch {
2025
+ return false;
2026
+ }
2027
+ }
2028
+ function readCommitRef(dir, ref) {
2029
+ if (!isSafeHeadRef(ref)) return null;
2030
+ const sha = git2(dir, ["rev-parse", "--verify", "--end-of-options", ref]);
2031
+ return sha && isFullSha(sha) ? sha : null;
2032
+ }
2033
+ function symbolicRef(dir, ref) {
2034
+ if (!isSafeHeadRef(ref)) return null;
2035
+ const value = git2(dir, ["symbolic-ref", "-q", "--end-of-options", ref]);
2036
+ return value || null;
2037
+ }
2038
+ function checkedOutBranch(dir) {
2039
+ try {
2040
+ const out = execFileSync6("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
2041
+ cwd: dir,
2042
+ encoding: "utf8",
2043
+ stdio: ["ignore", "pipe", "ignore"],
2044
+ timeout: 5e3
2045
+ }).trim();
2046
+ return { ok: true, branch: out || null };
2047
+ } catch (error) {
2048
+ if (error.status === 1) return { ok: true, branch: null };
2049
+ return { ok: false };
2050
+ }
2051
+ }
2052
+ function mainCheckout(cwd) {
2053
+ let out;
2054
+ try {
2055
+ out = execFileSync6("git", ["worktree", "list", "--porcelain"], {
2056
+ cwd,
2057
+ encoding: "utf8",
2058
+ stdio: ["ignore", "pipe", "ignore"],
2059
+ timeout: 5e3
2060
+ });
2061
+ } catch {
2062
+ return null;
2063
+ }
2064
+ const first = out.split(/\n\s*\n/)[0] ?? "";
2065
+ let wt = null;
2066
+ let branch = null;
2067
+ let detached = false;
2068
+ for (const line of first.split("\n")) {
2069
+ if (line.startsWith("worktree ")) wt = line.slice("worktree ".length).trim();
2070
+ else if (line.startsWith("branch ")) branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
2071
+ else if (line === "detached" || line.startsWith("detached ")) detached = true;
2072
+ }
2073
+ if (!wt) return null;
2074
+ try {
2075
+ return { path: physicalPath(wt), branch: detached ? null : branch };
2076
+ } catch {
2077
+ return null;
2078
+ }
2079
+ }
2080
+ function directoryInside(dir, root) {
2081
+ try {
2082
+ const resolved = physicalPath(dir);
2083
+ const base = physicalPath(root);
2084
+ return resolved === base || isWithin(base, resolved);
2085
+ } catch {
2086
+ return false;
2087
+ }
2088
+ }
2089
+ function git2(dir, args) {
2090
+ const out = gitRaw(dir, args);
2091
+ return out === null ? null : out.trim();
2092
+ }
2093
+ function gitRaw(dir, args) {
2094
+ try {
2095
+ return execFileSync6("git", args, {
2096
+ cwd: dir,
2097
+ encoding: "utf8",
2098
+ stdio: ["ignore", "pipe", "ignore"],
2099
+ timeout: 5e3,
2100
+ maxBuffer: 8 * 1024 * 1024
2101
+ });
2102
+ } catch {
2103
+ return null;
2104
+ }
2105
+ }
2106
+ function isFullSha(value) {
2107
+ return /^[0-9a-f]{40}$/.test(value);
2108
+ }
2109
+ function isSafeRev(rev) {
2110
+ return rev.length > 0 && rev.length < 200 && SAFE_REV.test(rev) && !rev.includes("..");
2111
+ }
2112
+ function isSafeHeadRef(ref) {
2113
+ if (ref === "HEAD") return true;
2114
+ if (!ref.startsWith("refs/heads/")) return false;
2115
+ const name = ref.slice("refs/heads/".length);
2116
+ if (!name || name.startsWith("/") || name.endsWith("/") || name.includes("..") || name.includes("@{")) return false;
2117
+ return /^[A-Za-z0-9._/-]+$/.test(name);
2118
+ }
2119
+ function short(sha) {
2120
+ return sha.length > 12 ? sha.slice(0, 12) : sha;
2121
+ }
2122
+ function leasePath(coordDir, agentId) {
2123
+ const name = crypto5.createHash("sha256").update(agentId).digest("hex") + ".json";
2124
+ return path6.join(coordDir, "ref-guards", name);
2125
+ }
2126
+ function writeLease(host, pending) {
2127
+ const dir = path6.join(host.coordDir, "ref-guards");
2128
+ fs6.mkdirSync(dir, { recursive: true, mode: 448 });
2129
+ const target = leasePath(host.coordDir, host.agentId);
2130
+ const tmp = `${target}.${process.pid}.tmp`;
2131
+ fs6.writeFileSync(tmp, JSON.stringify(pending), { mode: 384 });
2132
+ fs6.renameSync(tmp, target);
2133
+ }
2134
+ function readLease(coordDir, agentId) {
2135
+ return listLeases(coordDir).find((pending) => pending.agentId === agentId) ?? null;
2136
+ }
2137
+ function listLeases(coordDir) {
2138
+ const dir = path6.join(coordDir, "ref-guards");
2139
+ let names = [];
2140
+ try {
2141
+ names = fs6.readdirSync(dir);
2142
+ } catch {
2143
+ return [];
2144
+ }
2145
+ const now = Date.now();
2146
+ const pending = [];
2147
+ for (const name of names) {
2148
+ if (!name.endsWith(".json")) continue;
2149
+ const file = path6.join(dir, name);
2150
+ let parsed = null;
2151
+ try {
2152
+ parsed = JSON.parse(fs6.readFileSync(file, "utf8"));
2153
+ } catch {
2154
+ parsed = null;
2155
+ }
2156
+ if (!parsed || typeof parsed.agentId !== "string" || !Array.isArray(parsed.updates) || typeof parsed.expiresAt !== "number") {
2157
+ try {
2158
+ fs6.unlinkSync(file);
2159
+ } catch {
2160
+ }
2161
+ continue;
2162
+ }
2163
+ if (parsed.expiresAt <= now) {
2164
+ try {
2165
+ fs6.unlinkSync(file);
2166
+ } catch {
2167
+ }
2168
+ continue;
2169
+ }
2170
+ pending.push(parsed);
2171
+ }
2172
+ return pending;
2173
+ }
2174
+ function extractCommitMessage(command) {
2175
+ const fromTree = flagMessage(command, "commit-tree");
2176
+ if (fromTree) return subject(fromTree);
2177
+ const fromRef = flagMessage(command, "update-ref");
2178
+ if (!fromRef) return null;
2179
+ return subject(fromRef.replace(/^commit:\s*/, ""));
2180
+ }
2181
+ function flagMessage(command, subcommand) {
2182
+ const re = new RegExp(String.raw`\b${subcommand}\b[\s\S]{0,500}?(?:-m|--message)(?:=|\s+)(?:'([^']*)'|"([^"]*)"|(\S+))`);
2183
+ const match = re.exec(command);
2184
+ const text = match?.[1] ?? match?.[2] ?? match?.[3];
2185
+ const trimmed = text?.trim();
2186
+ return trimmed ? trimmed : null;
2187
+ }
2188
+ function subject(message) {
2189
+ const line = message.split(/\r?\n/, 1)[0]?.trim() ?? "";
2190
+ if (!line) return null;
2191
+ return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;
2192
+ }
2193
+ function quoteArg(value) {
2194
+ if (/^[A-Za-z0-9._@/:+=,-]+$/.test(value)) return value;
2195
+ if (!/["\\$`]/.test(value)) return `"${value}"`;
2196
+ return `'${value.replaceAll("'", `'\\''`)}'`;
2197
+ }
2198
+ function scanCommand(command, startDir) {
2199
+ const scan = { sawUpdateRef: false, updates: [], failure: null, checkoutRewrite: false, otherRefWrite: false };
2200
+ const segments = splitShellSegments(command);
2201
+ if (!segments) {
2202
+ scan.sawUpdateRef = /\bupdate-ref\b/.test(command);
2203
+ scan.failure = "The ref command could not be parsed.";
2204
+ return scan;
2205
+ }
2206
+ let cwd = path6.resolve(startDir);
2207
+ let untrusted = false;
2208
+ for (const segment of segments) {
2209
+ const matched = DESTRUCTIVE_SHARED_REFS.test(segment.raw);
2210
+ const sawRef = /\bupdate-ref\b/.test(segment.raw);
2211
+ if (sawRef) scan.sawUpdateRef = true;
2212
+ const words = tokenizeShell(segment.raw);
2213
+ if (!words) {
2214
+ if (matched || sawRef) scan.failure = scan.failure ?? "The ref command could not be parsed.";
2215
+ if (continuesShell(segment.nextSep) && /\b(?:cd|pushd|popd|export|source)\b|\bGIT_DIR\b/.test(segment.raw)) untrusted = true;
2216
+ continue;
2217
+ }
2218
+ const { danger, argv } = stripLeadingEnv(words);
2219
+ if (argv.length === 0) continue;
2220
+ const head = argv[0];
2221
+ if (!head.expansion && head.text === "cd") {
2222
+ const next = applyCd(argv, cwd);
2223
+ if (next && continuesShell(segment.nextSep)) cwd = next;
2224
+ else if (!next && continuesShell(segment.nextSep)) untrusted = true;
2225
+ continue;
2226
+ }
2227
+ if (!head.expansion && (head.text === "pushd" || head.text === "popd" || head.text === "source" || head.text === "." && argv.length > 1)) {
2228
+ if (continuesShell(segment.nextSep)) untrusted = true;
2229
+ continue;
2230
+ }
2231
+ if (!head.expansion && head.text === "export") {
2232
+ if (argv.slice(1).some((arg) => dangerousGitEnv(assignmentName(arg) ?? arg.text))) untrusted = true;
2233
+ continue;
2234
+ }
2235
+ if (head.expansion || !isGitBinary(head.text) || danger || untrusted) {
2236
+ if (matched || sawRef) {
2237
+ 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.");
2238
+ }
2239
+ continue;
2240
+ }
2241
+ const parsed = parseLooseGit(argv, cwd);
2242
+ if (parsed.kind === "unclassified") {
2243
+ if (matched || sawRef) scan.failure = scan.failure ?? "The ref command could not be classified.";
2244
+ continue;
2245
+ }
2246
+ if (parsed.sub === "update-ref") {
2247
+ scan.sawUpdateRef = true;
2248
+ const cas = parseCas(parsed.dir, parsed.args);
2249
+ if (cas.failure) scan.failure = scan.failure ?? cas.failure;
2250
+ if (cas.update) scan.updates.push(cas.update);
2251
+ continue;
2252
+ }
2253
+ if (parsed.sub === "symbolic-ref") {
2254
+ const kind = classifySymbolic(parsed.args);
2255
+ if (kind !== "read") scan.otherRefWrite = true;
2256
+ continue;
2257
+ }
2258
+ if (parsed.sub === "worktree" && matched) {
2259
+ scan.otherRefWrite = true;
2260
+ continue;
2261
+ }
2262
+ if (parsed.sub === "branch" && matched) {
2263
+ scan.otherRefWrite = true;
2264
+ continue;
2265
+ }
2266
+ if (CHECKOUT_REWRITE.has(parsed.sub)) scan.checkoutRewrite = true;
2267
+ }
2268
+ return scan;
2269
+ }
2270
+ function parseCas(dir, args) {
2271
+ let noDeref = false;
2272
+ let deleteRef = false;
2273
+ let stdin = false;
2274
+ let end = false;
2275
+ const positionals = [];
2276
+ for (let i = 0; i < args.length; i++) {
2277
+ const word = args[i];
2278
+ if (!end && !word.expansion && word.text === "--") {
2279
+ end = true;
2280
+ continue;
2281
+ }
2282
+ if (!end && !word.expansion && word.text.startsWith("-")) {
2283
+ const arg = word.text;
2284
+ if (arg === "--no-deref") {
2285
+ noDeref = true;
2286
+ continue;
2287
+ }
2288
+ if (arg === "--deref") {
2289
+ noDeref = false;
2290
+ continue;
2291
+ }
2292
+ if (arg === "--create-reflog" || arg === "--no-create-reflog" || arg === "--no-stdin") continue;
2293
+ if (arg === "--stdin" || arg === "-z") {
2294
+ stdin = true;
2295
+ continue;
2296
+ }
2297
+ if (arg === "-d" || arg === "--delete") {
2298
+ deleteRef = true;
2299
+ continue;
2300
+ }
2301
+ if (arg === "-m" || arg === "--message") {
2302
+ if (args[i + 1] === void 0) return { failure: "update-ref -m is missing its message." };
2303
+ i++;
2304
+ continue;
2305
+ }
2306
+ if (arg.startsWith("-m") && arg.length > 2 || arg.startsWith("--message=")) continue;
2307
+ return { failure: `Unrecognized update-ref option '${arg}'.` };
2308
+ }
2309
+ positionals.push(word);
2310
+ }
2311
+ if (stdin) return { failure: "update-ref --stdin batches cannot be verified before they run." };
2312
+ if (deleteRef) return { failure: "Deleting a ref is not a one-commit fast-forward." };
2313
+ if (positionals.length === 2) return { failure: "No compare-and-swap old value." };
2314
+ if (positionals.length !== 3 || !positionals[0]) return { failure: "update-ref is missing a ref or value." };
2315
+ const ref = positionals[0];
2316
+ if (ref.expansion || !ref.text) return { failure: "The ref must be a literal HEAD or refs/heads/<current branch>." };
2317
+ return {
2318
+ update: { dir, ref: ref.text, noDeref, newWord: positionals[1], oldWord: positionals[2] }
2319
+ };
2320
+ }
2321
+ function classifySymbolic(args) {
2322
+ let deleteRef = false;
2323
+ let end = false;
2324
+ const positionals = [];
2325
+ for (let i = 0; i < args.length; i++) {
2326
+ const word = args[i];
2327
+ if (!end && !word.expansion && word.text === "--") {
2328
+ end = true;
2329
+ continue;
2330
+ }
2331
+ if (!end && !word.expansion && word.text.startsWith("-")) {
2332
+ const arg = word.text;
2333
+ if (arg === "-q" || arg === "--quiet" || arg === "--no-quiet" || arg === "--short" || arg === "--no-short") continue;
2334
+ if (arg === "--recurse" || arg === "--no-recurse") continue;
2335
+ if (arg === "-d" || arg === "--delete") {
2336
+ deleteRef = true;
2337
+ continue;
2338
+ }
2339
+ if (arg === "--no-delete") {
2340
+ deleteRef = false;
2341
+ continue;
2342
+ }
2343
+ if (arg === "-m" || arg === "--message") {
2344
+ if (args[i + 1] === void 0) return "unknown";
2345
+ i++;
2346
+ continue;
2347
+ }
2348
+ if (arg.startsWith("-m") && arg.length > 2 || arg.startsWith("--message=")) continue;
2349
+ return "unknown";
2350
+ }
2351
+ if (word.expansion) return "unknown";
2352
+ positionals.push(word);
2353
+ }
2354
+ if (deleteRef) return positionals.length === 1 ? "write" : "unknown";
2355
+ if (positionals.length === 1) return "read";
2356
+ if (positionals.length === 2) return "write";
2357
+ return "unknown";
2358
+ }
2359
+ function parseLooseGit(argv, cwd) {
2360
+ let i = 1;
2361
+ let dir = cwd;
2362
+ while (i < argv.length) {
2363
+ const token = argv[i];
2364
+ if (token.expansion) return { kind: "unclassified" };
2365
+ const text = token.text;
2366
+ if (text === "--") {
2367
+ i++;
2368
+ break;
2369
+ }
2370
+ if (text === "-C") {
2371
+ const next = argv[i + 1];
2372
+ if (!next || next.expansion || next.text.startsWith("~")) return { kind: "unclassified" };
2373
+ if (next.text !== "") dir = path6.isAbsolute(next.text) ? next.text : path6.resolve(dir, next.text);
2374
+ i += 2;
2375
+ continue;
2376
+ }
2377
+ if (text.startsWith("-C") && text.length > 2) {
2378
+ const next = text.slice(2);
2379
+ if (next.startsWith("~")) return { kind: "unclassified" };
2380
+ dir = path6.isAbsolute(next) ? next : path6.resolve(dir, next);
2381
+ i++;
2382
+ continue;
2383
+ }
2384
+ if (SAFE_GIT_GLOBALS.has(text)) {
2385
+ i++;
2386
+ continue;
2387
+ }
2388
+ if (text.startsWith("-")) return { kind: "unclassified" };
2389
+ break;
2390
+ }
2391
+ const sub = argv[i];
2392
+ if (!sub || sub.expansion) return { kind: "unclassified" };
2393
+ return { kind: "git", dir, sub: sub.text, args: argv.slice(i + 1) };
2394
+ }
2395
+ function stripLeadingEnv(words) {
2396
+ let i = 0;
2397
+ let danger = false;
2398
+ while (i < words.length) {
2399
+ const name = assignmentName(words[i]);
2400
+ if (!name) break;
2401
+ if (dangerousGitEnv(name)) danger = true;
2402
+ i++;
2403
+ }
2404
+ return { danger, argv: words.slice(i) };
2405
+ }
2406
+ function assignmentName(word) {
2407
+ const eq = word.text.indexOf("=");
2408
+ if (eq <= 0) return null;
2409
+ const name = word.text.slice(0, eq);
2410
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : null;
2411
+ }
2412
+ function dangerousGitEnv(name) {
2413
+ 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);
2414
+ }
2415
+ function applyCd(argv, cwd) {
2416
+ let args = argv.slice(1);
2417
+ if (args[0] && !args[0].expansion && args[0].text === "--") args = args.slice(1);
2418
+ if (args.length !== 1 || !args[0] || args[0].expansion) return null;
2419
+ const target = args[0].text;
2420
+ if (target === "-" || target.startsWith("-") || target.startsWith("~")) return null;
2421
+ return path6.resolve(cwd, target);
2422
+ }
2423
+ function isGitBinary(word) {
2424
+ const base = word.slice(Math.max(word.lastIndexOf("/"), word.lastIndexOf("\\")) + 1);
2425
+ return base === "git" || base.toLowerCase() === "git.exe";
2426
+ }
2427
+ function continuesShell(sep) {
2428
+ return sep === "&&" || sep === ";" || sep === "\n";
2429
+ }
2430
+ function splitShellSegments(command) {
2431
+ const parts = [];
2432
+ let buf = "";
2433
+ let quote = null;
2434
+ const push = (sep) => {
2435
+ const raw = buf.trim();
2436
+ buf = "";
2437
+ if (raw) parts.push({ raw, nextSep: sep });
2438
+ };
2439
+ for (let i = 0; i < command.length; i++) {
2440
+ const ch = command[i];
2441
+ if (quote === "'") {
2442
+ buf += ch;
2443
+ if (ch === "'") quote = null;
2444
+ continue;
2445
+ }
2446
+ if (quote === '"') {
2447
+ if (ch === "\\" && i + 1 < command.length) {
2448
+ const next = command[i + 1];
2449
+ if (next === "$" || next === "`" || next === '"' || next === "\\" || next === "\n") {
2450
+ buf += ch + next;
2451
+ i++;
2452
+ continue;
2453
+ }
2454
+ }
2455
+ buf += ch;
2456
+ if (ch === '"') quote = null;
2457
+ continue;
2458
+ }
2459
+ if (ch === "\\" && i + 1 < command.length) {
2460
+ if (command[i + 1] === "\n") {
2461
+ i++;
2462
+ continue;
2463
+ }
2464
+ buf += ch + command[i + 1];
2465
+ i++;
2466
+ continue;
2467
+ }
2468
+ if (ch === "'" || ch === '"') {
2469
+ quote = ch;
2470
+ buf += ch;
2471
+ continue;
2472
+ }
2473
+ if (ch === "&" && command[i + 1] === "&") {
2474
+ push("&&");
2475
+ i++;
2476
+ continue;
2477
+ }
2478
+ if (ch === "|" && command[i + 1] === "|") {
2479
+ push("||");
2480
+ i++;
2481
+ continue;
2482
+ }
2483
+ if (ch === "\r" && command[i + 1] === "\n") {
2484
+ push("\n");
2485
+ i++;
2486
+ continue;
2487
+ }
2488
+ if (ch === "\n") {
2489
+ push("\n");
2490
+ continue;
2491
+ }
2492
+ if (ch === ";") {
2493
+ push(";");
2494
+ continue;
2495
+ }
2496
+ if (ch === "|") {
2497
+ push("|");
2498
+ continue;
2499
+ }
2500
+ if (ch === "&") {
2501
+ push("&");
2502
+ continue;
2503
+ }
2504
+ buf += ch;
2505
+ }
2506
+ if (quote) return null;
2507
+ push("end");
2508
+ return parts;
2509
+ }
2510
+ function tokenizeShell(segment) {
2511
+ const words = [];
2512
+ let buf = "";
2513
+ let expansion = false;
2514
+ let quote = null;
2515
+ let word = false;
2516
+ const flush = () => {
2517
+ if (word) words.push({ text: buf, expansion });
2518
+ buf = "";
2519
+ expansion = false;
2520
+ word = false;
2521
+ };
2522
+ const mark = (text) => {
2523
+ buf += text;
2524
+ word = true;
2525
+ expansion = true;
2526
+ };
2527
+ for (let i = 0; i < segment.length; i++) {
2528
+ const ch = segment[i];
2529
+ if (quote === "'") {
2530
+ if (ch === "'") quote = null;
2531
+ else {
2532
+ buf += ch;
2533
+ word = true;
2534
+ }
2535
+ continue;
2536
+ }
2537
+ if (quote === '"') {
2538
+ if (ch === "\\" && i + 1 < segment.length) {
2539
+ const next = segment[i + 1];
2540
+ if ('$`"\\'.includes(next)) {
2541
+ buf += next;
2542
+ word = true;
2543
+ i++;
2544
+ continue;
2545
+ }
2546
+ if (next === "\n") {
2547
+ i++;
2548
+ continue;
2549
+ }
2550
+ }
2551
+ if (ch === '"') {
2552
+ quote = null;
2553
+ word = true;
2554
+ continue;
2555
+ }
2556
+ if (ch === "`") {
2557
+ const end = segment.indexOf("`", i + 1);
2558
+ if (end < 0) return null;
2559
+ mark(segment.slice(i, end + 1));
2560
+ i = end;
2561
+ continue;
2562
+ }
2563
+ if (ch === "$") {
2564
+ const consumed = consumeExpansion(segment, i);
2565
+ if (!consumed) return null;
2566
+ mark(consumed.text);
2567
+ i = consumed.end - 1;
2568
+ continue;
2569
+ }
2570
+ buf += ch;
2571
+ word = true;
2572
+ continue;
2573
+ }
2574
+ if (ch === "\\" && i + 1 < segment.length) {
2575
+ buf += segment[i + 1];
2576
+ word = true;
2577
+ i++;
2578
+ continue;
2579
+ }
2580
+ if (ch === "'" || ch === '"') {
2581
+ quote = ch;
2582
+ word = true;
2583
+ continue;
2584
+ }
2585
+ if (ch === "`") {
2586
+ const end = segment.indexOf("`", i + 1);
2587
+ if (end < 0) return null;
2588
+ mark(segment.slice(i, end + 1));
2589
+ i = end;
2590
+ continue;
2591
+ }
2592
+ if (ch === "$") {
2593
+ const consumed = consumeExpansion(segment, i);
2594
+ if (!consumed) return null;
2595
+ mark(consumed.text);
2596
+ i = consumed.end - 1;
2597
+ continue;
2598
+ }
2599
+ if (ch === "(" || ch === ")" || ch === "<" || ch === ">") return null;
2600
+ if (ch === "#" && !word) break;
2601
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
2602
+ flush();
2603
+ continue;
2604
+ }
2605
+ buf += ch;
2606
+ word = true;
2607
+ }
2608
+ if (quote) return null;
2609
+ flush();
2610
+ return words;
2611
+ }
2612
+ function consumeExpansion(segment, i) {
2613
+ const next = segment[i + 1];
2614
+ if (next === "(") {
2615
+ let depth = 1;
2616
+ let quoted = null;
2617
+ for (let j = i + 2; j < segment.length; j++) {
2618
+ const ch = segment[j];
2619
+ if (quoted === "'") {
2620
+ if (ch === "'") quoted = null;
2621
+ continue;
2622
+ }
2623
+ if (quoted === '"') {
2624
+ if (ch === "\\" && j + 1 < segment.length) {
2625
+ j++;
2626
+ continue;
2627
+ }
2628
+ if (ch === '"') quoted = null;
2629
+ continue;
2630
+ }
2631
+ if (ch === "\\") {
2632
+ j++;
2633
+ continue;
2634
+ }
2635
+ if (ch === "'" || ch === '"') {
2636
+ quoted = ch;
2637
+ continue;
2638
+ }
2639
+ if (ch === "`") {
2640
+ const end = segment.indexOf("`", j + 1);
2641
+ if (end < 0) return null;
2642
+ j = end;
2643
+ continue;
2644
+ }
2645
+ if (ch === "(") depth++;
2646
+ else if (ch === ")") {
2647
+ depth--;
2648
+ if (depth === 0) return { text: segment.slice(i, j + 1), end: j + 1 };
2649
+ }
2650
+ }
2651
+ return null;
2652
+ }
2653
+ if (next === "{") {
2654
+ let depth = 1;
2655
+ for (let j = i + 2; j < segment.length; j++) {
2656
+ if (segment[j] === "{") depth++;
2657
+ else if (segment[j] === "}") {
2658
+ depth--;
2659
+ if (depth === 0) return { text: segment.slice(i, j + 1), end: j + 1 };
2660
+ }
2661
+ }
2662
+ return null;
2663
+ }
2664
+ if (next && /[A-Za-z_]/.test(next)) {
2665
+ let j = i + 2;
2666
+ while (j < segment.length && /[A-Za-z0-9_]/.test(segment[j])) j++;
2667
+ return { text: segment.slice(i, j), end: j };
2668
+ }
2669
+ return null;
2670
+ }
2671
+
2672
+ // src/core/bash-guard.ts
2673
+ var require2 = createRequire(import.meta.url);
2674
+ var SAFE_GIT_GLOBALS2 = /* @__PURE__ */ new Set([
2675
+ "--no-pager",
2676
+ "-P",
2677
+ "--paginate",
2678
+ "-p",
2679
+ "--literal-pathspecs",
2680
+ "--no-optional-locks",
2681
+ "--no-replace-objects"
2682
+ ]);
2683
+ function refUpdateResyncRoots(command, startDir) {
2684
+ const dirs = [];
2685
+ const ops = parseRefOps(command, startDir);
2686
+ if (ops) {
2687
+ for (const op of ops) {
2688
+ if (op.kind === "update-ref" && !op.stdin && op.ref) dirs.push(op.dir);
2689
+ }
2690
+ }
2691
+ if (dirs.length === 0) dirs.push(...casCommandDirectories(command, startDir));
2692
+ if (dirs.length === 0) return [];
2693
+ let anchor = null;
2694
+ try {
2695
+ anchor = discoverRepository(startDir).commonGitDir;
2696
+ } catch {
2697
+ anchor = null;
2698
+ }
2699
+ const roots = [];
2700
+ for (const dir of dirs) {
2701
+ let checkout;
2702
+ let common;
2703
+ try {
2704
+ const layout = discoverRepository(dir);
2705
+ checkout = layout.checkoutRoot;
2706
+ common = layout.commonGitDir;
2707
+ } catch {
2708
+ continue;
2709
+ }
2710
+ if (!common) continue;
2711
+ if (anchor && common !== anchor) continue;
2712
+ if (!roots.includes(checkout)) roots.push(checkout);
2713
+ }
2714
+ return roots;
2715
+ }
2716
+ function sharedRefUpdatesAreOwned(command, startDir, agent, peers) {
2717
+ const ops = parseRefOps(command, startDir);
2718
+ if (!ops) return false;
2719
+ if (ops.some((op) => op.kind === "block")) return false;
2720
+ const needsOwner = ops.some((op) => op.kind === "update-ref" || op.kind === "symbolic-write");
2721
+ if (!needsOwner) return true;
2722
+ if (!agent?.worktree_path || !agent.branch) return false;
2723
+ const owner = isolatedOwner(agent, peers);
2724
+ for (const op of ops) {
2725
+ if (op.kind === "update-ref" && !updateRefOwned(op, owner)) return false;
2726
+ if (op.kind === "symbolic-write" && !symbolicWriteOwned(op, owner)) return false;
2727
+ }
2728
+ return true;
2729
+ }
2730
+ function isolatedOwner(agent, peers) {
2731
+ if (!agent.worktree_path || !agent.branch) return null;
2732
+ let worktree;
2733
+ try {
2734
+ worktree = physicalPath(agent.worktree_path);
2735
+ } catch {
2736
+ return null;
2737
+ }
2738
+ const main = mainCheckout2(worktree);
2739
+ if (!main || main.path === worktree) return null;
2740
+ if (main.branch && agent.branch === main.branch) return null;
2741
+ for (const peer of peers) {
2742
+ if (peer.branch === agent.branch) return null;
2743
+ try {
2744
+ if (physicalPath(peer.worktree_path ?? main.path) === worktree) return null;
2745
+ } catch {
2746
+ return null;
2747
+ }
2748
+ }
2749
+ return { worktree, branch: agent.branch, integrationBranch: main.branch };
2750
+ }
2751
+ function mainCheckout2(cwd) {
2752
+ let out;
2753
+ try {
2754
+ out = execFileSync7("git", ["worktree", "list", "--porcelain"], {
2755
+ cwd,
2756
+ encoding: "utf8",
2757
+ stdio: ["ignore", "pipe", "ignore"],
2758
+ timeout: 5e3
2759
+ });
2760
+ } catch {
2761
+ return null;
2762
+ }
2763
+ const first = out.split(/\n\s*\n/)[0] ?? "";
2764
+ let wt = null;
2765
+ let branch = null;
2766
+ let detached = false;
2767
+ for (const line of first.split("\n")) {
2768
+ if (line.startsWith("worktree ")) wt = line.slice("worktree ".length).trim();
2769
+ else if (line.startsWith("branch ")) branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
2770
+ else if (line === "detached" || line.startsWith("detached ")) detached = true;
2771
+ }
2772
+ if (!wt) return null;
2773
+ try {
2774
+ return { path: physicalPath(wt), branch: detached ? null : branch };
2775
+ } catch {
2776
+ return null;
2777
+ }
2778
+ }
2779
+ function updateRefOwned(op, owner) {
2780
+ if (op.stdin || !owner || !directoryInside2(op.dir, owner.worktree)) return false;
2781
+ if (op.ref === "HEAD") {
2782
+ if (op.noDeref) return true;
2783
+ const checked2 = checkedOutBranch2(op.dir);
2784
+ if (!checked2.ok) return false;
2785
+ if (checked2.branch === null) return true;
2786
+ return checked2.branch === owner.branch && checked2.branch !== owner.integrationBranch;
2787
+ }
2788
+ const branch = headsBranch(op.ref);
2789
+ if (!branch || branch !== owner.branch || branch === owner.integrationBranch) return false;
2790
+ const checked = checkedOutBranch2(op.dir);
2791
+ return checked.ok && checked.branch === branch;
2792
+ }
2793
+ function symbolicWriteOwned(op, owner) {
2794
+ if (op.delete || !op.target || !owner || op.name !== "HEAD") return false;
2795
+ if (!directoryInside2(op.dir, owner.worktree)) return false;
2796
+ if (owner.integrationBranch && owner.branch === owner.integrationBranch) return false;
2797
+ return op.target === `refs/heads/${owner.branch}`;
2798
+ }
2799
+ function headsBranch(ref) {
2800
+ if (!ref.startsWith("refs/heads/")) return null;
2801
+ const name = ref.slice("refs/heads/".length);
2802
+ if (!name || name.startsWith("/") || name.endsWith("/") || name.includes("@{") || name.includes("..")) return null;
2803
+ return name;
2804
+ }
2805
+ function directoryInside2(dir, worktree) {
2806
+ try {
2807
+ const resolved = physicalPath(dir);
2808
+ return resolved === worktree || isWithin(worktree, resolved);
2809
+ } catch {
2810
+ return false;
2811
+ }
2812
+ }
2813
+ function checkedOutBranch2(dir) {
2814
+ try {
2815
+ const out = execFileSync7("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
2816
+ cwd: dir,
2817
+ encoding: "utf8",
2818
+ stdio: ["ignore", "pipe", "ignore"],
2819
+ timeout: 5e3
2820
+ }).trim();
2821
+ return { ok: true, branch: out || null };
2822
+ } catch (error) {
2823
+ if (error.status === 1) return { ok: true, branch: null };
2824
+ return { ok: false };
2825
+ }
2826
+ }
2827
+ function parseRefOps(command, startDir) {
2828
+ const segments = splitShellSegments2(command);
2829
+ if (!segments) return null;
2830
+ let cwd = path7.resolve(startDir);
2831
+ let trusted = true;
2832
+ const ops = [];
2833
+ for (const segment of segments) {
2834
+ const words = shellWords(segment.raw);
2835
+ const matched = DESTRUCTIVE_SHARED_REFS.test(segment.raw);
2836
+ if (!words) {
2837
+ if (matched) ops.push({ kind: "block" });
2838
+ if (continuesShell2(segment.nextSep) && /\b(?:cd|pushd|popd|export|source)\b|\bGIT_DIR\b/.test(segment.raw)) trusted = false;
2839
+ continue;
2840
+ }
2841
+ const { danger, argv } = stripLeadingEnv2(words);
2842
+ if (argv.length === 0) continue;
2843
+ const head = argv[0];
2844
+ if (head === "cd") {
2845
+ const next = applyCd2(argv, cwd);
2846
+ if (next && continuesShell2(segment.nextSep)) cwd = next;
2847
+ else if (!next && continuesShell2(segment.nextSep)) trusted = false;
2848
+ continue;
2849
+ }
2850
+ if (head === "pushd" || head === "popd" || head === "source" || head === "." && argv.length > 1) {
2851
+ if (continuesShell2(segment.nextSep)) trusted = false;
2852
+ continue;
2853
+ }
2854
+ if (head === "export") {
2855
+ if (argv.slice(1).some((arg) => dangerousGitEnv2(arg.split("=")[0] ?? arg))) trusted = false;
2856
+ continue;
2857
+ }
2858
+ if (!isGitBinary2(head) || danger || !trusted) {
2859
+ if (matched) ops.push({ kind: "block" });
2860
+ continue;
2861
+ }
2862
+ const parsed = parseGitInvocation(argv, cwd);
2863
+ if (parsed.kind === "unclassified") {
2864
+ if (matched) ops.push({ kind: "block" });
2865
+ continue;
2866
+ }
2867
+ if (parsed.kind !== "other") ops.push(parsed);
2868
+ }
2869
+ return ops;
2870
+ }
2871
+ function continuesShell2(sep) {
2872
+ return sep === "&&" || sep === ";" || sep === "\n";
2873
+ }
2874
+ function splitShellSegments2(command) {
2875
+ const parts = [];
2876
+ let buf = "";
2877
+ let quote = null;
2878
+ const push = (sep) => {
2879
+ const raw = buf.trim();
2880
+ buf = "";
2881
+ if (raw) parts.push({ raw, nextSep: sep });
2882
+ };
2883
+ for (let i = 0; i < command.length; i++) {
2884
+ const ch = command[i];
2885
+ if (quote === "'") {
2886
+ buf += ch;
2887
+ if (ch === "'") quote = null;
2888
+ continue;
2889
+ }
2890
+ if (quote === '"') {
2891
+ if (ch === "\\" && i + 1 < command.length) {
2892
+ const next = command[i + 1];
2893
+ if (next === "$" || next === "`" || next === '"' || next === "\\" || next === "\n") {
2894
+ buf += ch + next;
2895
+ i++;
2896
+ continue;
2897
+ }
2898
+ }
2899
+ buf += ch;
2900
+ if (ch === '"') quote = null;
2901
+ continue;
2902
+ }
2903
+ if (ch === "\\" && i + 1 < command.length) {
2904
+ if (command[i + 1] === "\n") {
2905
+ i++;
2906
+ continue;
2907
+ }
2908
+ buf += ch + command[i + 1];
2909
+ i++;
2910
+ continue;
2911
+ }
2912
+ if (ch === "'" || ch === '"') {
2913
+ quote = ch;
2914
+ buf += ch;
2915
+ continue;
2916
+ }
2917
+ if (ch === "&" && command[i + 1] === "&") {
2918
+ push("&&");
2919
+ i++;
2920
+ continue;
2921
+ }
2922
+ if (ch === "|" && command[i + 1] === "|") {
2923
+ push("||");
2924
+ i++;
2925
+ continue;
2926
+ }
2927
+ if (ch === "\r" && command[i + 1] === "\n") {
2928
+ push("\n");
2929
+ i++;
2930
+ continue;
2931
+ }
2932
+ if (ch === "\n") {
2933
+ push("\n");
2934
+ continue;
2935
+ }
2936
+ if (ch === ";") {
2937
+ push(";");
2938
+ continue;
2939
+ }
2940
+ if (ch === "|") {
2941
+ push("|");
2942
+ continue;
2943
+ }
2944
+ if (ch === "&") {
2945
+ push("&");
2946
+ continue;
2947
+ }
2948
+ buf += ch;
2949
+ }
2950
+ if (quote) return null;
2951
+ push("end");
2952
+ return parts;
2953
+ }
2954
+ function shellWords(segment) {
2955
+ const words = [];
2956
+ let buf = "";
2957
+ let quote = null;
2958
+ let word = false;
2959
+ const flush = () => {
2960
+ if (word) words.push(buf);
2961
+ buf = "";
2962
+ word = false;
2963
+ };
2964
+ for (let i = 0; i < segment.length; i++) {
2965
+ const ch = segment[i];
2966
+ if (quote === "'") {
2967
+ if (ch === "'") quote = null;
2968
+ else {
2969
+ buf += ch;
2970
+ word = true;
2971
+ }
2972
+ continue;
2973
+ }
2974
+ if (quote === '"') {
2975
+ if (ch === "\\" && i + 1 < segment.length) {
2976
+ const next = segment[i + 1];
2977
+ if ('$`"\\'.includes(next)) {
2978
+ buf += next;
2979
+ word = true;
2980
+ i++;
2981
+ continue;
2982
+ }
2983
+ if (next === "\n") {
2984
+ i++;
2985
+ continue;
2986
+ }
2987
+ }
2988
+ if (ch === '"') {
2989
+ quote = null;
2990
+ word = true;
2991
+ continue;
2992
+ }
2993
+ if (ch === "`" || ch === "$") return null;
2994
+ buf += ch;
2995
+ word = true;
2996
+ continue;
2997
+ }
2998
+ if (ch === "\\" && i + 1 < segment.length) {
2999
+ buf += segment[i + 1];
3000
+ word = true;
3001
+ i++;
3002
+ continue;
3003
+ }
3004
+ if (ch === "'" || ch === '"') {
3005
+ quote = ch;
3006
+ word = true;
3007
+ continue;
3008
+ }
3009
+ if (ch === "`" || ch === "$" || ch === "(" || ch === ")" || ch === "<" || ch === ">") return null;
3010
+ if (ch === "#" && !word) break;
3011
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
3012
+ flush();
3013
+ continue;
3014
+ }
3015
+ buf += ch;
3016
+ word = true;
3017
+ }
3018
+ if (quote) return null;
3019
+ flush();
3020
+ return words;
3021
+ }
3022
+ function stripLeadingEnv2(argv) {
3023
+ let i = 0;
3024
+ let danger = false;
3025
+ while (i < argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[i])) {
3026
+ if (dangerousGitEnv2(argv[i].slice(0, argv[i].indexOf("=")))) danger = true;
3027
+ i++;
3028
+ }
3029
+ return { danger, argv: argv.slice(i) };
3030
+ }
3031
+ function dangerousGitEnv2(name) {
3032
+ 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);
3033
+ }
3034
+ function applyCd2(argv, cwd) {
3035
+ let args = argv.slice(1);
3036
+ if (args[0] === "--") args = args.slice(1);
3037
+ if (args.length !== 1 || args[0] === "-" || args[0].startsWith("-") || args[0].startsWith("~")) return null;
3038
+ return path7.resolve(cwd, args[0]);
3039
+ }
3040
+ function isGitBinary2(word) {
3041
+ const base = word.slice(Math.max(word.lastIndexOf("/"), word.lastIndexOf("\\")) + 1);
3042
+ return base === "git" || base.toLowerCase() === "git.exe";
3043
+ }
3044
+ function parseGitInvocation(argv, cwd) {
3045
+ let i = 1;
3046
+ let dir = cwd;
3047
+ while (i < argv.length) {
3048
+ const token = argv[i];
3049
+ if (token === "--") {
3050
+ i++;
3051
+ break;
3052
+ }
3053
+ if (token === "-C") {
3054
+ const next = argv[i + 1];
3055
+ if (next === void 0 || next.startsWith("~")) return { kind: "unclassified" };
3056
+ if (next !== "") dir = path7.isAbsolute(next) ? next : path7.resolve(dir, next);
3057
+ i += 2;
3058
+ continue;
3059
+ }
3060
+ if (token.startsWith("-C") && token.length > 2) {
3061
+ const next = token.slice(2);
3062
+ if (next.startsWith("~")) return { kind: "unclassified" };
3063
+ dir = path7.isAbsolute(next) ? next : path7.resolve(dir, next);
3064
+ i++;
3065
+ continue;
3066
+ }
3067
+ if (SAFE_GIT_GLOBALS2.has(token)) {
3068
+ i++;
3069
+ continue;
3070
+ }
3071
+ if (token.startsWith("-")) return { kind: "unclassified" };
3072
+ break;
3073
+ }
3074
+ const sub = argv[i];
3075
+ if (!sub) return { kind: "other" };
3076
+ const args = argv.slice(i + 1);
3077
+ if (sub === "update-ref") return parseUpdateRef(dir, args);
3078
+ if (sub === "symbolic-ref") return parseSymbolicRef(dir, args);
3079
+ if (sub === "worktree") return args.some((arg) => arg === "remove" || arg === "prune") ? { kind: "block" } : { kind: "other" };
3080
+ if (sub === "branch") return branchArgsAreDestructive(args) ? { kind: "block" } : { kind: "other" };
3081
+ return { kind: "other" };
3082
+ }
3083
+ function branchArgsAreDestructive(args) {
3084
+ for (const arg of args) {
3085
+ if (arg === "--") break;
3086
+ if (arg === "--delete" || arg === "--move" || arg === "--force") return true;
3087
+ if (arg.startsWith("--delete") || arg.startsWith("--move") || arg.startsWith("--force")) return true;
3088
+ if (arg.startsWith("-") && !arg.startsWith("--") && /[dDmMfF]/.test(arg.slice(1))) return true;
3089
+ }
3090
+ return false;
3091
+ }
3092
+ function parseUpdateRef(dir, args) {
3093
+ let noDeref = false;
3094
+ let deleteRef = false;
3095
+ let stdin = false;
3096
+ let end = false;
3097
+ const positionals = [];
3098
+ for (let i = 0; i < args.length; i++) {
3099
+ const arg = args[i];
3100
+ if (!end && arg === "--") {
3101
+ end = true;
3102
+ continue;
3103
+ }
3104
+ if (!end && arg.startsWith("-")) {
3105
+ if (arg === "--no-deref") {
3106
+ noDeref = true;
3107
+ continue;
3108
+ }
3109
+ if (arg === "--deref") {
3110
+ noDeref = false;
3111
+ continue;
3112
+ }
3113
+ if (arg === "--create-reflog" || arg === "--no-create-reflog" || arg === "--no-stdin") continue;
3114
+ if (arg === "--stdin" || arg === "-z") {
3115
+ stdin = true;
3116
+ continue;
3117
+ }
3118
+ if (arg === "-d") {
3119
+ deleteRef = true;
3120
+ continue;
3121
+ }
3122
+ if (arg === "-m" || arg === "--message") {
3123
+ if (args[i + 1] === void 0) return { kind: "unclassified" };
3124
+ i++;
3125
+ continue;
3126
+ }
3127
+ if (arg.startsWith("-m") && arg.length > 2) continue;
3128
+ if (arg.startsWith("--message=")) continue;
3129
+ return { kind: "unclassified" };
3130
+ }
3131
+ positionals.push(arg);
3132
+ }
3133
+ if (stdin) return { kind: "update-ref", dir, ref: "", noDeref, stdin: true };
3134
+ const expected = deleteRef ? [1, 2] : [2, 3];
3135
+ if (!expected.includes(positionals.length) || !positionals[0]) return { kind: "unclassified" };
3136
+ return { kind: "update-ref", dir, ref: positionals[0], noDeref, stdin: false };
3137
+ }
3138
+ function parseSymbolicRef(dir, args) {
3139
+ let deleteRef = false;
3140
+ let end = false;
3141
+ const positionals = [];
3142
+ for (let i = 0; i < args.length; i++) {
3143
+ const arg = args[i];
3144
+ if (!end && arg === "--") {
3145
+ end = true;
3146
+ continue;
3147
+ }
3148
+ if (!end && arg.startsWith("-")) {
3149
+ if (arg === "-q" || arg === "--quiet" || arg === "--no-quiet" || arg === "--short" || arg === "--no-short") continue;
3150
+ if (arg === "--recurse" || arg === "--no-recurse") continue;
3151
+ if (arg === "-d" || arg === "--delete") {
3152
+ deleteRef = true;
3153
+ continue;
3154
+ }
3155
+ if (arg === "--no-delete") {
3156
+ deleteRef = false;
3157
+ continue;
3158
+ }
3159
+ if (arg === "-m" || arg === "--message") {
3160
+ if (args[i + 1] === void 0) return { kind: "unclassified" };
3161
+ i++;
3162
+ continue;
3163
+ }
3164
+ if (arg.startsWith("-m") && arg.length > 2) continue;
3165
+ if (arg.startsWith("--message=")) continue;
3166
+ return { kind: "unclassified" };
3167
+ }
3168
+ positionals.push(arg);
1618
3169
  }
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`);
3170
+ if (deleteRef) {
3171
+ if (positionals.length !== 1) return { kind: "unclassified" };
3172
+ return { kind: "symbolic-write", dir, name: positionals[0], target: null, delete: true };
3173
+ }
3174
+ if (positionals.length === 1) return { kind: "symbolic-read" };
3175
+ if (positionals.length === 2) return { kind: "symbolic-write", dir, name: positionals[0], target: positionals[1], delete: false };
3176
+ return { kind: "unclassified" };
3177
+ }
1625
3178
  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
3179
  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
3180
  function isReadOnlyShellCommand(command) {
@@ -1637,7 +3190,7 @@ function commandTargetsFileForWrite(command, relPath) {
1637
3190
  if (!WRITE_PRIMITIVE_RE.test(stripped)) return false;
1638
3191
  const norm = relPath.replace(/\\/g, "/");
1639
3192
  if (stripped.includes(norm)) return true;
1640
- const base = path6.posix.basename(norm);
3193
+ const base = path7.posix.basename(norm);
1641
3194
  return base.length >= 4 && stripped.includes(base);
1642
3195
  }
1643
3196
  var BashMerkleGuard = class _BashMerkleGuard {
@@ -1658,21 +3211,76 @@ var BashMerkleGuard = class _BashMerkleGuard {
1658
3211
  */
1659
3212
  checkCommandSafety(params) {
1660
3213
  this.fencing.assertSession(params.agentId);
1661
- const root = physicalPath(this.fencing.getAgent(params.agentId)?.worktree_path ?? this.coordDb.repoRoot);
3214
+ const agent = this.fencing.getAgent(params.agentId);
3215
+ const repoRoot = this.coordDb.repoRoot;
3216
+ const root = physicalPath(agent?.worktree_path ?? repoRoot);
1662
3217
  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
- };
3218
+ const sharesCheckout = peers.some((a) => physicalPath(a.worktree_path ?? repoRoot) === root);
3219
+ const startDir = agent?.worktree_path ?? repoRoot;
3220
+ const refuse = (specific) => ({
3221
+ safe: false,
3222
+ reason: firewallReason(suggestKithCommit(this.refHost(params.agentId), params.command), specific)
3223
+ });
3224
+ if (peers.length && sharesCheckout && commandMovesSharedCheckout(params.command)) {
3225
+ const foreign = foreignRefLease(this.coordDb.coordDir, params.agentId);
3226
+ if (foreign) {
3227
+ return refuse(`Agent ${foreign.agentId} is verifying a shared-checkout commit; retry shortly.`);
3228
+ }
3229
+ }
3230
+ if (peers.length && DESTRUCTIVE_SHARED_REFS.test(params.command) && !sharedRefUpdatesAreOwned(params.command, startDir, agent, peers)) {
3231
+ try {
3232
+ const decision = assessSharedCheckoutUpdate(this.refHost(params.agentId), params.command, startDir);
3233
+ if (decision.action === "allow") return { safe: true };
3234
+ if (decision.action === "defer") return { safe: true, deferred: true };
3235
+ if (decision.action === "block" && decision.reason) return { safe: false, reason: decision.reason };
3236
+ } catch {
3237
+ return refuse("The shared-checkout update could not be verified.");
3238
+ }
3239
+ return refuse();
3240
+ }
3241
+ if (sharesCheckout && DESTRUCTIVE_SHARED_TREE.test(params.command)) {
3242
+ return refuse();
1669
3243
  }
1670
3244
  return { safe: true };
1671
3245
  }
3246
+ /**
3247
+ * Post-hook half of a deferred shared-checkout update-ref. Literal SHAs are decided in
3248
+ * checkCommandSafety; shell variables are checked against the commit that landed.
3249
+ */
3250
+ settleDeferredRefUpdate(params) {
3251
+ return settleDeferredRefUpdate(this.refHost(params.agentId), params.command);
3252
+ }
3253
+ refHost(agentId) {
3254
+ const agent = this.fencing.getAgent(agentId);
3255
+ return {
3256
+ repoRoot: this.coordDb.repoRoot,
3257
+ coordDir: this.coordDb.coordDir,
3258
+ agentId,
3259
+ agent,
3260
+ locks: this.lockEngine.listLocks(),
3261
+ tasks: this.recordedTasks(),
3262
+ presenceTouched: presenceTouchedFor(this.coordDb.commonGitDir, agent),
3263
+ logEvent: (id, type, payload) => this.coordDb.logEvent(id, type, payload)
3264
+ };
3265
+ }
3266
+ recordedTasks() {
3267
+ try {
3268
+ const rows = this.coordDb.db.prepare(
3269
+ `SELECT owner_agent_id, status, scope_globs_json FROM tasks`
3270
+ ).all();
3271
+ return rows.map((row) => ({
3272
+ owner_agent_id: row.owner_agent_id,
3273
+ status: row.status,
3274
+ scope_globs: parseScopeGlobs(row.scope_globs_json)
3275
+ }));
3276
+ } catch {
3277
+ return [];
3278
+ }
3279
+ }
1672
3280
  getSnapshotFilePath(agentId) {
1673
3281
  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`);
3282
+ const safeId = crypto6.createHash("sha256").update(`${agentId}:${epoch}`).digest("hex");
3283
+ return path7.join(this.coordDb.coordDir, "snapshots", `${safeId}.json`);
1676
3284
  }
1677
3285
  /**
1678
3286
  * Captures a Merkle snapshot of workspace files before a Bash tool execution.
@@ -1683,9 +3291,9 @@ var BashMerkleGuard = class _BashMerkleGuard {
1683
3291
  const activeLocks = this.lockEngine.listLocks().filter((l) => l.owner_agent_id !== agentId);
1684
3292
  const snapPath = this.getSnapshotFilePath(agentId);
1685
3293
  let prevEntries = {};
1686
- if (fs6.existsSync(snapPath)) {
3294
+ if (fs7.existsSync(snapPath)) {
1687
3295
  try {
1688
- const parsed = JSON.parse(fs6.readFileSync(snapPath, "utf8"));
3296
+ const parsed = JSON.parse(fs7.readFileSync(snapPath, "utf8"));
1689
3297
  if (parsed.rootDir === rootDir && parsed.entries) prevEntries = parsed.entries;
1690
3298
  } catch {
1691
3299
  }
@@ -1694,8 +3302,8 @@ var BashMerkleGuard = class _BashMerkleGuard {
1694
3302
  const entries = {};
1695
3303
  const files = this.walkWorkspaceFiles(rootDir);
1696
3304
  for (const absPath of files) {
1697
- const relPath = path6.relative(rootDir, absPath).replace(/\\/g, "/");
1698
- const stat = fs6.statSync(absPath);
3305
+ const relPath = path7.relative(rootDir, absPath).replace(/\\/g, "/");
3306
+ const stat = fs7.statSync(absPath);
1699
3307
  if (stat.size > 5 * 1024 * 1024) continue;
1700
3308
  const lockedByOther = activeLocks.some(
1701
3309
  (l) => LockEngine.patternsOverlap(relPath, l.pattern)
@@ -1710,8 +3318,8 @@ var BashMerkleGuard = class _BashMerkleGuard {
1710
3318
  };
1711
3319
  continue;
1712
3320
  }
1713
- const buf = fs6.readFileSync(absPath);
1714
- const sha256 = unchanged ? cached.sha256 : crypto5.createHash("sha256").update(buf).digest("hex");
3321
+ const buf = fs7.readFileSync(absPath);
3322
+ const sha256 = unchanged ? cached.sha256 : crypto6.createHash("sha256").update(buf).digest("hex");
1715
3323
  entries[relPath] = {
1716
3324
  relPath,
1717
3325
  mtimeMs: stat.mtimeMs,
@@ -1721,7 +3329,7 @@ var BashMerkleGuard = class _BashMerkleGuard {
1721
3329
  backupContentBase64: lockedByOther ? buf.toString("base64") : void 0
1722
3330
  };
1723
3331
  }
1724
- fs6.writeFileSync(
3332
+ fs7.writeFileSync(
1725
3333
  snapPath,
1726
3334
  JSON.stringify({ timestamp: Date.now(), rootDir, entries }),
1727
3335
  { encoding: "utf8", mode: 384 }
@@ -1735,10 +3343,10 @@ var BashMerkleGuard = class _BashMerkleGuard {
1735
3343
  */
1736
3344
  verifyPostBashAndQuarantine(params) {
1737
3345
  const snapPath = this.getSnapshotFilePath(params.agentId);
1738
- if (!fs6.existsSync(snapPath)) {
3346
+ if (!fs7.existsSync(snapPath)) {
1739
3347
  return { allowed: true, authorizedModifiedFiles: [], quarantinedViolations: [] };
1740
3348
  }
1741
- const rawSnap = JSON.parse(fs6.readFileSync(snapPath, "utf8"));
3349
+ const rawSnap = JSON.parse(fs7.readFileSync(snapPath, "utf8"));
1742
3350
  const rootDir = params.rootDir ?? rawSnap.rootDir ?? this.coordDb.repoRoot;
1743
3351
  const beforeEntries = rawSnap.entries;
1744
3352
  const currentFiles = this.walkWorkspaceFiles(rootDir);
@@ -1747,16 +3355,16 @@ var BashMerkleGuard = class _BashMerkleGuard {
1747
3355
  const authorizedModifiedFiles = [];
1748
3356
  const quarantinedViolations = [];
1749
3357
  for (const absPath of currentFiles) {
1750
- const relPath = path6.relative(rootDir, absPath).replace(/\\/g, "/");
3358
+ const relPath = path7.relative(rootDir, absPath).replace(/\\/g, "/");
1751
3359
  seenCurrentRelPaths.add(relPath);
1752
- const stat = fs6.statSync(absPath);
3360
+ const stat = fs7.statSync(absPath);
1753
3361
  if (stat.size > 5 * 1024 * 1024) continue;
1754
3362
  const prev = beforeEntries[relPath];
1755
3363
  if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
1756
3364
  continue;
1757
3365
  }
1758
- const buf = fs6.readFileSync(absPath);
1759
- const sha256 = crypto5.createHash("sha256").update(buf).digest("hex");
3366
+ const buf = fs7.readFileSync(absPath);
3367
+ const sha256 = crypto6.createHash("sha256").update(buf).digest("hex");
1760
3368
  if (prev && prev.sha256 === sha256) {
1761
3369
  continue;
1762
3370
  }
@@ -1810,14 +3418,14 @@ var BashMerkleGuard = class _BashMerkleGuard {
1810
3418
  }
1811
3419
  }
1812
3420
  try {
1813
- fs6.unlinkSync(snapPath);
3421
+ fs7.unlinkSync(snapPath);
1814
3422
  } catch {
1815
3423
  }
1816
3424
  if (authorizedModifiedFiles.length > 0) {
1817
3425
  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"));
3426
+ const absFile = path7.join(rootDir, relFile);
3427
+ if (fs7.existsSync(absFile) && /\.(ts|tsx|js|jsx|mjs|py)$/.test(relFile)) {
3428
+ this.depGraph.recordFileModification(params.agentId, relFile, fs7.readFileSync(absFile, "utf8"));
1821
3429
  }
1822
3430
  }
1823
3431
  this.shadowGit.probeAllActiveConflicts(
@@ -1833,31 +3441,31 @@ var BashMerkleGuard = class _BashMerkleGuard {
1833
3441
  };
1834
3442
  }
1835
3443
  quarantineAndRevertFile(params) {
1836
- const id = `quar_${crypto5.randomBytes(6).toString("hex")}`;
3444
+ const id = `quar_${crypto6.randomBytes(6).toString("hex")}`;
1837
3445
  const now = Date.now();
1838
3446
  const safeName = params.relPath.replace(/[^a-zA-Z0-9._-]/g, "_");
1839
- const patchPath = path6.join(
3447
+ const patchPath = path7.join(
1840
3448
  this.coordDb.coordDir,
1841
3449
  "quarantine",
1842
3450
  `${id}_${safeName}.quarantine`
1843
3451
  );
1844
3452
  if (params.unauthorizedBuf) {
1845
- fs6.writeFileSync(patchPath, params.unauthorizedBuf, { mode: 384 });
3453
+ fs7.writeFileSync(patchPath, params.unauthorizedBuf, { mode: 384 });
1846
3454
  } else {
1847
- fs6.writeFileSync(patchPath, `[DELETED BY COMMAND: ${params.command}]
3455
+ fs7.writeFileSync(patchPath, `[DELETED BY COMMAND: ${params.command}]
1848
3456
  `, { encoding: "utf8", mode: 384 });
1849
3457
  }
1850
3458
  if (params.prevEntry?.backupContentBase64 !== void 0) {
1851
- fs6.writeFileSync(patchPath + ".before", Buffer.from(params.prevEntry.backupContentBase64, "base64"), { mode: 384 });
3459
+ fs7.writeFileSync(patchPath + ".before", Buffer.from(params.prevEntry.backupContentBase64, "base64"), { mode: 384 });
1852
3460
  }
1853
- const absTarget = path6.join(params.rootDir, params.relPath);
3461
+ const absTarget = path7.join(params.rootDir, params.relPath);
1854
3462
  if (params.restoreLockedFiles && params.prevEntry === null) {
1855
- if (fs6.existsSync(absTarget)) {
1856
- fs6.unlinkSync(absTarget);
3463
+ if (fs7.existsSync(absTarget)) {
3464
+ fs7.unlinkSync(absTarget);
1857
3465
  }
1858
3466
  } else if (params.restoreLockedFiles && params.prevEntry?.backupContentBase64 !== void 0) {
1859
- fs6.mkdirSync(path6.dirname(absTarget), { recursive: true });
1860
- fs6.writeFileSync(
3467
+ fs7.mkdirSync(path7.dirname(absTarget), { recursive: true });
3468
+ fs7.writeFileSync(
1861
3469
  absTarget,
1862
3470
  Buffer.from(params.prevEntry.backupContentBase64, "base64")
1863
3471
  );
@@ -1916,12 +3524,36 @@ var BashMerkleGuard = class _BashMerkleGuard {
1916
3524
  return this.coordDb.db.prepare(`SELECT * FROM quarantine ORDER BY created_at DESC`).all();
1917
3525
  }
1918
3526
  };
3527
+ function parseScopeGlobs(raw) {
3528
+ try {
3529
+ const parsed = JSON.parse(raw);
3530
+ return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : [];
3531
+ } catch {
3532
+ return [];
3533
+ }
3534
+ }
3535
+ function presenceTouchedFor(commonGitDir, agent) {
3536
+ if (!commonGitDir || !agent) return [];
3537
+ try {
3538
+ const { listRepoPresence: listRepoPresence2, ownedByCaller: ownedByCaller2 } = require2("../cli/auto-session.js");
3539
+ const peers = listRepoPresence2(void 0, commonGitDir);
3540
+ const touched = /* @__PURE__ */ new Set();
3541
+ for (const peer of peers) {
3542
+ if (peer.agentId === agent.id) for (const file of peer.touchedFiles) touched.add(file);
3543
+ }
3544
+ const byPid = peers.filter((peer) => ownedByCaller2(peer.pid, agent.pid));
3545
+ if (byPid.length === 1) for (const file of byPid[0].touchedFiles) touched.add(file);
3546
+ return [...touched];
3547
+ } catch {
3548
+ return [];
3549
+ }
3550
+ }
1919
3551
 
1920
3552
  // src/core/broker.ts
1921
3553
  import { fork } from "child_process";
1922
- import fs7 from "fs";
3554
+ import fs8 from "fs";
1923
3555
  import { fileURLToPath } from "url";
1924
- import crypto6 from "crypto";
3556
+ import crypto7 from "crypto";
1925
3557
  import net from "net";
1926
3558
  var ResourceBroker = class _ResourceBroker {
1927
3559
  constructor(coordDb, fencing) {
@@ -1979,7 +3611,7 @@ var ResourceBroker = class _ResourceBroker {
1979
3611
  id, type, name, value, owner_agent_id, fencing_token, queue_json, acquired_at, expires_at
1980
3612
  ) VALUES (?, 'port', ?, ?, ?, ?, '[]', ?, ?)
1981
3613
  `).run(
1982
- `res_${crypto6.randomBytes(6).toString("hex")}`,
3614
+ `res_${crypto7.randomBytes(6).toString("hex")}`,
1983
3615
  resourceKey,
1984
3616
  String(candidatePort),
1985
3617
  params.agentId,
@@ -2046,7 +3678,7 @@ var ResourceBroker = class _ResourceBroker {
2046
3678
  this.coordDb.db.prepare(`INSERT OR REPLACE INTO resources
2047
3679
  (id, type, name, value, owner_agent_id, fencing_token, queue_json, acquired_at, expires_at)
2048
3680
  VALUES (?, 'mutex', ?, 'locked', ?, ?, '[]', ?, ?)
2049
- `).run(existing?.id ?? `res_${crypto6.randomBytes(6).toString("hex")}`, params.mutexName, params.agentId, token, now, now + leaseMs);
3681
+ `).run(existing?.id ?? `res_${crypto7.randomBytes(6).toString("hex")}`, params.mutexName, params.agentId, token, now, now + leaseMs);
2050
3682
  this.coordDb.db.prepare("DELETE FROM mutex_waiters WHERE mutex_name=? AND request_id=?").run(params.mutexName, requestId);
2051
3683
  this.coordDb.logEvent(params.agentId, "mutex_acquired", { mutexName: params.mutexName, fencingToken: token });
2052
3684
  return { acquired: true, fencingToken: token, holderAgentId: params.agentId, queuePosition: 0 };
@@ -2125,7 +3757,7 @@ var ResourceBroker = class _ResourceBroker {
2125
3757
  }
2126
3758
  if (params.maxOutputBytes !== void 0 && (!Number.isSafeInteger(params.maxOutputBytes) || params.maxOutputBytes <= 0)) throw new Error("maxOutputBytes must be a positive integer");
2127
3759
  const epoch = this.fencing.assertSession(params.agentId);
2128
- const requestId = crypto6.randomUUID();
3760
+ const requestId = crypto7.randomUUID();
2129
3761
  const started = Date.now();
2130
3762
  let run = null;
2131
3763
  const abortError = () => new DOMException("Mutex command cancelled", "AbortError");
@@ -2162,7 +3794,7 @@ var ResourceBroker = class _ResourceBroker {
2162
3794
  const prepared = await lifecycle?.prepare();
2163
3795
  if (params.signal?.aborted) throw abortError();
2164
3796
  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));
3797
+ const script = candidates.find((name) => fs8.existsSync(name));
2166
3798
  if (!script) throw new Error("Missing command worker. Build Kith before running supervised commands.");
2167
3799
  const worker = fork(script, [], { detached: true, stdio: ["ignore", "pipe", "pipe", "ipc"], execArgv: [] });
2168
3800
  const workerPid = worker.pid;
@@ -2346,10 +3978,10 @@ function groupIsAlive(pgid, expectedStart) {
2346
3978
  }
2347
3979
  if (process.platform === "linux") {
2348
3980
  try {
2349
- for (const pid of fs7.readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
3981
+ for (const pid of fs8.readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
2350
3982
  let stat;
2351
3983
  try {
2352
- stat = fs7.readFileSync(`/proc/${pid}/stat`, "utf8");
3984
+ stat = fs8.readFileSync(`/proc/${pid}/stat`, "utf8");
2353
3985
  } catch (err) {
2354
3986
  if (err.code === "ENOENT" || err.code === "ESRCH") continue;
2355
3987
  return true;
@@ -2377,13 +4009,13 @@ function delay(ms) {
2377
4009
  }
2378
4010
 
2379
4011
  // 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);
4012
+ import { createRequire as createRequire2 } from "module";
4013
+ import fs9 from "fs";
4014
+ import path8 from "path";
4015
+ var require3 = createRequire2(import.meta.url);
2384
4016
  var sqlite;
2385
4017
  function sqliteDatabase() {
2386
- return (sqlite ??= require2("node:sqlite")).DatabaseSync;
4018
+ return (sqlite ??= require3("node:sqlite")).DatabaseSync;
2387
4019
  }
2388
4020
  var CoordDatabase = class _CoordDatabase {
2389
4021
  db;
@@ -2398,26 +4030,26 @@ var CoordDatabase = class _CoordDatabase {
2398
4030
  this.repoRoot = layout.checkoutRoot;
2399
4031
  this.commonGitDir = layout.commonGitDir;
2400
4032
  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"))) {
4033
+ for (let current = fs9.realpathSync.native(repoRoot); isWithin(this.repoRoot, current); current = path8.dirname(current)) {
4034
+ const local = path8.join(current, ".coord");
4035
+ if (local !== layout.coordDir && fs9.existsSync(path8.join(local, "state.db"))) {
2404
4036
  throw new Error(`Legacy checkout-local coordination state found at ${local}. Stop clients and preserve that directory before consolidating shared state.`);
2405
4037
  }
2406
4038
  if (current === this.repoRoot) break;
2407
4039
  }
2408
4040
  this.coordDir = layout.coordDir;
2409
4041
  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");
4042
+ this.dbPath = customDbPath ?? path8.join(this.coordDir, "state.db");
2411
4043
  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);
4044
+ 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) => {
4045
+ const dir = path8.join(this.coordDir, name);
4046
+ return fs9.existsSync(dir) && (!fs9.lstatSync(dir).isDirectory() || fs9.readdirSync(dir).length > 0);
2415
4047
  }));
2416
- const sidecars = ["-wal", "-shm", "-journal"].some((suffix) => fs8.existsSync(this.dbPath + suffix));
2417
- if (!fs8.existsSync(this.dbPath) && (recoveryFiles || sidecars)) {
4048
+ const sidecars = ["-wal", "-shm", "-journal"].some((suffix) => fs9.existsSync(this.dbPath + suffix));
4049
+ if (!fs9.existsSync(this.dbPath) && (recoveryFiles || sidecars)) {
2418
4050
  throw new Error("Missing coordination database with existing recovery state. Stop clients and preserve the database, sidecars and worktrees before repair.");
2419
4051
  }
2420
- if (fs8.existsSync(this.dbPath)) {
4052
+ if (fs9.existsSync(this.dbPath)) {
2421
4053
  const probe = new (sqliteDatabase())(this.dbPath, { readOnly: true });
2422
4054
  try {
2423
4055
  probe.exec("PRAGMA busy_timeout=10000; BEGIN");
@@ -2428,13 +4060,13 @@ var CoordDatabase = class _CoordDatabase {
2428
4060
  probe.close();
2429
4061
  }
2430
4062
  }
2431
- fs8.mkdirSync(this.coordDir, { recursive: true, mode: 448 });
4063
+ fs9.mkdirSync(this.coordDir, { recursive: true, mode: 448 });
2432
4064
  for (const name of ["shadow-index", "quarantine", "snapshots", "worktrees"]) {
2433
- const target = path7.join(this.coordDir, name);
4065
+ const target = path8.join(this.coordDir, name);
2434
4066
  if (!isWithin(this.coordDir, physicalPath(target)) || physicalPath(target) !== target) {
2435
4067
  throw new Error(`Coordination subdirectory must not be a symlink: ${name}`);
2436
4068
  }
2437
- fs8.mkdirSync(target, { recursive: true });
4069
+ fs9.mkdirSync(target, { recursive: true });
2438
4070
  }
2439
4071
  this.db = new (sqliteDatabase())(this.dbPath);
2440
4072
  try {
@@ -2813,7 +4445,7 @@ var CoordDatabase = class _CoordDatabase {
2813
4445
  };
2814
4446
 
2815
4447
  // src/core/dep-graph.ts
2816
- import crypto7 from "crypto";
4448
+ import crypto8 from "crypto";
2817
4449
  var DependencyAndContractEngine = class _DependencyAndContractEngine {
2818
4450
  constructor(coordDb, lockEngine, fencing) {
2819
4451
  this.coordDb = coordDb;
@@ -2945,7 +4577,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
2945
4577
  };
2946
4578
  breakingChanges.push(alert);
2947
4579
  if (agentId && affectedLock) {
2948
- const conflictId = `conf_${crypto7.randomBytes(6).toString("hex")}`;
4580
+ const conflictId = `conf_${crypto8.randomBytes(6).toString("hex")}`;
2949
4581
  this.coordDb.db.prepare(`
2950
4582
  INSERT OR REPLACE INTO conflicts (
2951
4583
  id, agent_a, agent_b, file_path, severity, details_json, detected_at
@@ -2994,7 +4626,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
2994
4626
  publishExplicitContract(params) {
2995
4627
  const relPath = LockEngine.normalizeFile(this.coordDb.repoRoot, params.filePath);
2996
4628
  const now = Date.now();
2997
- const astHash = crypto7.createHash("sha256").update(params.signature).digest("hex").slice(0, 16);
4629
+ const astHash = crypto8.createHash("sha256").update(params.signature).digest("hex").slice(0, 16);
2998
4630
  return this.coordDb.withTransaction(() => {
2999
4631
  this.fencing.assertSession(params.agentId);
3000
4632
  const prevRow = this.coordDb.db.prepare(`SELECT * FROM contracts WHERE file_path = ? AND symbol_name = ?`).get(relPath, params.symbolName);
@@ -3025,7 +4657,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
3025
4657
  });
3026
4658
  }
3027
4659
  upsertContractInternal(params) {
3028
- const id = params.prev?.id ?? `ctr_${crypto7.randomBytes(6).toString("hex")}`;
4660
+ const id = params.prev?.id ?? `ctr_${crypto8.randomBytes(6).toString("hex")}`;
3029
4661
  const version = params.prev ? params.prev.ast_hash !== params.symbol.astHash ? params.prev.version + 1 : params.prev.version : 1;
3030
4662
  this.coordDb.db.prepare(`
3031
4663
  INSERT OR REPLACE INTO contracts (
@@ -3115,7 +4747,7 @@ var DependencyAndContractEngine = class _DependencyAndContractEngine {
3115
4747
  };
3116
4748
 
3117
4749
  // src/core/intents.ts
3118
- import crypto8 from "crypto";
4750
+ import crypto9 from "crypto";
3119
4751
  var IntentAndTaskEngine = class {
3120
4752
  constructor(coordDb, fencing, lockEngine) {
3121
4753
  this.coordDb = coordDb;
@@ -3137,7 +4769,7 @@ var IntentAndTaskEngine = class {
3137
4769
  const activeTasks = this.listTasks({ status: "active" }).filter(
3138
4770
  (t) => t.owner_agent_id !== params.agentId
3139
4771
  );
3140
- const taskId = `task_${crypto8.randomBytes(6).toString("hex")}`;
4772
+ const taskId = `task_${crypto9.randomBytes(6).toString("hex")}`;
3141
4773
  const lockRes = this.lockEngine.acquireLocks({
3142
4774
  agentId: params.agentId,
3143
4775
  patterns: params.scopeGlobs,
@@ -3195,7 +4827,7 @@ var IntentAndTaskEngine = class {
3195
4827
  * Orchestrator Mode: Adds a task to the DAG queue with optional dependencies and priority.
3196
4828
  */
3197
4829
  addTask(params) {
3198
- const id = params.id ?? `task_${crypto8.randomBytes(6).toString("hex")}`;
4830
+ const id = params.id ?? `task_${crypto9.randomBytes(6).toString("hex")}`;
3199
4831
  const dependsOn = params.dependsOn ?? [];
3200
4832
  const scopeGlobs = (params.scopeGlobs ?? []).map(
3201
4833
  (g) => LockEngine.normalizePattern(this.coordDb.repoRoot, g)
@@ -3389,12 +5021,12 @@ var IntentAndTaskEngine = class {
3389
5021
  };
3390
5022
 
3391
5023
  // src/core/handoffs.ts
3392
- import { execFileSync as execFileSync5 } from "child_process";
3393
- import fs9 from "fs";
5024
+ import { execFileSync as execFileSync8 } from "child_process";
5025
+ import fs10 from "fs";
3394
5026
  var RELEVANT_WINDOW_MS = 14 * 24 * 3600 * 1e3;
3395
5027
  function gitChangedFiles(worktree, repoRoot) {
3396
- if (!worktree || !fs9.existsSync(worktree)) return [];
3397
- const run = (cwd, ...args) => execFileSync5("git", args, {
5028
+ if (!worktree || !fs10.existsSync(worktree)) return [];
5029
+ const run = (cwd, ...args) => execFileSync8("git", args, {
3398
5030
  cwd,
3399
5031
  encoding: "utf8",
3400
5032
  stdio: ["ignore", "pipe", "ignore"],
@@ -3623,22 +5255,22 @@ function buildBrief(input, options = {}) {
3623
5255
  }
3624
5256
 
3625
5257
  // 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";
5258
+ import { execFileSync as execFileSync11 } from "child_process";
5259
+ import crypto11 from "crypto";
5260
+ import fs13 from "fs";
5261
+ import path11 from "path";
3630
5262
 
3631
5263
  // 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";
5264
+ import crypto10 from "crypto";
5265
+ import { execFileSync as execFileSync9 } from "child_process";
5266
+ import fs11 from "fs";
5267
+ import { createRequire as createRequire3 } from "module";
3636
5268
  import os from "os";
3637
- import path8 from "path";
5269
+ import path9 from "path";
3638
5270
  var PRESENCE_TTL_MS = 12 * 60 * 60 * 1e3;
3639
- var require3 = createRequire2(import.meta.url);
5271
+ var require4 = createRequire3(import.meta.url);
3640
5272
  function openSqlite(filePath) {
3641
- const { DatabaseSync } = require3("node:sqlite");
5273
+ const { DatabaseSync } = require4("node:sqlite");
3642
5274
  const db = new DatabaseSync(filePath);
3643
5275
  db.exec("PRAGMA busy_timeout = 3000; PRAGMA journal_mode = WAL;");
3644
5276
  const existingCols = db.prepare("PRAGMA table_info(presence)").all();
@@ -3701,17 +5333,17 @@ function resolveHomeDir(explicitHome) {
3701
5333
  return physicalPath(raw);
3702
5334
  }
3703
5335
  function presenceDbPath(home) {
3704
- return path8.join(resolveHomeDir(home), ".local/share/kith/presence.db");
5336
+ return path9.join(resolveHomeDir(home), ".local/share/kith/presence.db");
3705
5337
  }
3706
5338
  function withPresenceDb(home, create, fn) {
3707
5339
  const file = presenceDbPath(home);
3708
- if (!create && !fs10.existsSync(file)) return null;
3709
- const dir = path8.dirname(file);
5340
+ if (!create && !fs11.existsSync(file)) return null;
5341
+ const dir = path9.dirname(file);
3710
5342
  if (create) {
3711
- fs10.mkdirSync(dir, { recursive: true, mode: 448 });
5343
+ fs11.mkdirSync(dir, { recursive: true, mode: 448 });
3712
5344
  }
3713
5345
  if (physicalPath(dir) !== dir) return null;
3714
- if (fs10.existsSync(file) && physicalPath(file) !== file) return null;
5346
+ if (fs11.existsSync(file) && physicalPath(file) !== file) return null;
3715
5347
  const db = openSqlite(file);
3716
5348
  try {
3717
5349
  return fn(db);
@@ -3798,7 +5430,7 @@ function listRepoPresence(home, repoCommonDir) {
3798
5430
  }
3799
5431
  function deterministicAgentId(client, sessionKey) {
3800
5432
  const cleanClient = client.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase() || "agent";
3801
- const hash = crypto9.createHash("sha1").update(sessionKey).digest("hex").slice(0, 8);
5433
+ const hash = crypto10.createHash("sha1").update(sessionKey).digest("hex").slice(0, 8);
3802
5434
  return `auto-${cleanClient}-${hash}`;
3803
5435
  }
3804
5436
  function ancestorChain(pid) {
@@ -3807,7 +5439,7 @@ function ancestorChain(pid) {
3807
5439
  let current = pid;
3808
5440
  for (let hop = 0; hop < 16; hop++) {
3809
5441
  try {
3810
- const line = execFileSync6("ps", ["-o", "ppid=", "-p", String(current)], {
5442
+ const line = execFileSync9("ps", ["-o", "ppid=", "-p", String(current)], {
3811
5443
  encoding: "utf8",
3812
5444
  stdio: ["ignore", "pipe", "ignore"],
3813
5445
  timeout: 500
@@ -3829,12 +5461,12 @@ function ownedByCaller(agentPid, callerPid) {
3829
5461
  }
3830
5462
 
3831
5463
  // src/core/gc.ts
3832
- import fs11 from "fs";
3833
- import path9 from "path";
3834
- import { execFileSync as execFileSync7 } from "child_process";
5464
+ import fs12 from "fs";
5465
+ import path10 from "path";
5466
+ import { execFileSync as execFileSync10 } from "child_process";
3835
5467
  function gitStatusDirty(dir) {
3836
5468
  try {
3837
- const out = execFileSync7("git", ["status", "--porcelain"], {
5469
+ const out = execFileSync10("git", ["status", "--porcelain"], {
3838
5470
  cwd: dir,
3839
5471
  encoding: "utf8",
3840
5472
  stdio: ["ignore", "pipe", "pipe"]
@@ -3847,7 +5479,7 @@ function gitStatusDirty(dir) {
3847
5479
  function gitIsMerged(repoRoot, commit) {
3848
5480
  if (!commit) return false;
3849
5481
  try {
3850
- execFileSync7("git", ["merge-base", "--is-ancestor", commit, "HEAD"], {
5482
+ execFileSync10("git", ["merge-base", "--is-ancestor", commit, "HEAD"], {
3851
5483
  cwd: repoRoot,
3852
5484
  stdio: ["ignore", "ignore", "ignore"]
3853
5485
  });
@@ -3859,7 +5491,7 @@ function gitIsMerged(repoRoot, commit) {
3859
5491
  function gitHasCommitSince(repoRoot, sinceMs, files) {
3860
5492
  if (!files.length) return false;
3861
5493
  try {
3862
- const out = execFileSync7(
5494
+ const out = execFileSync10(
3863
5495
  "git",
3864
5496
  ["log", "-1", "--format=%H", `--since=@${Math.floor(sinceMs / 1e3)}`, "--", ...files],
3865
5497
  { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
@@ -3872,7 +5504,7 @@ function gitHasCommitSince(repoRoot, sinceMs, files) {
3872
5504
  function resyncStaleIndexEntries(repoRoot) {
3873
5505
  let cachedPaths = [];
3874
5506
  try {
3875
- const out = execFileSync7("git", ["diff", "--cached", "--name-only", "-z", "HEAD"], {
5507
+ const out = execFileSync10("git", ["diff", "--cached", "--name-only", "-z", "HEAD"], {
3876
5508
  cwd: repoRoot,
3877
5509
  encoding: "utf8",
3878
5510
  stdio: ["ignore", "pipe", "ignore"]
@@ -3883,7 +5515,7 @@ function resyncStaleIndexEntries(repoRoot) {
3883
5515
  }
3884
5516
  if (cachedPaths.length === 0) return 0;
3885
5517
  try {
3886
- execFileSync7("git", ["reset", "-q", "HEAD"], {
5518
+ execFileSync10("git", ["reset", "-q", "HEAD"], {
3887
5519
  cwd: repoRoot,
3888
5520
  stdio: ["ignore", "ignore", "ignore"]
3889
5521
  });
@@ -3897,7 +5529,7 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3897
5529
  const force = Boolean(options.force);
3898
5530
  const staleDays = Number.isFinite(options.staleDays) ? Math.max(0, options.staleDays) : 14;
3899
5531
  const layout = discoverRepository(directory);
3900
- const dbPath = path9.join(layout.coordDir, "state.db");
5532
+ const dbPath = path10.join(layout.coordDir, "state.db");
3901
5533
  const report = {
3902
5534
  ok: true,
3903
5535
  dryRun,
@@ -3915,7 +5547,7 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3915
5547
  prunedDeadAgents: 0,
3916
5548
  prunedArtifacts: 0
3917
5549
  };
3918
- if (!fs11.existsSync(dbPath)) {
5550
+ if (!fs12.existsSync(dbPath)) {
3919
5551
  report.nothingToClean = true;
3920
5552
  return report;
3921
5553
  }
@@ -3959,11 +5591,11 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3959
5591
  const pinnedTaskIds = new Set(
3960
5592
  openHandoffs.map((h) => h.task_id).filter((id) => Boolean(id))
3961
5593
  );
3962
- const worktreesDir = physicalPath(path9.join(layout.coordDir, "worktrees"));
3963
- if (fs11.existsSync(worktreesDir)) {
5594
+ const worktreesDir = physicalPath(path10.join(layout.coordDir, "worktrees"));
5595
+ if (fs12.existsSync(worktreesDir)) {
3964
5596
  if (!dryRun) {
3965
5597
  try {
3966
- execFileSync7("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
5598
+ execFileSync10("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
3967
5599
  } catch {
3968
5600
  }
3969
5601
  }
@@ -3992,43 +5624,43 @@ function gcCoordination(directory = process.cwd(), options = {}) {
3992
5624
  if (removeBranch) report.deletedBranches.push(wt.branch);
3993
5625
  if (!dryRun) {
3994
5626
  try {
3995
- execFileSync7("git", ["worktree", "remove", ...force ? ["--force"] : [], wtPath], {
5627
+ execFileSync10("git", ["worktree", "remove", ...force ? ["--force"] : [], wtPath], {
3996
5628
  cwd: layout.checkoutRoot,
3997
5629
  stdio: ["ignore", "pipe", "pipe"]
3998
5630
  });
3999
5631
  } catch {
4000
- fs11.rmSync(wtPath, { recursive: true, force: true });
5632
+ fs12.rmSync(wtPath, { recursive: true, force: true });
4001
5633
  try {
4002
- execFileSync7("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
5634
+ execFileSync10("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
4003
5635
  } catch {
4004
5636
  }
4005
5637
  }
4006
5638
  if (removeBranch && wt.branch) {
4007
5639
  try {
4008
- execFileSync7("git", ["branch", "-D", wt.branch], { cwd: layout.checkoutRoot, stdio: ["ignore", "pipe", "pipe"] });
5640
+ execFileSync10("git", ["branch", "-D", wt.branch], { cwd: layout.checkoutRoot, stdio: ["ignore", "pipe", "pipe"] });
4009
5641
  } catch {
4010
5642
  }
4011
5643
  }
4012
5644
  }
4013
5645
  }
4014
5646
  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));
5647
+ for (const entry of fs12.readdirSync(worktreesDir)) {
5648
+ const orphan = physicalPath(path10.join(worktreesDir, entry));
4017
5649
  if (remaining.has(orphan) || activeWorktreePaths.has(orphan) || !force && handoffWorktrees.has(orphan)) continue;
4018
5650
  report.removedWorktrees.push(orphan);
4019
- if (!dryRun) fs11.rmSync(orphan, { recursive: true, force: true });
5651
+ if (!dryRun) fs12.rmSync(orphan, { recursive: true, force: true });
4020
5652
  }
4021
5653
  }
4022
5654
  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);
5655
+ const dir = path10.join(layout.coordDir, dirName);
5656
+ if (!fs12.existsSync(dir)) continue;
5657
+ for (const entry of fs12.readdirSync(dir)) {
5658
+ const full = path10.join(dir, entry);
4027
5659
  try {
4028
- const stat = fs11.lstatSync(full);
5660
+ const stat = fs12.lstatSync(full);
4029
5661
  if (stat.mtimeMs < cutoff) {
4030
5662
  report.prunedArtifacts++;
4031
- if (!dryRun) fs11.rmSync(full, { recursive: true, force: true });
5663
+ if (!dryRun) fs12.rmSync(full, { recursive: true, force: true });
4032
5664
  }
4033
5665
  } catch {
4034
5666
  }
@@ -4103,26 +5735,26 @@ function sleepSync(ms) {
4103
5735
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
4104
5736
  }
4105
5737
  function withCommitLock(coordDir, fn, timeoutMs = 15e3) {
4106
- fs12.mkdirSync(coordDir, { recursive: true, mode: 448 });
4107
- const lockPath = path10.join(coordDir, "commit.lock");
5738
+ fs13.mkdirSync(coordDir, { recursive: true, mode: 448 });
5739
+ const lockPath = path11.join(coordDir, "commit.lock");
4108
5740
  const started = Date.now();
4109
5741
  let fd;
4110
5742
  while (true) {
4111
5743
  try {
4112
- fd = fs12.openSync(lockPath, "wx", 384);
4113
- fs12.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
5744
+ fd = fs13.openSync(lockPath, "wx", 384);
5745
+ fs13.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
4114
5746
  break;
4115
5747
  } catch (err) {
4116
5748
  if (err.code !== "EEXIST") throw err;
4117
5749
  try {
4118
- const raw = JSON.parse(fs12.readFileSync(lockPath, "utf8"));
5750
+ const raw = JSON.parse(fs13.readFileSync(lockPath, "utf8"));
4119
5751
  if (raw.pid && raw.pid > 0) {
4120
5752
  try {
4121
5753
  process.kill(raw.pid, 0);
4122
5754
  } catch (killErr) {
4123
5755
  if (killErr.code === "ESRCH") {
4124
5756
  try {
4125
- fs12.unlinkSync(lockPath);
5757
+ fs13.unlinkSync(lockPath);
4126
5758
  continue;
4127
5759
  } catch {
4128
5760
  }
@@ -4142,40 +5774,16 @@ function withCommitLock(coordDir, fn, timeoutMs = 15e3) {
4142
5774
  } finally {
4143
5775
  if (fd !== void 0) {
4144
5776
  try {
4145
- fs12.closeSync(fd);
5777
+ fs13.closeSync(fd);
4146
5778
  } catch {
4147
5779
  }
4148
5780
  }
4149
5781
  try {
4150
- fs12.unlinkSync(lockPath);
5782
+ fs13.unlinkSync(lockPath);
4151
5783
  } catch {
4152
5784
  }
4153
5785
  }
4154
5786
  }
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
5787
  function commitScopedFiles(engine, params) {
4180
5788
  const message = (params.message ?? "").trim();
4181
5789
  if (!message) {
@@ -4224,7 +5832,7 @@ function commitScopedFiles(engine, params) {
4224
5832
  }
4225
5833
  }
4226
5834
  for (const peer of presencePeers) {
4227
- const digest = crypto10.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
5835
+ const digest = crypto11.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
4228
5836
  const autoId = `auto-${peer.client}-${digest}`;
4229
5837
  if (!params.agentId || params.agentId === autoId) {
4230
5838
  callerAgentIds.add(autoId);
@@ -4248,7 +5856,6 @@ function commitScopedFiles(engine, params) {
4248
5856
  const primaryAgentId = params.agentId ?? [...callerAgentIds][0] ?? null;
4249
5857
  const worktreeRoot = (primaryAgentId ? engine.fencing.getAgent(primaryAgentId)?.worktree_path : null) ?? engine.coordDb.repoRoot;
4250
5858
  const dirtyFiles = listDirtyFiles(worktreeRoot);
4251
- const dirtySet = new Set(dirtyFiles);
4252
5859
  const activeLocks = engine.locks.listLocks();
4253
5860
  let targetFiles = [];
4254
5861
  if (params.files && params.files.length > 0) {
@@ -4256,42 +5863,14 @@ function commitScopedFiles(engine, params) {
4256
5863
  new Set(params.files.map((f) => LockEngine.normalizeFile(worktreeRoot, f)))
4257
5864
  );
4258
5865
  } 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));
5866
+ targetFiles = collectRecordedFiles({
5867
+ worktreeRoot,
5868
+ callerAgentIds,
5869
+ locks: activeLocks,
5870
+ tasks: engine.intents.listTasks(),
5871
+ presenceTouched: presencePeers.flatMap((peer) => peer.touchedFiles),
5872
+ dirtyFiles
5873
+ });
4295
5874
  }
4296
5875
  if (targetFiles.length === 0) {
4297
5876
  return {
@@ -4321,10 +5900,22 @@ function commitScopedFiles(engine, params) {
4321
5900
  }
4322
5901
  }
4323
5902
  }
5903
+ const leaseError = waitForSharedRefLease(engine.coordDb.coordDir, primaryAgentId);
5904
+ if (leaseError) {
5905
+ return {
5906
+ ok: false,
5907
+ commit: null,
5908
+ branch: null,
5909
+ files: [],
5910
+ agentId: primaryAgentId,
5911
+ message,
5912
+ error: leaseError
5913
+ };
5914
+ }
4324
5915
  return withCommitLock(engine.coordDb.coordDir, () => {
4325
5916
  let headBefore = null;
4326
5917
  try {
4327
- headBefore = execFileSync8("git", ["rev-parse", "--verify", "HEAD"], {
5918
+ headBefore = execFileSync11("git", ["rev-parse", "--verify", "HEAD"], {
4328
5919
  cwd: worktreeRoot,
4329
5920
  encoding: "utf8",
4330
5921
  stdio: ["ignore", "pipe", "ignore"]
@@ -4334,7 +5925,7 @@ function commitScopedFiles(engine, params) {
4334
5925
  }
4335
5926
  let branch = null;
4336
5927
  try {
4337
- branch = execFileSync8("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
5928
+ branch = execFileSync11("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
4338
5929
  cwd: worktreeRoot,
4339
5930
  encoding: "utf8",
4340
5931
  stdio: ["ignore", "pipe", "ignore"]
@@ -4342,32 +5933,32 @@ function commitScopedFiles(engine, params) {
4342
5933
  } catch {
4343
5934
  branch = null;
4344
5935
  }
4345
- const tempIndex = path10.join(
5936
+ const tempIndex = path11.join(
4346
5937
  engine.coordDb.coordDir,
4347
5938
  "shadow-index",
4348
- `commit-${process.pid}-${crypto10.randomBytes(6).toString("hex")}.index`
5939
+ `commit-${process.pid}-${crypto11.randomBytes(6).toString("hex")}.index`
4349
5940
  );
4350
- fs12.mkdirSync(path10.dirname(tempIndex), { recursive: true, mode: 448 });
5941
+ fs13.mkdirSync(path11.dirname(tempIndex), { recursive: true, mode: 448 });
4351
5942
  const gitEnv = { ...process.env, GIT_INDEX_FILE: tempIndex };
4352
5943
  try {
4353
5944
  if (headBefore) {
4354
- execFileSync8("git", ["read-tree", headBefore], {
5945
+ execFileSync11("git", ["read-tree", headBefore], {
4355
5946
  cwd: worktreeRoot,
4356
5947
  env: gitEnv,
4357
5948
  stdio: ["ignore", "pipe", "pipe"]
4358
5949
  });
4359
5950
  }
4360
- execFileSync8("git", ["add", "-A", "--", ...targetFiles], {
5951
+ execFileSync11("git", ["add", "-A", "--", ...targetFiles], {
4361
5952
  cwd: worktreeRoot,
4362
5953
  env: gitEnv,
4363
5954
  stdio: ["ignore", "pipe", "pipe"]
4364
5955
  });
4365
- const diffOut = headBefore ? execFileSync8("git", ["diff-index", "--cached", "--name-only", "-z", headBefore], {
5956
+ const diffOut = headBefore ? execFileSync11("git", ["diff-index", "--cached", "--name-only", "-z", headBefore], {
4366
5957
  cwd: worktreeRoot,
4367
5958
  env: gitEnv,
4368
5959
  encoding: "utf8",
4369
5960
  stdio: ["ignore", "pipe", "pipe"]
4370
- }) : execFileSync8("git", ["ls-files", "--cached", "-z"], {
5961
+ }) : execFileSync11("git", ["ls-files", "--cached", "-z"], {
4371
5962
  cwd: worktreeRoot,
4372
5963
  env: gitEnv,
4373
5964
  encoding: "utf8",
@@ -4385,28 +5976,28 @@ function commitScopedFiles(engine, params) {
4385
5976
  error: "Specified files have no changes relative to HEAD."
4386
5977
  };
4387
5978
  }
4388
- const treeSha = execFileSync8("git", ["write-tree"], {
5979
+ const treeSha = execFileSync11("git", ["write-tree"], {
4389
5980
  cwd: worktreeRoot,
4390
5981
  env: gitEnv,
4391
5982
  encoding: "utf8",
4392
5983
  stdio: ["ignore", "pipe", "pipe"]
4393
5984
  }).trim();
4394
5985
  const commitArgs = ["commit-tree", treeSha, ...headBefore ? ["-p", headBefore] : [], "-m", message];
4395
- const commitSha = execFileSync8("git", commitArgs, {
5986
+ const commitSha = execFileSync11("git", commitArgs, {
4396
5987
  cwd: worktreeRoot,
4397
5988
  env: gitEnv,
4398
5989
  encoding: "utf8",
4399
5990
  stdio: ["ignore", "pipe", "pipe"]
4400
5991
  }).trim();
4401
- const subject = message.split(/\r?\n/, 1)[0];
5992
+ const subject2 = message.split(/\r?\n/, 1)[0];
4402
5993
  const oldRef = headBefore ?? "0000000000000000000000000000000000000000";
4403
- execFileSync8("git", ["update-ref", "-m", `commit: ${subject}`, "HEAD", commitSha, oldRef], {
5994
+ execFileSync11("git", ["update-ref", "-m", `commit: ${subject2}`, "HEAD", commitSha, oldRef], {
4404
5995
  cwd: worktreeRoot,
4405
5996
  stdio: ["ignore", "pipe", "pipe"]
4406
5997
  });
4407
5998
  for (let attempt = 0; attempt < 5; attempt++) {
4408
5999
  try {
4409
- execFileSync8("git", ["reset", "-q", "HEAD", "--", ...committedFiles], {
6000
+ execFileSync11("git", ["reset", "-q", "HEAD", "--", ...committedFiles], {
4410
6001
  cwd: worktreeRoot,
4411
6002
  stdio: ["ignore", "pipe", "pipe"]
4412
6003
  });
@@ -4420,7 +6011,7 @@ function commitScopedFiles(engine, params) {
4420
6011
  commit: commitSha,
4421
6012
  branch,
4422
6013
  files: committedFiles,
4423
- message: subject
6014
+ message: subject2
4424
6015
  });
4425
6016
  return {
4426
6017
  ok: true,
@@ -4432,7 +6023,7 @@ function commitScopedFiles(engine, params) {
4432
6023
  };
4433
6024
  } finally {
4434
6025
  try {
4435
- fs12.unlinkSync(tempIndex);
6026
+ fs13.unlinkSync(tempIndex);
4436
6027
  } catch {
4437
6028
  }
4438
6029
  }
@@ -4449,10 +6040,10 @@ function parseWorkflowMode(value) {
4449
6040
  }
4450
6041
 
4451
6042
  // 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";
6043
+ import { execFileSync as execFileSync12, execSync } from "child_process";
6044
+ import crypto12 from "crypto";
6045
+ import fs14 from "fs";
6046
+ import path12 from "path";
4456
6047
  function runVerificationCommand(command, cwd, env, timeoutMs = Number(process.env.KITH_MERGE_VERIFY_TIMEOUT_MS) || 3e5) {
4457
6048
  try {
4458
6049
  const out = execSync(command, {
@@ -4489,7 +6080,7 @@ var SpeculativeMergeTrain = class {
4489
6080
  this.fencing.assertSession(params.agentId);
4490
6081
  const sessionEnv = this.fencing.sessionEnvironment(params.agentId);
4491
6082
  const now = Date.now();
4492
- const id = `mrg_${crypto11.randomBytes(6).toString("hex")}`;
6083
+ const id = `mrg_${crypto12.randomBytes(6).toString("hex")}`;
4493
6084
  const token = this.coordDb.nextFencingToken();
4494
6085
  this.coordDb.withTransaction(() => {
4495
6086
  this.fencing.assertSession(params.agentId);
@@ -4511,16 +6102,16 @@ var SpeculativeMergeTrain = class {
4511
6102
  now
4512
6103
  );
4513
6104
  });
4514
- const stageDir = path11.join(this.coordDb.coordDir, "worktrees", `_merge_train_${id}`);
4515
- const lockPath = path11.join(this.coordDb.coordDir, "merge-train.lock");
6105
+ const stageDir = path12.join(this.coordDb.coordDir, "worktrees", `_merge_train_${id}`);
6106
+ const lockPath = path12.join(this.coordDb.coordDir, "merge-train.lock");
4516
6107
  let lockFd;
4517
6108
  const waitMs = Math.max(0, params.waitTimeoutMs ?? 0);
4518
6109
  const lockDeadline = Date.now() + waitMs;
4519
6110
  try {
4520
6111
  while (lockFd === void 0) {
4521
6112
  try {
4522
- lockFd = fs13.openSync(lockPath, "wx", 384);
4523
- fs13.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, entryId: id }));
6113
+ lockFd = fs14.openSync(lockPath, "wx", 384);
6114
+ fs14.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, entryId: id }));
4524
6115
  } catch {
4525
6116
  if (Date.now() >= lockDeadline) {
4526
6117
  throw new Error("Merge train is busy. If its owner crashed, inspect .coord/merge-train.lock before removing it.");
@@ -4542,13 +6133,13 @@ var SpeculativeMergeTrain = class {
4542
6133
  }
4543
6134
  }
4544
6135
  if (params.worktreePath) {
4545
- const statusOut = execFileSync9("git", ["status", "--porcelain"], {
6136
+ const statusOut = execFileSync12("git", ["status", "--porcelain"], {
4546
6137
  cwd: params.worktreePath,
4547
6138
  encoding: "utf8"
4548
6139
  }).trim();
4549
6140
  if (statusOut.length > 0) {
4550
- execFileSync9("git", ["add", "-A"], { cwd: params.worktreePath, env: sessionEnv, stdio: "ignore" });
4551
- execFileSync9(
6141
+ execFileSync12("git", ["add", "-A"], { cwd: params.worktreePath, env: sessionEnv, stdio: "ignore" });
6142
+ execFileSync12(
4552
6143
  "git",
4553
6144
  [
4554
6145
  "commit",
@@ -4559,25 +6150,25 @@ var SpeculativeMergeTrain = class {
4559
6150
  );
4560
6151
  }
4561
6152
  }
4562
- const sourceSha = execFileSync9("git", ["rev-parse", "--verify", "--end-of-options", `${params.branch}^{commit}`], {
6153
+ const sourceSha = execFileSync12("git", ["rev-parse", "--verify", "--end-of-options", `${params.branch}^{commit}`], {
4563
6154
  cwd: this.coordDb.repoRoot,
4564
6155
  encoding: "utf8",
4565
6156
  stdio: ["ignore", "pipe", "pipe"]
4566
6157
  }).trim();
4567
6158
  this.requireNoTargetOverlap(this.pathsChangedBySource(sourceSha));
4568
6159
  this.cleanupStageWorktree(stageDir);
4569
- execFileSync9("git", ["worktree", "add", "--detach", stageDir, baseHead], {
6160
+ execFileSync12("git", ["worktree", "add", "--detach", stageDir, baseHead], {
4570
6161
  cwd: this.coordDb.repoRoot,
4571
6162
  stdio: "ignore"
4572
6163
  });
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);
6164
+ const rootNodeModules = path12.join(this.coordDb.repoRoot, "node_modules");
6165
+ const stageNodeModules = path12.join(stageDir, "node_modules");
6166
+ const hydratedNodeModules = fs14.existsSync(rootNodeModules) && !fs14.existsSync(stageNodeModules);
4576
6167
  if (hydratedNodeModules) {
4577
- fs13.symlinkSync(rootNodeModules, stageNodeModules, process.platform === "win32" ? "junction" : "dir");
6168
+ fs14.symlinkSync(rootNodeModules, stageNodeModules, process.platform === "win32" ? "junction" : "dir");
4578
6169
  }
4579
6170
  try {
4580
- execFileSync9(
6171
+ execFileSync12(
4581
6172
  "git",
4582
6173
  ["merge", "--no-ff", "-m", `Merge branch '${params.branch}' (${params.agentId})`, sourceSha],
4583
6174
  {
@@ -4588,7 +6179,7 @@ var SpeculativeMergeTrain = class {
4588
6179
  }
4589
6180
  );
4590
6181
  } catch {
4591
- const conflictedFiles = execFileSync9("git", ["diff", "--name-only", "--diff-filter=U", "-z"], {
6182
+ const conflictedFiles = execFileSync12("git", ["diff", "--name-only", "--diff-filter=U", "-z"], {
4592
6183
  cwd: stageDir,
4593
6184
  encoding: "utf8"
4594
6185
  }).split("\0").filter(Boolean);
@@ -4599,11 +6190,11 @@ var SpeculativeMergeTrain = class {
4599
6190
  if (params.verificationCmd) {
4600
6191
  diagnostics = runVerificationCommand(params.verificationCmd, stageDir, sessionEnv, params.verificationTimeoutMs);
4601
6192
  }
4602
- const stageChanges = execFileSync9("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6193
+ const stageChanges = execFileSync12("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
4603
6194
  cwd: stageDir,
4604
6195
  encoding: "utf8"
4605
6196
  }).split("\0").filter(Boolean);
4606
- const unchangedHydration = hydratedNodeModules && fs13.lstatSync(stageNodeModules, { throwIfNoEntry: false })?.isSymbolicLink() && physicalPath(stageNodeModules) === physicalPath(rootNodeModules);
6197
+ const unchangedHydration = hydratedNodeModules && fs14.lstatSync(stageNodeModules, { throwIfNoEntry: false })?.isSymbolicLink() && physicalPath(stageNodeModules) === physicalPath(rootNodeModules);
4607
6198
  if (this.gitHead(stageDir) !== verifiedSha || stageChanges.some((change) => !(unchangedHydration && change === "?? node_modules"))) {
4608
6199
  throw new Error("Verification changed the staging checkout. Apply fixes in the source worktree and retry with a read-only check.");
4609
6200
  }
@@ -4612,7 +6203,7 @@ var SpeculativeMergeTrain = class {
4612
6203
  }
4613
6204
  this.fencing.assertSession(params.agentId);
4614
6205
  this.requireNoTargetOverlap(this.pathsBetween(baseHead, verifiedSha));
4615
- execFileSync9("git", ["merge", "--ff-only", verifiedSha], {
6206
+ execFileSync12("git", ["merge", "--ff-only", verifiedSha], {
4616
6207
  cwd: this.coordDb.repoRoot,
4617
6208
  stdio: "ignore"
4618
6209
  });
@@ -4660,16 +6251,16 @@ var SpeculativeMergeTrain = class {
4660
6251
  };
4661
6252
  } finally {
4662
6253
  if (lockFd !== void 0) {
4663
- fs13.closeSync(lockFd);
4664
- fs13.unlinkSync(lockPath);
6254
+ fs14.closeSync(lockFd);
6255
+ fs14.unlinkSync(lockPath);
4665
6256
  }
4666
6257
  }
4667
6258
  }
4668
6259
  gitHead(cwd) {
4669
- return execFileSync9("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
6260
+ return execFileSync12("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
4670
6261
  }
4671
6262
  gitBranch(cwd) {
4672
- return execFileSync9("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
6263
+ return execFileSync12("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
4673
6264
  cwd,
4674
6265
  encoding: "utf8",
4675
6266
  stdio: ["ignore", "pipe", "ignore"]
@@ -4677,7 +6268,7 @@ var SpeculativeMergeTrain = class {
4677
6268
  }
4678
6269
  /** Paths with uncommitted changes in the target checkout. Untracked directories end in `/`. Kith's own state is excluded. */
4679
6270
  dirtyTargetPaths() {
4680
- const records = execFileSync9("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6271
+ const records = execFileSync12("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
4681
6272
  cwd: this.coordDb.repoRoot,
4682
6273
  encoding: "utf8"
4683
6274
  }).split("\0").filter(Boolean);
@@ -4690,7 +6281,7 @@ var SpeculativeMergeTrain = class {
4690
6281
  return paths;
4691
6282
  }
4692
6283
  diffNames(...refs) {
4693
- return execFileSync9("git", ["diff", "--name-only", "-z", "--no-renames", ...refs], {
6284
+ return execFileSync12("git", ["diff", "--name-only", "-z", "--no-renames", ...refs], {
4694
6285
  cwd: this.coordDb.repoRoot,
4695
6286
  encoding: "utf8"
4696
6287
  }).split("\0").filter(Boolean);
@@ -4698,7 +6289,7 @@ var SpeculativeMergeTrain = class {
4698
6289
  /** Paths a merge of `sourceSha` will bring into the target: the source's own changes since the merge base. */
4699
6290
  pathsChangedBySource(sourceSha) {
4700
6291
  try {
4701
- const base = execFileSync9("git", ["merge-base", "HEAD", sourceSha], {
6292
+ const base = execFileSync12("git", ["merge-base", "HEAD", sourceSha], {
4702
6293
  cwd: this.coordDb.repoRoot,
4703
6294
  encoding: "utf8",
4704
6295
  stdio: ["ignore", "pipe", "ignore"]
@@ -4727,18 +6318,18 @@ var SpeculativeMergeTrain = class {
4727
6318
  }
4728
6319
  }
4729
6320
  cleanupStageWorktree(stageDir) {
4730
- if (!fs13.existsSync(stageDir)) return;
6321
+ if (!fs14.existsSync(stageDir)) return;
4731
6322
  try {
4732
- execFileSync9("git", ["worktree", "remove", "--force", stageDir], {
6323
+ execFileSync12("git", ["worktree", "remove", "--force", stageDir], {
4733
6324
  cwd: this.coordDb.repoRoot,
4734
6325
  stdio: "ignore"
4735
6326
  });
4736
6327
  } catch {
4737
- if (fs13.existsSync(stageDir)) {
4738
- fs13.rmSync(stageDir, { recursive: true, force: true });
6328
+ if (fs14.existsSync(stageDir)) {
6329
+ fs14.rmSync(stageDir, { recursive: true, force: true });
4739
6330
  }
4740
6331
  try {
4741
- execFileSync9("git", ["worktree", "prune"], {
6332
+ execFileSync12("git", ["worktree", "prune"], {
4742
6333
  cwd: this.coordDb.repoRoot,
4743
6334
  stdio: "ignore"
4744
6335
  });
@@ -4756,10 +6347,19 @@ var SpeculativeMergeTrain = class {
4756
6347
  };
4757
6348
 
4758
6349
  // 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";
6350
+ import { execFileSync as execFileSync13 } from "child_process";
6351
+ import crypto13 from "crypto";
6352
+ import fs15 from "fs";
6353
+ import os2 from "os";
6354
+ import path13 from "path";
6355
+ function isGitBlob(value) {
6356
+ return typeof value === "string" && /^[0-9a-f]{40,64}$/i.test(value);
6357
+ }
6358
+ function sameIdSet(left, right) {
6359
+ if (left.length !== right.length) return false;
6360
+ const have = new Set(left);
6361
+ return right.every((id) => have.has(id));
6362
+ }
4763
6363
  var ShadowGitEngine = class {
4764
6364
  constructor(coordDb, fencing) {
4765
6365
  this.coordDb = coordDb;
@@ -4769,7 +6369,7 @@ var ShadowGitEngine = class {
4769
6369
  fencing;
4770
6370
  isGitRepository(dir = this.coordDb.repoRoot) {
4771
6371
  try {
4772
- execFileSync10("git", ["rev-parse", "--is-inside-work-tree"], {
6372
+ execFileSync13("git", ["rev-parse", "--is-inside-work-tree"], {
4773
6373
  cwd: dir,
4774
6374
  stdio: "ignore"
4775
6375
  });
@@ -4780,7 +6380,7 @@ var ShadowGitEngine = class {
4780
6380
  }
4781
6381
  blobAt(commit, filePath) {
4782
6382
  try {
4783
- const out = execFileSync10("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", filePath], { cwd: this.coordDb.repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
6383
+ const out = execFileSync13("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", filePath], { cwd: this.coordDb.repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
4784
6384
  return /^\d+ blob ([0-9a-f]+)\t/.exec(out)?.[1] ?? null;
4785
6385
  } catch {
4786
6386
  return null;
@@ -4788,7 +6388,7 @@ var ShadowGitEngine = class {
4788
6388
  }
4789
6389
  getHeadCommit(dir = this.coordDb.repoRoot) {
4790
6390
  try {
4791
- return execFileSync10("git", ["rev-parse", "HEAD"], {
6391
+ return execFileSync13("git", ["rev-parse", "HEAD"], {
4792
6392
  cwd: dir,
4793
6393
  encoding: "utf8",
4794
6394
  stdio: ["ignore", "pipe", "ignore"]
@@ -4800,7 +6400,7 @@ var ShadowGitEngine = class {
4800
6400
  getShadowIndexPath(agentId) {
4801
6401
  const safeId = agentId.replace(/[^a-zA-Z0-9_-]/g, "_");
4802
6402
  const epoch = this.fencing.assertSession(agentId);
4803
- return path12.join(this.coordDb.coordDir, "shadow-index", `${safeId}-${epoch}.index`);
6403
+ return path13.join(this.coordDb.coordDir, "shadow-index", `${safeId}-${epoch}.index`);
4804
6404
  }
4805
6405
  /**
4806
6406
  * Updates an agent's ephemeral shadow Git index (`.coord/shadow-index/<agent-id>.index`)
@@ -4816,23 +6416,23 @@ var ShadowGitEngine = class {
4816
6416
  if (!headCommit) return null;
4817
6417
  const shadowIndex = this.getShadowIndexPath(params.agentId);
4818
6418
  const env = { ...process.env, GIT_INDEX_FILE: shadowIndex };
4819
- if (!fs14.existsSync(shadowIndex)) {
4820
- execFileSync10("git", ["read-tree", headCommit], {
6419
+ if (!fs15.existsSync(shadowIndex)) {
6420
+ execFileSync13("git", ["read-tree", headCommit], {
4821
6421
  cwd: targetDir,
4822
6422
  env,
4823
6423
  stdio: "ignore"
4824
6424
  });
4825
- fs14.writeFileSync(`${shadowIndex}.base`, headCommit);
6425
+ fs15.writeFileSync(`${shadowIndex}.base`, headCommit);
4826
6426
  } else {
4827
6427
  this.rebaseShadowIndex(shadowIndex, targetDir, env, headCommit);
4828
6428
  }
4829
6429
  if (params.worktreeDir && (!params.modifiedFiles || params.modifiedFiles.length === 0)) {
4830
- execFileSync10("git", ["read-tree", headCommit], {
6430
+ execFileSync13("git", ["read-tree", headCommit], {
4831
6431
  cwd: targetDir,
4832
6432
  env,
4833
6433
  stdio: "ignore"
4834
6434
  });
4835
- execFileSync10("git", ["add", "-A"], {
6435
+ execFileSync13("git", ["add", "-A"], {
4836
6436
  cwd: targetDir,
4837
6437
  env,
4838
6438
  stdio: "ignore"
@@ -4842,34 +6442,34 @@ var ShadowGitEngine = class {
4842
6442
  for (const mod of params.modifiedFiles) {
4843
6443
  const relPath = LockEngine.normalizeFile(targetDir, mod.filePath);
4844
6444
  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);
6445
+ const absPath = path13.join(targetDir, relPath);
6446
+ const content = mod.content ?? (fs15.existsSync(absPath) ? fs15.readFileSync(absPath, "utf8") : null);
4847
6447
  if (content === null) {
4848
6448
  {
4849
- execFileSync10("git", ["--literal-pathspecs", "update-index", "--force-remove", "--", relPath], {
6449
+ execFileSync13("git", ["--literal-pathspecs", "update-index", "--force-remove", "--", relPath], {
4850
6450
  cwd: targetDir,
4851
6451
  env,
4852
6452
  stdio: "ignore"
4853
6453
  });
4854
6454
  }
4855
6455
  } else {
4856
- const tracked = execFileSync10("git", ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", relPath], {
6456
+ const tracked = execFileSync13("git", ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", relPath], {
4857
6457
  cwd: targetDir,
4858
6458
  env,
4859
6459
  encoding: "utf8"
4860
6460
  }).split("\0").find(Boolean);
4861
6461
  const trackedMode = tracked?.split(" ")[0];
4862
- const stat = fs14.existsSync(absPath) ? fs14.lstatSync(absPath) : null;
6462
+ const stat = fs15.existsSync(absPath) ? fs15.lstatSync(absPath) : null;
4863
6463
  if (trackedMode && !["100644", "100755"].includes(trackedMode) || stat?.isSymbolicLink()) {
4864
6464
  throw new Error(`Cannot report symlinks or special entries as source content: ${relPath}`);
4865
6465
  }
4866
6466
  const mode = trackedMode ?? (stat && stat.mode & 73 ? "100755" : "100644");
4867
- const blobSha = execFileSync10("git", ["hash-object", "-w", "--stdin"], {
6467
+ const blobSha = execFileSync13("git", ["hash-object", "-w", "--stdin"], {
4868
6468
  cwd: targetDir,
4869
6469
  input: content,
4870
6470
  encoding: "utf8"
4871
6471
  }).trim();
4872
- execFileSync10(
6472
+ execFileSync13(
4873
6473
  "git",
4874
6474
  ["update-index", "--add", "--cacheinfo", `${mode},${blobSha},${relPath}`],
4875
6475
  {
@@ -4881,12 +6481,12 @@ var ShadowGitEngine = class {
4881
6481
  }
4882
6482
  }
4883
6483
  }
4884
- const treeSha = execFileSync10("git", ["write-tree"], {
6484
+ const treeSha = execFileSync13("git", ["write-tree"], {
4885
6485
  cwd: targetDir,
4886
6486
  env,
4887
6487
  encoding: "utf8"
4888
6488
  }).trim();
4889
- const shadowCommitSha = execFileSync10(
6489
+ const shadowCommitSha = execFileSync13(
4890
6490
  "git",
4891
6491
  ["commit-tree", treeSha, "-p", headCommit, "-m", `kith-shadow:${params.agentId}`],
4892
6492
  {
@@ -4909,15 +6509,15 @@ var ShadowGitEngine = class {
4909
6509
  const baseFile = `${shadowIndex}.base`;
4910
6510
  let base = "";
4911
6511
  try {
4912
- base = fs14.readFileSync(baseFile, "utf8").trim();
6512
+ base = fs15.readFileSync(baseFile, "utf8").trim();
4913
6513
  } catch {
4914
6514
  }
4915
6515
  if (base === head) return;
4916
6516
  try {
4917
6517
  if (base) {
4918
- const raw = execFileSync10("git", ["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head], { cwd: dir, encoding: "utf8" }).split("\0");
6518
+ const raw = execFileSync13("git", ["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head], { cwd: dir, encoding: "utf8" }).split("\0");
4919
6519
  const staged = /* @__PURE__ */ new Map();
4920
- for (const line of execFileSync10("git", ["ls-files", "--stage", "-z"], { cwd: dir, env, encoding: "utf8" }).split("\0")) {
6520
+ for (const line of execFileSync13("git", ["ls-files", "--stage", "-z"], { cwd: dir, env, encoding: "utf8" }).split("\0")) {
4921
6521
  const m = /^\d+ ([0-9a-f]+) \d\t([\s\S]+)$/.exec(line);
4922
6522
  if (m) staged.set(m[2], m[1]);
4923
6523
  }
@@ -4932,9 +6532,9 @@ var ShadowGitEngine = class {
4932
6532
  const untouched = oldSha === zero ? mine === void 0 : mine === oldSha;
4933
6533
  if (untouched) info.push(newSha === zero ? `0 ${zero} ${file}` : `${newMode} ${newSha} ${file}`);
4934
6534
  }
4935
- if (info.length) execFileSync10("git", ["update-index", "--index-info", "-z"], { cwd: dir, env, input: info.join("\0") + "\0", stdio: ["pipe", "ignore", "ignore"] });
6535
+ if (info.length) execFileSync13("git", ["update-index", "--index-info", "-z"], { cwd: dir, env, input: info.join("\0") + "\0", stdio: ["pipe", "ignore", "ignore"] });
4936
6536
  }
4937
- fs14.writeFileSync(baseFile, head);
6537
+ fs15.writeFileSync(baseFile, head);
4938
6538
  } catch {
4939
6539
  }
4940
6540
  }
@@ -4980,7 +6580,7 @@ var ShadowGitEngine = class {
4980
6580
  probePairConflict(agentA, commitA, agentB, commitB) {
4981
6581
  this.fencing.assertSession(agentA);
4982
6582
  try {
4983
- const stdout = execFileSync10(
6583
+ const stdout = execFileSync13(
4984
6584
  "git",
4985
6585
  ["merge-tree", "--write-tree", "-z", commitA, commitB],
4986
6586
  {
@@ -5023,7 +6623,7 @@ var ShadowGitEngine = class {
5023
6623
  if (committed && (stages.stage2 === committed || stages.stage3 === committed)) continue;
5024
6624
  const severity = "text_conflict";
5025
6625
  const record = {
5026
- id: `conf_${crypto12.randomBytes(6).toString("hex")}`,
6626
+ id: `conf_${crypto13.randomBytes(6).toString("hex")}`,
5027
6627
  agent_a: agentA,
5028
6628
  agent_b: agentB,
5029
6629
  file_path: filePath,
@@ -5072,8 +6672,8 @@ var ShadowGitEngine = class {
5072
6672
  }
5073
6673
  /** Remove orphaned shadow Git index files left behind by dead or completed sessions. */
5074
6674
  pruneStaleShadowIndexes(dryRun = false) {
5075
- const indexDir = path12.join(this.coordDb.coordDir, "shadow-index");
5076
- if (!fs14.existsSync(indexDir)) return 0;
6675
+ const indexDir = path13.join(this.coordDb.coordDir, "shadow-index");
6676
+ if (!fs15.existsSync(indexDir)) return 0;
5077
6677
  const activeRows = this.coordDb.db.prepare(`
5078
6678
  SELECT a.id AS agent_id, s.epoch AS epoch
5079
6679
  FROM agents a JOIN agent_sessions s ON a.id = s.agent_id
@@ -5081,22 +6681,210 @@ var ShadowGitEngine = class {
5081
6681
  `).all();
5082
6682
  const keep = new Set(activeRows.map((r) => `${r.agent_id.replace(/[^a-zA-Z0-9_-]/g, "_")}-${r.epoch}.index`));
5083
6683
  let removed = 0;
5084
- for (const entry of fs14.readdirSync(indexDir, { withFileTypes: true })) {
6684
+ for (const entry of fs15.readdirSync(indexDir, { withFileTypes: true })) {
5085
6685
  if (!entry.isFile() || !entry.name.endsWith(".index") || keep.has(entry.name)) continue;
5086
6686
  if (dryRun) {
5087
6687
  removed++;
5088
6688
  continue;
5089
6689
  }
5090
6690
  try {
5091
- fs14.unlinkSync(path12.join(indexDir, entry.name));
6691
+ fs15.unlinkSync(path13.join(indexDir, entry.name));
5092
6692
  removed++;
5093
6693
  } catch {
5094
6694
  }
5095
6695
  }
5096
6696
  return removed;
5097
6697
  }
6698
+ /** Counts from the most recent {@link pruneFalseConflicts} call. Tests assert the probe budget. */
6699
+ lastConflictHygiene = {
6700
+ mergeFileProbes: 0,
6701
+ headReads: 0,
6702
+ removed: 0,
6703
+ probeDir: null
6704
+ };
6705
+ /**
6706
+ * Drop stored conflicts that are no longer real. 0.1.8 already refuses to record a side equal
6707
+ * to HEAD, or two identical sides, while probing. Rows written before that commit, or before
6708
+ * HEAD moved, stay until something reads them. `git merge-file` runs only for triples not
6709
+ * already settled, at most `maxMergeProbes` per call, and the decision is cached by HEAD sha
6710
+ * plus conflict id so a later status read does not spawn those processes again. Probe files
6711
+ * live in the system temp directory and are removed before this returns.
6712
+ */
6713
+ pruneFalseConflicts(maxMergeProbes = 100) {
6714
+ const stats = { mergeFileProbes: 0, headReads: 0, removed: 0, probeDir: null };
6715
+ this.lastConflictHygiene = stats;
6716
+ const rows = this.coordDb.db.prepare("SELECT * FROM conflicts").all();
6717
+ if (!rows.length) return 0;
6718
+ const parsed = rows.map((row) => {
6719
+ let details = { reason: "" };
6720
+ try {
6721
+ details = JSON.parse(String(row.details_json));
6722
+ } catch {
6723
+ }
6724
+ return {
6725
+ id: String(row.id),
6726
+ file: String(row.file_path),
6727
+ severity: String(row.severity),
6728
+ details
6729
+ };
6730
+ });
6731
+ const doomed = /* @__PURE__ */ new Set();
6732
+ for (const row of parsed) {
6733
+ const { blobA, blobB } = row.details;
6734
+ if (row.severity === "text_conflict" && isGitBlob(blobA) && blobA === blobB) doomed.add(row.id);
6735
+ }
6736
+ const cache = this.readHygieneCache();
6737
+ const head = this.getHeadCommit();
6738
+ const headChecked = new Set(cache.head === head ? cache.headChecked : []);
6739
+ const mergeSettled = new Set(cache.mergeSettled);
6740
+ 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));
6741
+ if (needHead.length) {
6742
+ const atHead = head ? this.blobsAtCommit(head, [...new Set(needHead.map((row) => row.file))], stats) : null;
6743
+ if (atHead) {
6744
+ for (const row of needHead) {
6745
+ const committed = atHead.get(row.file) ?? null;
6746
+ if (committed && (row.details.blobA === committed || row.details.blobB === committed)) doomed.add(row.id);
6747
+ headChecked.add(row.id);
6748
+ }
6749
+ }
6750
+ }
6751
+ 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));
6752
+ const batch = needMerge.slice(0, Math.max(0, maxMergeProbes));
6753
+ if (batch.length) {
6754
+ const dir = fs15.mkdtempSync(path13.join(this.mergeProbeParent(), "kith-merge-probe-"));
6755
+ stats.probeDir = dir;
6756
+ try {
6757
+ for (const row of batch) {
6758
+ stats.mergeFileProbes++;
6759
+ const merged = this.blobsMergeCleanly(dir, row.details.baseBlob, row.details.blobA, row.details.blobB);
6760
+ if (merged === "clean") doomed.add(row.id);
6761
+ else if (merged === "conflict") mergeSettled.add(row.id);
6762
+ }
6763
+ } finally {
6764
+ fs15.rmSync(dir, { recursive: true, force: true });
6765
+ }
6766
+ }
6767
+ for (const row of parsed) {
6768
+ if (doomed.has(row.id)) continue;
6769
+ const probeable = row.severity === "text_conflict" && isGitBlob(row.details.baseBlob) && isGitBlob(row.details.blobA) && isGitBlob(row.details.blobB);
6770
+ if (!probeable) mergeSettled.add(row.id);
6771
+ }
6772
+ if (doomed.size) {
6773
+ this.coordDb.withTransaction(() => {
6774
+ const del = this.coordDb.db.prepare("DELETE FROM conflicts WHERE id = ?");
6775
+ for (const id of doomed) del.run(id);
6776
+ });
6777
+ }
6778
+ stats.removed = doomed.size;
6779
+ const remain = new Set(parsed.filter((row) => !doomed.has(row.id)).map((row) => row.id));
6780
+ const nextCache = {
6781
+ head,
6782
+ headChecked: [...headChecked].filter((id) => remain.has(id)),
6783
+ mergeSettled: [...mergeSettled].filter((id) => remain.has(id))
6784
+ };
6785
+ if (doomed.size || !sameIdSet(cache.headChecked, nextCache.headChecked) || !sameIdSet(cache.mergeSettled, nextCache.mergeSettled) || cache.head !== head) {
6786
+ this.writeHygieneCache(nextCache);
6787
+ }
6788
+ return doomed.size;
6789
+ }
6790
+ blobsAtCommit(commit, files, stats) {
6791
+ const found = /* @__PURE__ */ new Map();
6792
+ try {
6793
+ for (let offset = 0; offset < files.length; offset += 200) {
6794
+ const chunk = files.slice(offset, offset + 200);
6795
+ stats.headReads++;
6796
+ const out = execFileSync13("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", ...chunk], {
6797
+ cwd: this.coordDb.repoRoot,
6798
+ encoding: "utf8",
6799
+ stdio: ["ignore", "pipe", "ignore"],
6800
+ maxBuffer: 8 * 1024 * 1024
6801
+ });
6802
+ for (const line of out.split("\0")) {
6803
+ const match = /^\d+ blob ([0-9a-f]+)\t([\s\S]+)$/.exec(line);
6804
+ if (match) found.set(match[2], match[1]);
6805
+ }
6806
+ }
6807
+ } catch {
6808
+ return null;
6809
+ }
6810
+ for (const file of files) if (!found.has(file)) found.set(file, null);
6811
+ return found;
6812
+ }
6813
+ /** `conflict` is a real overlap. `error` is not cached, so a later read can retry the probe. */
6814
+ blobsMergeCleanly(dir, base, blobA, blobB) {
6815
+ const show = (sha, name) => {
6816
+ const file = path13.join(dir, name);
6817
+ const bytes = execFileSync13("git", ["cat-file", "blob", sha], {
6818
+ cwd: this.coordDb.repoRoot,
6819
+ stdio: ["ignore", "pipe", "ignore"],
6820
+ maxBuffer: 16 * 1024 * 1024
6821
+ });
6822
+ fs15.writeFileSync(file, bytes);
6823
+ return file;
6824
+ };
6825
+ try {
6826
+ const ours = show(blobA, "a");
6827
+ const baseFile = show(base, "base");
6828
+ const theirs = show(blobB, "b");
6829
+ try {
6830
+ execFileSync13("git", ["merge-file", ours, baseFile, theirs], { cwd: dir, stdio: "ignore" });
6831
+ return "clean";
6832
+ } catch (err) {
6833
+ const status = err.status;
6834
+ return typeof status === "number" && status > 0 ? "conflict" : "error";
6835
+ }
6836
+ } catch {
6837
+ return "error";
6838
+ }
6839
+ }
6840
+ /** Prefer the system temp dir. If that lives inside this checkout, step outside it. */
6841
+ mergeProbeParent() {
6842
+ const repo = fs15.realpathSync(this.coordDb.repoRoot);
6843
+ for (const candidate of [os2.tmpdir(), "/tmp", os2.homedir()]) {
6844
+ try {
6845
+ const real = fs15.realpathSync(candidate);
6846
+ const relative = path13.relative(repo, real);
6847
+ if (relative.startsWith("..") || path13.isAbsolute(relative)) return real;
6848
+ } catch {
6849
+ }
6850
+ }
6851
+ return fs15.realpathSync(os2.tmpdir());
6852
+ }
6853
+ hygieneCachePath() {
6854
+ return path13.join(this.coordDb.coordDir, "conflict-hygiene.json");
6855
+ }
6856
+ readHygieneCache() {
6857
+ try {
6858
+ const raw = JSON.parse(fs15.readFileSync(this.hygieneCachePath(), "utf8"));
6859
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
6860
+ return {
6861
+ head: typeof raw.head === "string" || raw.head === null ? raw.head : null,
6862
+ headChecked: strings(raw.headChecked),
6863
+ mergeSettled: strings(raw.mergeSettled)
6864
+ };
6865
+ } catch {
6866
+ return { head: null, headChecked: [], mergeSettled: [] };
6867
+ }
6868
+ }
6869
+ writeHygieneCache(cache) {
6870
+ const file = this.hygieneCachePath();
6871
+ const tmp = `${file}.${process.pid}.tmp`;
6872
+ try {
6873
+ fs15.writeFileSync(tmp, JSON.stringify(cache));
6874
+ fs15.renameSync(tmp, file);
6875
+ } catch {
6876
+ try {
6877
+ fs15.unlinkSync(tmp);
6878
+ } catch {
6879
+ }
6880
+ }
6881
+ }
5098
6882
  listConflicts() {
5099
6883
  this.fencing.reapDeadAgents();
6884
+ try {
6885
+ this.pruneFalseConflicts();
6886
+ } catch {
6887
+ }
5100
6888
  const rows = this.coordDb.db.prepare(`SELECT * FROM conflicts ORDER BY detected_at DESC`).all();
5101
6889
  return rows.map((r) => ({
5102
6890
  id: String(r.id),
@@ -5111,15 +6899,15 @@ var ShadowGitEngine = class {
5111
6899
  };
5112
6900
 
5113
6901
  // src/core/workspace-contracts.ts
5114
- import { execFileSync as execFileSync11 } from "child_process";
5115
- import fs16 from "fs";
5116
- import path14 from "path";
6902
+ import { execFileSync as execFileSync14 } from "child_process";
6903
+ import fs17 from "fs";
6904
+ import path15 from "path";
5117
6905
 
5118
6906
  // src/core/observation.ts
5119
- import crypto13 from "crypto";
5120
- import fs15 from "fs";
5121
- import os2 from "os";
5122
- import path13 from "path";
6907
+ import crypto14 from "crypto";
6908
+ import fs16 from "fs";
6909
+ import os3 from "os";
6910
+ import path14 from "path";
5123
6911
  function extractRecentAgentFiles(rows) {
5124
6912
  const result = {};
5125
6913
  for (const row of rows) {
@@ -5182,36 +6970,36 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5182
6970
  };
5183
6971
  let scratch, db;
5184
6972
  try {
5185
- const file = path13.join(layout.coordDir, "state.db");
6973
+ const file = path14.join(layout.coordDir, "state.db");
5186
6974
  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`);
6975
+ for (let current = fs16.realpathSync.native(directory); isWithin(layout.checkoutRoot, current); current = path14.dirname(current)) {
6976
+ const local = path14.join(current, ".coord");
6977
+ if (local !== layout.coordDir && fs16.existsSync(path14.join(local, "state.db"))) throw new Error(`Legacy independent state at ${local}; preserve it before consolidation`);
5190
6978
  if (current === layout.checkoutRoot) break;
5191
6979
  }
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);
6980
+ if (!fs16.existsSync(file)) {
6981
+ if (["setup.lock", "merge-train.lock"].some((name) => fs16.existsSync(path14.join(layout.coordDir, name))) || ["-wal", "-shm", "-journal"].some((s) => fs16.existsSync(file + s)) || ["worktrees", "quarantine", "snapshots", "shadow-index", "setup"].some((name) => {
6982
+ const p = path14.join(layout.coordDir, name);
6983
+ return fs16.existsSync(p) && (!fs16.lstatSync(p).isDirectory() || fs16.readdirSync(p).length > 0);
5196
6984
  })) throw new Error("Missing database with retained sidecars; preserve the recovery set");
5197
6985
  return empty;
5198
6986
  }
5199
6987
  const files = ["", "-wal", "-shm", "-journal"].map((s) => file + s);
5200
6988
  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 });
6989
+ if (!fs16.existsSync(f)) return null;
6990
+ if (physicalPath(f) !== f || !fs16.lstatSync(f).isFile()) throw new Error("Database or sidecar is redirected or not a regular file");
6991
+ const s = fs16.statSync(f, { bigint: true });
5204
6992
  return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
5205
6993
  };
5206
6994
  const before = files.map(identity);
5207
- scratch = fs15.mkdtempSync(path13.join(os2.tmpdir(), "kith-observe-"));
6995
+ scratch = fs16.mkdtempSync(path14.join(os3.tmpdir(), "kith-observe-"));
5208
6996
  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);
6997
+ const target = path14.join(scratch, path14.basename(files[i]));
6998
+ fs16.copyFileSync(files[i], target);
6999
+ fs16.chmodSync(target, 384);
5212
7000
  }
5213
7001
  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 });
7002
+ db = new (sqliteDatabase())(path14.join(scratch, "state.db"), { readOnly: true });
5215
7003
  db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN");
5216
7004
  const schemaVersion = CoordDatabase.inspectSchema(db);
5217
7005
  if (schemaVersion < 2) throw new Error("Offline observation requires schema 2 or newer; preserve state and upgrade with clients stopped");
@@ -5285,7 +7073,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
5285
7073
  return { ...empty, state: "unavailable", error: error instanceof Error ? error.message : String(error) };
5286
7074
  } finally {
5287
7075
  db?.close();
5288
- if (scratch) fs15.rmSync(scratch, { recursive: true, force: true });
7076
+ if (scratch) fs16.rmSync(scratch, { recursive: true, force: true });
5289
7077
  }
5290
7078
  }
5291
7079
  function readBrief(directory = process.cwd(), options = {}) {
@@ -5346,7 +7134,7 @@ function readBrief(directory = process.cwd(), options = {}) {
5346
7134
  if (peers.length) {
5347
7135
  for (const peer of peers) {
5348
7136
  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);
7137
+ const hash = crypto14.createHash("sha1").update(peer.sessionKey).digest("hex").slice(0, 8);
5350
7138
  const autoId = `auto-${cleanClient}-${hash}`;
5351
7139
  const resolvedId = peer.agentId || autoId;
5352
7140
  if (seenAgentIds.has(resolvedId) || seenAgentIds.has(autoId) || seenPids.has(peer.pid) || [...seenPids].some((pid) => ownedByCaller(pid, peer.pid))) {
@@ -5379,19 +7167,19 @@ function readBrief(directory = process.cwd(), options = {}) {
5379
7167
  }, { ...options, scopeGlobs });
5380
7168
  }
5381
7169
  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),
7170
+ const state = readCoordinationState(directory), retainedRoot = path14.join(state.repository.coordDir, "worktrees");
7171
+ const retained = physicalPath(retainedRoot) === retainedRoot && fs16.existsSync(retainedRoot) && fs16.lstatSync(retainedRoot).isDirectory() && !fs16.lstatSync(retainedRoot).isSymbolicLink() ? fs16.readdirSync(retainedRoot, { withFileTypes: true }).map((entry) => ({
7172
+ path: path14.join(retainedRoot, entry.name),
5385
7173
  symlink: entry.isSymbolicLink(),
5386
- agentIds: state.agents.filter((a) => a.worktree_path === path13.join(retainedRoot, entry.name)).map((a) => a.id)
7174
+ agentIds: state.agents.filter((a) => a.worktree_path === path14.join(retainedRoot, entry.name)).map((a) => a.id)
5387
7175
  })) : [];
5388
7176
  return {
5389
7177
  ...state,
5390
7178
  retainedWorktrees: retained,
5391
7179
  expiredClaims: state.locks.filter((lock) => Number(lock.expires_at) <= state.observedAt),
5392
7180
  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")) }
7181
+ setupLock: { path: path14.join(state.repository.coordDir, "setup.lock"), present: fs16.existsSync(path14.join(state.repository.coordDir, "setup.lock")) },
7182
+ integrationLock: { path: path14.join(state.repository.coordDir, "merge-train.lock"), present: fs16.existsSync(path14.join(state.repository.coordDir, "merge-train.lock")) }
5395
7183
  };
5396
7184
  }
5397
7185
 
@@ -5467,8 +7255,8 @@ var MAX_SOURCE_BYTES = 64 * 1024;
5467
7255
  var MAX_REPLY_BYTES = 16 * 1024;
5468
7256
  var MAX_LINKS = 8;
5469
7257
  var MAX_SYMBOLS = 64;
5470
- function git2(root, ...args) {
5471
- return execFileSync11("git", ["-c", "core.fsmonitor=false", ...args], {
7258
+ function git3(root, ...args) {
7259
+ return execFileSync14("git", ["-c", "core.fsmonitor=false", ...args], {
5472
7260
  cwd: root,
5473
7261
  encoding: "utf8",
5474
7262
  stdio: ["ignore", "pipe", "pipe"],
@@ -5478,21 +7266,21 @@ function git2(root, ...args) {
5478
7266
  }).trim();
5479
7267
  }
5480
7268
  function readBounded(file) {
5481
- const fd = fs16.openSync(file, "r");
7269
+ const fd = fs17.openSync(file, "r");
5482
7270
  try {
5483
- const stat = fs16.fstatSync(fd);
7271
+ const stat = fs17.fstatSync(fd);
5484
7272
  if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) throw new Error("Contract/config file exceeds inspection limit or is not a regular file");
5485
7273
  const bytes = Buffer.alloc(MAX_SOURCE_BYTES + 1);
5486
- const size = fs16.readSync(fd, bytes, 0, bytes.length, 0);
7274
+ const size = fs17.readSync(fd, bytes, 0, bytes.length, 0);
5487
7275
  if (size > MAX_SOURCE_BYTES) throw new Error("Contract/config file exceeds inspection limit");
5488
7276
  return bytes.subarray(0, size).toString("utf8");
5489
7277
  } finally {
5490
- fs16.closeSync(fd);
7278
+ fs17.closeSync(fd);
5491
7279
  }
5492
7280
  }
5493
7281
  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);
7282
+ for (const name of [base, `${base}.ts`, `${base}.tsx`, `${base}.d.ts`, `${base}.js`, `${base}.jsx`, path15.join(base, "index.ts"), path15.join(base, "index.js")]) {
7283
+ if (fs17.existsSync(name) && fs17.statSync(name).isFile()) return physicalPath(name);
5496
7284
  }
5497
7285
  }
5498
7286
  function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
@@ -5507,8 +7295,8 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5507
7295
  const activeRoot = layout.checkoutRoot;
5508
7296
  let config = null;
5509
7297
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
5510
- const file = path14.join(activeRoot, name);
5511
- if (!fs16.existsSync(file)) continue;
7298
+ const file = path15.join(activeRoot, name);
7299
+ if (!fs17.existsSync(file)) continue;
5512
7300
  repositoryFile(activeRoot, file);
5513
7301
  config = parseJsoncObject(readBounded(file));
5514
7302
  if (!config) unavailable(`Cannot parse ${name}; aliases were not inspected.`);
@@ -5526,11 +7314,11 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5526
7314
  unavailable("Worktree repository identity differs from the caller.");
5527
7315
  return report;
5528
7316
  }
5529
- const bases = [.../* @__PURE__ */ new Set([activeRoot, caller.checkoutRoot])].map((root) => path14.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : "."));
7317
+ const bases = [.../* @__PURE__ */ new Set([activeRoot, caller.checkoutRoot])].map((root) => path15.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : "."));
5530
7318
  let symbolBudget = MAX_SYMBOLS;
5531
7319
  const aliases = Object.entries(options.paths).sort(([a], [b]) => b.length - a.length);
5532
7320
  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("*", "")))));
7321
+ const externalTargets = (targets) => Array.isArray(targets) && targets.slice(0, 8).some((target) => typeof target === "string" && !isWithin(caller.checkoutRoot, physicalPath(path15.resolve(bases[bases.length - 1], target.replace("*", "")))));
5534
7322
  const selected = imports ? [...new Set(imports)].slice(0, 32) : aliases.slice(0, 32).filter(([a]) => !a.includes("*")).map(([a]) => a);
5535
7323
  if (imports && imports.length > 32) unavailable("Import limit reached; inspection is partial.");
5536
7324
  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 +7341,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5553
7341
  for (const target of targets.slice(0, 8)) {
5554
7342
  if (typeof target !== "string" || (target.match(/\*/g)?.length ?? 0) > 1) continue;
5555
7343
  for (const base of bases) {
5556
- externalFile = resolveFile(path14.resolve(base, target.replace("*", substitution)));
7344
+ externalFile = resolveFile(path15.resolve(base, target.replace("*", substitution)));
5557
7345
  if (externalFile) break;
5558
7346
  }
5559
7347
  if (externalFile) break;
@@ -5563,14 +7351,14 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5563
7351
  continue;
5564
7352
  }
5565
7353
  if (isWithin(activeRoot, externalFile)) continue;
5566
- const sibling = discoverRepository(path14.dirname(externalFile));
7354
+ const sibling = discoverRepository(path15.dirname(externalFile));
5567
7355
  if (!sibling.commonGitDir || sibling.commonGitDir === layout.commonGitDir) {
5568
7356
  unavailable(`'${specifier}' does not select a separate Git repository; no external source was read.`);
5569
7357
  continue;
5570
7358
  }
5571
7359
  const siblingRoot = sibling.checkoutRoot;
5572
7360
  const relative = repositoryFile(siblingRoot, externalFile);
5573
- git2(siblingRoot, "ls-files", "--error-unmatch", "--", relative);
7361
+ git3(siblingRoot, "ls-files", "--error-unmatch", "--", relative);
5574
7362
  if (report.linkedContracts.length >= MAX_LINKS || symbolBudget <= 0) {
5575
7363
  unavailable("Contract/symbol limit reached; inspection is partial.");
5576
7364
  break;
@@ -5588,7 +7376,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5588
7376
  if (!exportsComplete) unavailable(`'${specifier}' exports are partial or re-exported; missing-export checks are unavailable.`);
5589
7377
  let dirtyInCheckout = null;
5590
7378
  try {
5591
- dirtyInCheckout = Boolean(git2(siblingRoot, "status", "--porcelain=v1", "--", relative));
7379
+ dirtyInCheckout = Boolean(git3(siblingRoot, "status", "--porcelain=v1", "--", relative));
5592
7380
  } catch {
5593
7381
  unavailable(`'${specifier}' Git status is unavailable.`);
5594
7382
  }
@@ -5603,7 +7391,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5603
7391
  try {
5604
7392
  const wt = discoverRepository(agent.worktree_path);
5605
7393
  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);
7394
+ const file = path15.join(wt.checkoutRoot, relative);
5607
7395
  repositoryFile(wt.checkoutRoot, file);
5608
7396
  const current = AstAnalyzer.extractExports(readBounded(file));
5609
7397
  const original = new Map(extracted.map((s) => [s.symbolName, s.astHash]));
@@ -5617,7 +7405,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
5617
7405
  }
5618
7406
  }
5619
7407
  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 };
7408
+ const link = { alias: specifier, sourceRepo: siblingRoot, sourceRepoName: path15.basename(siblingRoot), filePath: relative, absolutePath: externalFile, symbols, exportsComplete, ownershipAvailable, dirtyInCheckout, lockedByAgent: locked ? String(locked.owner_agent_id) : null, activeWorktreeDrifts: drifts };
5621
7409
  report.linkedContracts.push(link);
5622
7410
  if (Buffer.byteLength(JSON.stringify(report)) > MAX_REPLY_BYTES - 3e3) {
5623
7411
  report.linkedContracts.pop();
@@ -5659,9 +7447,9 @@ function verifyCrossRepoImportsForFile(params) {
5659
7447
  }
5660
7448
 
5661
7449
  // src/core/worktree-cow.ts
5662
- import { execFileSync as execFileSync12 } from "child_process";
5663
- import fs17 from "fs";
5664
- import path15 from "path";
7450
+ import { execFileSync as execFileSync15 } from "child_process";
7451
+ import fs18 from "fs";
7452
+ import path16 from "path";
5665
7453
  var CoWWorktreeManager = class _CoWWorktreeManager {
5666
7454
  constructor(coordDb, fencing) {
5667
7455
  this.coordDb = coordDb;
@@ -5681,32 +7469,32 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5681
7469
  const safeId = params.agentId.replace(/[^a-zA-Z0-9_-]/g, "-");
5682
7470
  const branch = params.branch ?? `kith/${safeId}`;
5683
7471
  const baseRef = params.baseRef ?? "HEAD";
5684
- const worktreePath = path15.join(this.coordDb.coordDir, "worktrees", safeId);
7472
+ const worktreePath = path16.join(this.coordDb.coordDir, "worktrees", safeId);
5685
7473
  if (!this.fencing.getAgent(params.agentId)) throw new Error(`Unknown agent: ${params.agentId}`);
5686
7474
  if (!safeId || safeId === "." || safeId === "..") throw new Error("Invalid agent ID");
5687
- if (fs17.existsSync(worktreePath)) {
7475
+ if (fs18.existsSync(worktreePath)) {
5688
7476
  throw new Error(`Worktree already exists: ${worktreePath}. Commit or preserve its work before removing it.`);
5689
7477
  }
5690
- fs17.mkdirSync(path15.dirname(worktreePath), { recursive: true });
5691
- execFileSync12("git", ["worktree", "add", "-b", branch, worktreePath, baseRef], {
7478
+ fs18.mkdirSync(path16.dirname(worktreePath), { recursive: true });
7479
+ execFileSync15("git", ["worktree", "add", "-b", branch, worktreePath, baseRef], {
5692
7480
  cwd: this.coordDb.repoRoot,
5693
7481
  stdio: "ignore"
5694
7482
  });
5695
7483
  const hydratedDirs = [];
5696
7484
  let hydrationMethod = "none";
5697
7485
  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;
7486
+ const srcDir = path16.join(this.coordDb.repoRoot, dirName);
7487
+ const destDir = path16.join(worktreePath, dirName);
7488
+ if (!fs18.existsSync(srcDir) || fs18.existsSync(destDir)) continue;
5701
7489
  const method = this.cloneDirectoryCoW(srcDir, destDir);
5702
7490
  if (hydrationMethod !== "copy") hydrationMethod = method;
5703
7491
  hydratedDirs.push(dirName);
5704
7492
  }
5705
7493
  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);
7494
+ const srcEnv = path16.join(this.coordDb.repoRoot, envName);
7495
+ const destEnv = path16.join(worktreePath, envName);
7496
+ if (fs18.existsSync(srcEnv) && !fs18.existsSync(destEnv)) {
7497
+ fs18.copyFileSync(srcEnv, destEnv);
5710
7498
  }
5711
7499
  }
5712
7500
  this.coordDb.withTransaction(() => {
@@ -5732,7 +7520,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5732
7520
  const cowTimeoutMs = Number(process.env.KITH_COW_TIMEOUT_MS) || 6e4;
5733
7521
  if (process.platform === "darwin") {
5734
7522
  try {
5735
- execFileSync12("cp", ["-cR", srcDir, destDir], {
7523
+ execFileSync15("cp", ["-cR", srcDir, destDir], {
5736
7524
  stdio: "ignore",
5737
7525
  timeout: cowTimeoutMs
5738
7526
  });
@@ -5741,7 +7529,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5741
7529
  }
5742
7530
  } else if (process.platform === "linux") {
5743
7531
  try {
5744
- execFileSync12("cp", ["--reflink=always", "-R", srcDir, destDir], {
7532
+ execFileSync15("cp", ["--reflink=always", "-R", srcDir, destDir], {
5745
7533
  stdio: "ignore",
5746
7534
  timeout: cowTimeoutMs
5747
7535
  });
@@ -5749,27 +7537,27 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5749
7537
  } catch {
5750
7538
  }
5751
7539
  }
5752
- fs17.rmSync(destDir, { recursive: true, force: true });
5753
- fs17.cpSync(srcDir, destDir, { recursive: true, dereference: false });
7540
+ fs18.rmSync(destDir, { recursive: true, force: true });
7541
+ fs18.cpSync(srcDir, destDir, { recursive: true, dereference: false });
5754
7542
  return "copy";
5755
7543
  }
5756
7544
  removeWorktree(agentId) {
5757
7545
  this.fencing.assertSession(agentId);
5758
7546
  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;
7547
+ const worktreePath = path16.join(this.coordDb.coordDir, "worktrees", safeId);
7548
+ if (!fs18.existsSync(worktreePath)) return false;
5761
7549
  const registered = this.fencing.getAgent(agentId)?.worktree_path;
5762
7550
  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
7551
  throw new Error("Refusing to remove a worktree that is not exclusively registered to this agent.");
5764
7552
  }
5765
- const status = execFileSync12("git", ["status", "--porcelain", "--untracked-files=normal", "--ignored=matching"], {
7553
+ const status = execFileSync15("git", ["status", "--porcelain", "--untracked-files=normal", "--ignored=matching"], {
5766
7554
  cwd: worktreePath,
5767
7555
  encoding: "utf8"
5768
7556
  });
5769
7557
  if (status.trim()) {
5770
7558
  throw new Error(`Refusing to remove dirty worktree: ${worktreePath}. Commit or preserve changed, untracked, and ignored files first.`);
5771
7559
  }
5772
- execFileSync12("git", ["worktree", "remove", worktreePath], {
7560
+ execFileSync15("git", ["worktree", "remove", worktreePath], {
5773
7561
  cwd: this.coordDb.repoRoot,
5774
7562
  stdio: ["ignore", "pipe", "pipe"]
5775
7563
  });
@@ -5781,7 +7569,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
5781
7569
  }
5782
7570
  listWorktrees() {
5783
7571
  try {
5784
- const out = execFileSync12("git", ["worktree", "list", "--porcelain"], {
7572
+ const out = execFileSync15("git", ["worktree", "list", "--porcelain"], {
5785
7573
  cwd: this.coordDb.repoRoot,
5786
7574
  encoding: "utf8"
5787
7575
  });
@@ -5861,7 +7649,14 @@ var KithEngine = class {
5861
7649
  return next;
5862
7650
  }
5863
7651
  commit(params) {
5864
- return commitScopedFiles(this, params);
7652
+ const result = commitScopedFiles(this, params);
7653
+ if (result.ok) {
7654
+ try {
7655
+ this.shadowGit.pruneFalseConflicts();
7656
+ } catch {
7657
+ }
7658
+ }
7659
+ return result;
5865
7660
  }
5866
7661
  /** Read-only situational summary from live state: who is active on what, open handoffs, conflicts, claims that overlap a scope. */
5867
7662
  brief(options = {}) {
@@ -5905,7 +7700,7 @@ var KithEngine = class {
5905
7700
  warnings: []
5906
7701
  };
5907
7702
  }
5908
- const content = params.content ?? (fs18.existsSync(path16.join(targetRoot, file)) ? fs18.readFileSync(path16.join(targetRoot, file), "utf8") : "");
7703
+ const content = params.content ?? (fs19.existsSync(path17.join(targetRoot, file)) ? fs19.readFileSync(path17.join(targetRoot, file), "utf8") : "");
5909
7704
  const contractReport = this.depGraph.recordFileModification(
5910
7705
  params.agentId,
5911
7706
  file,
@@ -5982,10 +7777,10 @@ var KithEngine = class {
5982
7777
  const held = this.coordDb.db.prepare(`SELECT pattern FROM locks WHERE owner_agent_id = ?`).all(agentId).map((l) => l.pattern.replace(/^file:/, ""));
5983
7778
  const mine = activeConflicts.filter((c) => c.agent_a === agentId || held.some((p) => c.file_path === p || LockEngine.patternsOverlap(p, c.file_path)));
5984
7779
  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`);
7780
+ const seenFile = path17.join(this.coordDb.coordDir, "delta-seen", `${agentId.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`);
5986
7781
  let seen = { keys: [], others: 0 };
5987
7782
  try {
5988
- seen = JSON.parse(fs18.readFileSync(seenFile, "utf8"));
7783
+ seen = JSON.parse(fs19.readFileSync(seenFile, "utf8"));
5989
7784
  } catch {
5990
7785
  }
5991
7786
  const seenKeys = new Set(seen.keys);
@@ -6000,8 +7795,8 @@ var KithEngine = class {
6000
7795
  try {
6001
7796
  const keys = mine.map(keyOf).sort();
6002
7797
  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 }));
7798
+ fs19.mkdirSync(path17.dirname(seenFile), { recursive: true });
7799
+ fs19.writeFileSync(seenFile, JSON.stringify({ keys, others }));
6005
7800
  }
6006
7801
  } catch {
6007
7802
  }
@@ -6127,20 +7922,20 @@ ${kept.join("\n")}` : "";
6127
7922
  const root = physicalPath(agent.worktree_path);
6128
7923
  const owner = discoverRepository(this.coordDb.repoRoot);
6129
7924
  const layout = discoverRepository(root);
6130
- const git3 = (...args) => execFileSync13("git", args, {
7925
+ const git4 = (...args) => execFileSync16("git", args, {
6131
7926
  cwd: root,
6132
7927
  encoding: "utf8",
6133
7928
  stdio: ["ignore", "pipe", "pipe"],
6134
7929
  timeout: 5e3
6135
7930
  }).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)) {
7931
+ if (!isWithin(physicalPath(path17.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
7932
  throw new Error("Saved worktree identity or ownership changed; inspect and preserve it before claiming another task.");
6138
7933
  }
6139
- if (git3("status", "--porcelain", "--untracked-files=normal")) {
7934
+ if (git4("status", "--porcelain", "--untracked-files=normal")) {
6140
7935
  throw new Error("Saved worktree has unfinished changes; preserve or finish them before claiming another task.");
6141
7936
  }
6142
- const head = execFileSync13("git", ["rev-parse", "HEAD"], { cwd: this.coordDb.repoRoot, encoding: "utf8" }).trim();
6143
- if (git3("rev-parse", "HEAD") !== head) {
7937
+ const head = execFileSync16("git", ["rev-parse", "HEAD"], { cwd: this.coordDb.repoRoot, encoding: "utf8" }).trim();
7938
+ if (git4("rev-parse", "HEAD") !== head) {
6144
7939
  throw new Error("Saved worktree is ahead or behind the current checkout; integrate or replace it explicitly before claiming another task.");
6145
7940
  }
6146
7941
  return { agentId, worktreePath: root, branch: agent.branch, hydrationMethod: "none", hydratedDirs: [], durationMs: 0 };
@@ -6236,6 +8031,7 @@ export {
6236
8031
  readBrief,
6237
8032
  readCoordinationState,
6238
8033
  recoveryReport,
8034
+ refUpdateResyncRoots,
6239
8035
  repositoryFile,
6240
8036
  resyncStaleIndexEntries,
6241
8037
  runVerificationCommand,