kith-coord 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __kithRequire } from 'node:module'; const require = __kithRequire(import.meta.url);
2
2
 
3
3
  // src/core/engine.ts
4
- import { execFileSync as execFileSync16 } from "child_process";
4
+ import { execFileSync as execFileSync18 } from "child_process";
5
5
 
6
6
  // src/core/repository.ts
7
7
  import { execFileSync } from "child_process";
@@ -162,7 +162,7 @@ async function waitForClaim(params) {
162
162
  }
163
163
 
164
164
  // src/version.ts
165
- var KITH_VERSION = "0.1.9";
165
+ var KITH_VERSION = "0.2.0";
166
166
  var KITH_PROTOCOL_VERSION = "1.6.0";
167
167
 
168
168
  // src/core/git-ignore.ts
@@ -411,8 +411,8 @@ function previewIntegration(repoRoot, agent) {
411
411
  }
412
412
 
413
413
  // src/core/engine.ts
414
- import fs19 from "fs";
415
- import path17 from "path";
414
+ import fs20 from "fs";
415
+ import path18 from "path";
416
416
 
417
417
  // src/core/ast-analyzer.ts
418
418
  import crypto from "crypto";
@@ -776,7 +776,7 @@ function scopesOverlap(a, b, literalA = false, literalB = false) {
776
776
  }
777
777
 
778
778
  // src/core/fencing.ts
779
- import { execFileSync as execFileSync4 } from "child_process";
779
+ import { execFile, execFileSync as execFileSync4 } from "child_process";
780
780
  import crypto3 from "crypto";
781
781
  import fs4 from "fs";
782
782
  import path4 from "path";
@@ -989,6 +989,9 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
989
989
  capabilities = /* @__PURE__ */ new Map();
990
990
  static ownWindowsStart = null;
991
991
  static inspectionFailure = null;
992
+ /** Confirmed start times. Heartbeats must not spawn `ps` on every 100ms tick: on macOS that blocks the event loop longer than a short mutex lease and the lease is lost before the command starts. */
993
+ static confirmedStarts = /* @__PURE__ */ new Map();
994
+ static rechecking = /* @__PURE__ */ new Set();
992
995
  static validateLease(duration) {
993
996
  if (!Number.isSafeInteger(duration) || duration < 100 || duration > 864e5) {
994
997
  throw new Error("Lease duration must be an integer between 100 and 86400000 milliseconds");
@@ -1002,7 +1005,7 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
1002
1005
  try {
1003
1006
  if (process.platform === "linux") {
1004
1007
  const stat = fs4.readFileSync(`/proc/${pid}/stat`, "utf8");
1005
- return `linux:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
1008
+ return this.rememberStart(pid, `linux:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`);
1006
1009
  }
1007
1010
  if (process.platform === "win32") {
1008
1011
  if (pid === process.pid && this.ownWindowsStart) return this.ownWindowsStart;
@@ -1023,7 +1026,7 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
1023
1026
  }
1024
1027
  const identity = `windows:${ticks}`;
1025
1028
  if (pid === process.pid) this.ownWindowsStart = identity;
1026
- return identity;
1029
+ return this.rememberStart(pid, identity);
1027
1030
  }
1028
1031
  const out = execFileSync4("ps", ["-o", "lstart=", "-p", String(pid)], {
1029
1032
  encoding: "utf8",
@@ -1031,22 +1034,92 @@ var FencingAndAgentManager = class _FencingAndAgentManager {
1031
1034
  timeout: 1500,
1032
1035
  env: { ...process.env, LC_ALL: "C" }
1033
1036
  }).trim();
1034
- return out || null;
1037
+ return out ? this.rememberStart(pid, out) : null;
1035
1038
  } catch (error) {
1036
1039
  const failure = error;
1037
1040
  this.inspectionFailure = [failure.code, failure.status === void 0 ? null : `exit ${failure.status}`, failure.signal].filter(Boolean).join(", ") || "inspection unavailable";
1038
1041
  return null;
1039
1042
  }
1040
1043
  }
1044
+ /**
1045
+ * Resolve a start time without blocking lease renewal. A just-forked pid can be
1046
+ * invisible to `ps` for a moment, and a single timed-out `ps` must not abort the command.
1047
+ */
1048
+ static async waitForProcessStartTime(pid, budgetMs, aborted) {
1049
+ const deadline = Date.now() + budgetMs;
1050
+ while (!aborted?.() && Date.now() < deadline) {
1051
+ try {
1052
+ process.kill(pid, 0);
1053
+ } catch (err) {
1054
+ if (err.code === "ESRCH") return null;
1055
+ }
1056
+ const start = process.platform === "darwin" ? await this.readDarwinStartTime(pid, Math.min(800, Math.max(50, deadline - Date.now()))) : this.getProcessStartTime(pid);
1057
+ if (start) return start;
1058
+ await new Promise((resolve) => setTimeout(resolve, 20));
1059
+ }
1060
+ return null;
1061
+ }
1041
1062
  static isProcessAlive(pid, expectedStartTime) {
1042
1063
  if (!Number.isSafeInteger(pid) || pid <= 0) return false;
1043
1064
  try {
1044
1065
  process.kill(pid, 0);
1045
1066
  } catch (err) {
1046
- if (err.code === "ESRCH") return false;
1067
+ if (err.code === "ESRCH") {
1068
+ this.confirmedStarts.delete(pid);
1069
+ return false;
1070
+ }
1071
+ }
1072
+ const cached = this.confirmedStarts.get(pid);
1073
+ if (cached?.start === expectedStartTime) {
1074
+ this.scheduleStartRecheck(pid);
1075
+ return true;
1047
1076
  }
1048
1077
  const current = this.getProcessStartTime(pid);
1049
- return current === null || current === expectedStartTime;
1078
+ if (current === null) return true;
1079
+ if (current === expectedStartTime) return true;
1080
+ this.confirmedStarts.delete(pid);
1081
+ return false;
1082
+ }
1083
+ static rememberStart(pid, start) {
1084
+ this.confirmedStarts.set(pid, { start, at: Date.now() });
1085
+ return start;
1086
+ }
1087
+ /** Refresh identity in the background so a slow `ps` cannot stall mutex renewal. */
1088
+ static scheduleStartRecheck(pid) {
1089
+ const cached = this.confirmedStarts.get(pid);
1090
+ if (!cached || this.rechecking.has(pid) || Date.now() - cached.at < 250) return;
1091
+ this.rechecking.add(pid);
1092
+ const finish = (start) => {
1093
+ this.rechecking.delete(pid);
1094
+ if (start) {
1095
+ this.rememberStart(pid, start);
1096
+ return;
1097
+ }
1098
+ try {
1099
+ process.kill(pid, 0);
1100
+ } catch (err) {
1101
+ if (err.code === "ESRCH") this.confirmedStarts.delete(pid);
1102
+ }
1103
+ };
1104
+ if (process.platform === "darwin") void this.readDarwinStartTime(pid, 800).then(finish);
1105
+ else finish(this.getProcessStartTime(pid));
1106
+ }
1107
+ static readDarwinStartTime(pid, timeoutMs) {
1108
+ return new Promise((resolve) => {
1109
+ const child = execFile("ps", ["-o", "lstart=", "-p", String(pid)], {
1110
+ encoding: "utf8",
1111
+ timeout: timeoutMs,
1112
+ env: { ...process.env, LC_ALL: "C" }
1113
+ }, (err, stdout) => {
1114
+ if (err) {
1115
+ resolve(null);
1116
+ return;
1117
+ }
1118
+ const value = stdout.trim();
1119
+ resolve(value ? this.rememberStart(pid, value) : null);
1120
+ });
1121
+ child.unref();
1122
+ });
1050
1123
  }
1051
1124
  registerAgent(params) {
1052
1125
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(params.id)) throw new Error("Invalid agent ID");
@@ -3550,7 +3623,7 @@ function presenceTouchedFor(commonGitDir, agent) {
3550
3623
  }
3551
3624
 
3552
3625
  // src/core/broker.ts
3553
- import { fork } from "child_process";
3626
+ import { execFileSync as execFileSync8, fork } from "child_process";
3554
3627
  import fs8 from "fs";
3555
3628
  import { fileURLToPath } from "url";
3556
3629
  import crypto7 from "crypto";
@@ -3760,6 +3833,7 @@ var ResourceBroker = class _ResourceBroker {
3760
3833
  const requestId = crypto7.randomUUID();
3761
3834
  const started = Date.now();
3762
3835
  let run = null;
3836
+ let groupReaped = false;
3763
3837
  const abortError = () => new DOMException("Mutex command cancelled", "AbortError");
3764
3838
  this.activeExecutions++;
3765
3839
  try {
@@ -3803,7 +3877,7 @@ var ResourceBroker = class _ResourceBroker {
3803
3877
  });
3804
3878
  throw new Error("Could not start command supervisor");
3805
3879
  }
3806
- let workerIdentity = FencingAndAgentManager.getProcessStartTime(workerPid);
3880
+ let workerIdentity = null;
3807
3881
  let failure;
3808
3882
  let outcome;
3809
3883
  const stdout = [];
@@ -3831,11 +3905,19 @@ var ResourceBroker = class _ResourceBroker {
3831
3905
  };
3832
3906
  const onAbort = () => stop(abortError());
3833
3907
  params.signal?.addEventListener("abort", onAbort, { once: true });
3908
+ const renew = () => {
3909
+ this.fencing.heartbeat(params.agentId);
3910
+ this.renewMutex({ ...params, fencingToken: run.fencing_token });
3911
+ lifecycle?.renew();
3912
+ };
3913
+ try {
3914
+ renew();
3915
+ } catch (err) {
3916
+ stop(err instanceof Error ? err : new Error(String(err)));
3917
+ }
3834
3918
  const interval = setInterval(() => {
3835
3919
  try {
3836
- this.fencing.heartbeat(params.agentId);
3837
- this.renewMutex({ ...params, fencingToken: run.fencing_token });
3838
- lifecycle?.renew();
3920
+ renew();
3839
3921
  } catch (err) {
3840
3922
  stop(err instanceof Error ? err : new Error(String(err)));
3841
3923
  }
@@ -3849,26 +3931,43 @@ var ResourceBroker = class _ResourceBroker {
3849
3931
  };
3850
3932
  worker.stdout.on("data", capture(stdout, params.onStdout));
3851
3933
  worker.stderr.on("data", capture(stderr, params.onStderr));
3934
+ let launchStarted = false;
3852
3935
  worker.on("message", (message) => {
3853
3936
  if (disposed) return;
3854
3937
  if (message.ready) {
3855
- try {
3856
- if (params.signal?.aborted) throw abortError();
3857
- this.coordDb.withTransaction(() => {
3858
- this.fencing.assertSession(params.agentId);
3859
- const identity = FencingAndAgentManager.getProcessStartTime(workerPid);
3938
+ if (launchStarted || failure) return;
3939
+ launchStarted = true;
3940
+ void (async () => {
3941
+ try {
3942
+ if (params.signal?.aborted) throw abortError();
3943
+ try {
3944
+ renew();
3945
+ } catch (err) {
3946
+ throw err instanceof Error ? err : new Error(String(err));
3947
+ }
3948
+ const identity = await FencingAndAgentManager.waitForProcessStartTime(
3949
+ workerPid,
3950
+ 5e3,
3951
+ () => disposed || Boolean(failure) || Boolean(params.signal?.aborted)
3952
+ );
3953
+ if (disposed || failure) return;
3954
+ if (params.signal?.aborted) throw abortError();
3860
3955
  if (!identity) throw new Error("Cannot inspect command worker");
3861
- this.coordDb.db.prepare("UPDATE mutex_runs SET worker_pid=?, worker_start=? WHERE run_id=?").run(workerPid, identity, requestId);
3862
- run.worker_pid = workerPid;
3863
- run.worker_start = identity;
3864
- workerIdentity = identity;
3865
- this.renewMutex({ ...params, fencingToken: run.fencing_token });
3866
- lifecycle?.renew();
3867
- });
3868
- worker.send({ command: prepared?.command ?? params.command, env: prepared?.env, cwd: params.cwd ?? this.coordDb.repoRoot, mutexName: params.mutexName });
3869
- } catch (err) {
3870
- stop(err instanceof Error ? err : new Error(String(err)));
3871
- }
3956
+ this.coordDb.withTransaction(() => {
3957
+ this.fencing.assertSession(params.agentId);
3958
+ this.coordDb.db.prepare("UPDATE mutex_runs SET worker_pid=?, worker_start=? WHERE run_id=?").run(workerPid, identity, requestId);
3959
+ run.worker_pid = workerPid;
3960
+ run.worker_start = identity;
3961
+ workerIdentity = identity;
3962
+ this.renewMutex({ ...params, fencingToken: run.fencing_token });
3963
+ lifecycle?.renew();
3964
+ });
3965
+ if (params.signal?.aborted || failure) throw abortError();
3966
+ worker.send({ command: prepared?.command ?? params.command, env: prepared?.env, cwd: params.cwd ?? this.coordDb.repoRoot, mutexName: params.mutexName });
3967
+ } catch (err) {
3968
+ if (!disposed && !failure) stop(err instanceof Error ? err : new Error(String(err)));
3969
+ }
3970
+ })();
3872
3971
  } else {
3873
3972
  outcome = { exitCode: message.exitCode ?? 1, error: message.error };
3874
3973
  }
@@ -3894,12 +3993,22 @@ var ResourceBroker = class _ResourceBroker {
3894
3993
  const killError = signalGroup(workerPid, "SIGKILL", workerIdentity);
3895
3994
  failure ??= killError;
3896
3995
  const deadline = stopDeadline ?? Date.now() + 5e3;
3897
- while (groupIsAlive(workerPid, workerIdentity) && Date.now() < deadline) await delay(20);
3996
+ let lastZombieCheck = 0;
3997
+ while (groupIsAlive(workerPid, workerIdentity) && Date.now() < deadline) {
3998
+ if (process.platform === "darwin" && Date.now() - lastZombieCheck >= 200) {
3999
+ lastZombieCheck = Date.now();
4000
+ if (darwinGroupHasLiveMember(workerPid) === false) {
4001
+ groupReaped = true;
4002
+ break;
4003
+ }
4004
+ }
4005
+ await delay(20);
4006
+ }
3898
4007
  }
3899
4008
  disposed = true;
3900
4009
  if (killTimer) clearTimeout(killTimer);
3901
4010
  if (stopTimer) clearTimeout(stopTimer);
3902
- if (groupIsAlive(workerPid, workerIdentity)) {
4011
+ if (!groupReaped && groupIsAlive(workerPid, workerIdentity)) {
3903
4012
  worker.stdout?.destroy();
3904
4013
  worker.stderr?.destroy();
3905
4014
  if (worker.connected) worker.disconnect();
@@ -3911,7 +4020,7 @@ var ResourceBroker = class _ResourceBroker {
3911
4020
  try {
3912
4021
  this.coordDb.withTransaction(() => {
3913
4022
  this.coordDb.db.prepare("DELETE FROM mutex_waiters WHERE mutex_name=? AND request_id=? AND session_epoch=?").run(params.mutexName, requestId, epoch);
3914
- if (run && !this.runIsAlive(run)) this.clearRun(run);
4023
+ if (run && (groupReaped || !this.runIsAlive(run))) this.clearRun(run);
3915
4024
  if (run && run.worker_pid === null) this.clearRun(run);
3916
4025
  if (!this.getRun(params.mutexName)) lifecycle?.release();
3917
4026
  });
@@ -3966,6 +4075,29 @@ var ResourceBroker = class _ResourceBroker {
3966
4075
  };
3967
4076
  }
3968
4077
  };
4078
+ function darwinGroupHasLiveMember(pgid) {
4079
+ try {
4080
+ const out = execFileSync8("ps", ["-ax", "-o", "pid=,pgid=,stat="], {
4081
+ encoding: "utf8",
4082
+ timeout: 1e3,
4083
+ stdio: ["ignore", "pipe", "ignore"],
4084
+ env: { ...process.env, LC_ALL: "C" }
4085
+ });
4086
+ let sawMember = false;
4087
+ for (const line of out.split("\n")) {
4088
+ const parts = line.trim().split(/\s+/);
4089
+ if (parts.length < 3) continue;
4090
+ const pid = Number(parts[0]);
4091
+ const group = Number(parts[1]);
4092
+ if (pid !== pgid && group !== pgid) continue;
4093
+ sawMember = true;
4094
+ if (!parts.slice(2).join(" ").startsWith("Z")) return true;
4095
+ }
4096
+ return sawMember ? false : null;
4097
+ } catch {
4098
+ return null;
4099
+ }
4100
+ }
3969
4101
  function groupIsAlive(pgid, expectedStart) {
3970
4102
  if (expectedStart) {
3971
4103
  const currentStart = FencingAndAgentManager.getProcessStartTime(pgid);
@@ -4346,6 +4478,20 @@ var CoordDatabase = class _CoordDatabase {
4346
4478
  CREATE INDEX IF NOT EXISTS idx_handoffs_task ON handoffs(task_id);
4347
4479
  CREATE INDEX IF NOT EXISTS idx_handoffs_created ON handoffs(created_at DESC);
4348
4480
  `);
4481
+ this.db.exec(`
4482
+ CREATE TABLE IF NOT EXISTS worktree_registrations (
4483
+ agent_id TEXT PRIMARY KEY,
4484
+ worktree_path TEXT NOT NULL,
4485
+ provenance TEXT NOT NULL,
4486
+ source TEXT NOT NULL,
4487
+ branch TEXT,
4488
+ head TEXT,
4489
+ detached INTEGER NOT NULL DEFAULT 0,
4490
+ dirty INTEGER NOT NULL DEFAULT 0,
4491
+ branch_elsewhere INTEGER NOT NULL DEFAULT 0,
4492
+ registered_at INTEGER NOT NULL
4493
+ );
4494
+ `);
4349
4495
  if (version < 2) {
4350
4496
  this.db.exec(`
4351
4497
  UPDATE tasks SET status='queued', owner_agent_id=NULL, fencing_token=NULL
@@ -5021,12 +5167,12 @@ var IntentAndTaskEngine = class {
5021
5167
  };
5022
5168
 
5023
5169
  // src/core/handoffs.ts
5024
- import { execFileSync as execFileSync8 } from "child_process";
5170
+ import { execFileSync as execFileSync9 } from "child_process";
5025
5171
  import fs10 from "fs";
5026
5172
  var RELEVANT_WINDOW_MS = 14 * 24 * 3600 * 1e3;
5027
5173
  function gitChangedFiles(worktree, repoRoot) {
5028
5174
  if (!worktree || !fs10.existsSync(worktree)) return [];
5029
- const run = (cwd, ...args) => execFileSync8("git", args, {
5175
+ const run = (cwd, ...args) => execFileSync9("git", args, {
5030
5176
  cwd,
5031
5177
  encoding: "utf8",
5032
5178
  stdio: ["ignore", "pipe", "ignore"],
@@ -5255,18 +5401,470 @@ function buildBrief(input, options = {}) {
5255
5401
  }
5256
5402
 
5257
5403
  // src/core/commit.ts
5258
- import { execFileSync as execFileSync11 } from "child_process";
5404
+ import { execFileSync as execFileSync13 } from "child_process";
5259
5405
  import crypto11 from "crypto";
5260
- import fs13 from "fs";
5261
- import path11 from "path";
5406
+ import fs14 from "fs";
5407
+ import path12 from "path";
5262
5408
 
5263
5409
  // src/cli/auto-session.ts
5264
5410
  import crypto10 from "crypto";
5265
- import { execFileSync as execFileSync9 } from "child_process";
5266
- import fs11 from "fs";
5411
+ import { execFileSync as execFileSync11 } from "child_process";
5412
+ import fs12 from "fs";
5267
5413
  import { createRequire as createRequire3 } from "module";
5268
5414
  import os from "os";
5415
+ import path10 from "path";
5416
+
5417
+ // src/core/worktree-adopt.ts
5418
+ import { execFileSync as execFileSync10 } from "child_process";
5419
+ import fs11 from "fs";
5269
5420
  import path9 from "path";
5421
+ var REGISTRATION_SQL = `SELECT agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at
5422
+ FROM worktree_registrations`;
5423
+ function detachedIntegrationError() {
5424
+ return "Adopted worktree HEAD is detached. Check out a branch before integrating. The worktree was left unchanged.";
5425
+ }
5426
+ function branchElsewhereError(branch) {
5427
+ return `Branch '${branch}' is checked out in another worktree. Integration and kith commit are refused until this worktree is the only checkout of that branch. The worktree was left unchanged.`;
5428
+ }
5429
+ function parseWorktreePorcelain(output) {
5430
+ const entries = [];
5431
+ let current = null;
5432
+ const push = () => {
5433
+ if (current) entries.push(current);
5434
+ };
5435
+ for (const line of output.split(/\r?\n/)) {
5436
+ if (!line) continue;
5437
+ if (line.startsWith("worktree ")) {
5438
+ push();
5439
+ current = { path: line.slice("worktree ".length).trim(), head: "", branch: null, detached: false, locked: false, lockReason: null };
5440
+ } else if (!current) {
5441
+ continue;
5442
+ } else if (line.startsWith("HEAD ")) {
5443
+ current.head = line.slice("HEAD ".length).trim();
5444
+ } else if (line.startsWith("branch ")) {
5445
+ current.branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim() || null;
5446
+ } else if (line === "detached") {
5447
+ current.detached = true;
5448
+ current.branch = null;
5449
+ } else if (line === "locked" || line.startsWith("locked ")) {
5450
+ current.locked = true;
5451
+ const reason = line.slice("locked".length).trim();
5452
+ current.lockReason = reason || null;
5453
+ }
5454
+ }
5455
+ push();
5456
+ return entries;
5457
+ }
5458
+ function listGitWorktrees(repoRoot) {
5459
+ try {
5460
+ const out = execFileSync10("git", ["worktree", "list", "--porcelain"], {
5461
+ cwd: repoRoot,
5462
+ encoding: "utf8",
5463
+ timeout: 5e3,
5464
+ stdio: ["ignore", "pipe", "pipe"]
5465
+ });
5466
+ return parseWorktreePorcelain(out);
5467
+ } catch {
5468
+ return [];
5469
+ }
5470
+ }
5471
+ function branchIsCheckedOutElsewhere(entries, worktreePath, branch) {
5472
+ if (!branch) return false;
5473
+ let here;
5474
+ try {
5475
+ here = physicalPath(worktreePath);
5476
+ } catch {
5477
+ here = path9.resolve(worktreePath);
5478
+ }
5479
+ return entries.some((entry) => {
5480
+ if (entry.branch !== branch) return false;
5481
+ try {
5482
+ return physicalPath(entry.path) !== here;
5483
+ } catch {
5484
+ return path9.resolve(entry.path) !== here;
5485
+ }
5486
+ });
5487
+ }
5488
+ function kithWorktreesRoot(coord) {
5489
+ return physicalPath(path9.join(coord.coordDir, "worktrees"));
5490
+ }
5491
+ function isKithOwnedWorktree(coord, worktreePath) {
5492
+ try {
5493
+ const root = kithWorktreesRoot(coord);
5494
+ const target = physicalPath(worktreePath);
5495
+ return target !== root && isWithin(root, target);
5496
+ } catch {
5497
+ return false;
5498
+ }
5499
+ }
5500
+ function primaryCheckoutOf(start) {
5501
+ const layout = discoverRepository(start);
5502
+ if (!layout.commonGitDir || !layout.isLinkedWorktree) return layout.checkoutRoot;
5503
+ for (const entry of listGitWorktrees(layout.checkoutRoot)) {
5504
+ try {
5505
+ const item = discoverRepository(entry.path);
5506
+ if (!item.isLinkedWorktree && item.commonGitDir === layout.commonGitDir) return item.checkoutRoot;
5507
+ } catch {
5508
+ }
5509
+ }
5510
+ return layout.checkoutRoot;
5511
+ }
5512
+ function registrationFromRow(row) {
5513
+ const source = row.source === "kith" || row.source === "claude-code" ? row.source : "external";
5514
+ return {
5515
+ agentId: row.agent_id,
5516
+ worktreePath: row.worktree_path,
5517
+ provenance: row.provenance === "created" ? "created" : "adopted",
5518
+ source,
5519
+ branch: row.branch,
5520
+ head: row.head,
5521
+ detached: Boolean(row.detached),
5522
+ dirty: Boolean(row.dirty),
5523
+ branchCheckedOutElsewhere: Boolean(row.branch_elsewhere),
5524
+ registeredAt: Number(row.registered_at)
5525
+ };
5526
+ }
5527
+ function registrationsTable(coord) {
5528
+ return Boolean(coord.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='worktree_registrations'").get());
5529
+ }
5530
+ function readRegistration(coord, agentId) {
5531
+ if (!registrationsTable(coord)) return null;
5532
+ const row = coord.db.prepare(`${REGISTRATION_SQL} WHERE agent_id = ?`).get(agentId);
5533
+ return row ? registrationFromRow(row) : null;
5534
+ }
5535
+ function listRegistrations(coord) {
5536
+ if (!registrationsTable(coord)) return [];
5537
+ return coord.db.prepare(`${REGISTRATION_SQL} ORDER BY registered_at`).all().map(registrationFromRow);
5538
+ }
5539
+ function clearRegistration(coord, agentId) {
5540
+ if (!registrationsTable(coord)) return;
5541
+ coord.db.prepare("DELETE FROM worktree_registrations WHERE agent_id = ?").run(agentId);
5542
+ }
5543
+ function worktreeDirty(cwd) {
5544
+ try {
5545
+ const out = execFileSync10("git", ["status", "--porcelain", "--untracked-files=normal"], {
5546
+ cwd,
5547
+ encoding: "utf8",
5548
+ timeout: 5e3,
5549
+ stdio: ["ignore", "pipe", "pipe"]
5550
+ });
5551
+ return out.trim().length > 0;
5552
+ } catch {
5553
+ throw new Error(`Cannot inspect worktree status at ${cwd}.`);
5554
+ }
5555
+ }
5556
+ function claudeMarker(worktreePath) {
5557
+ let admin = null;
5558
+ try {
5559
+ const text = fs11.readFileSync(path9.join(worktreePath, ".git"), "utf8");
5560
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(text);
5561
+ if (match?.[1]) admin = path9.resolve(worktreePath, match[1].trim());
5562
+ } catch {
5563
+ return { marker: false, lockReason: null };
5564
+ }
5565
+ if (!admin) return { marker: false, lockReason: null };
5566
+ let lockReason = null;
5567
+ try {
5568
+ lockReason = fs11.readFileSync(path9.join(admin, "locked"), "utf8").trim() || null;
5569
+ } catch {
5570
+ }
5571
+ const names = ["claude", "claude.json", "claude-worktree"];
5572
+ const marker = names.some((name) => {
5573
+ try {
5574
+ return fs11.existsSync(path9.join(admin, name));
5575
+ } catch {
5576
+ return false;
5577
+ }
5578
+ }) || Boolean(lockReason && /claude/i.test(lockReason));
5579
+ return { marker, lockReason };
5580
+ }
5581
+ function pathHasClaudeWorktrees(worktreePath) {
5582
+ const parts = worktreePath.split(path9.sep);
5583
+ for (let i = 0; i < parts.length - 1; i++) {
5584
+ if (parts[i] === ".claude" && parts[i + 1] === "worktrees" && parts.length >= i + 3) return true;
5585
+ }
5586
+ return false;
5587
+ }
5588
+ function classifySource(coord, worktreePath, lockReason) {
5589
+ if (isKithOwnedWorktree(coord, worktreePath)) return "kith";
5590
+ const marker = claudeMarker(worktreePath);
5591
+ if (pathHasClaudeWorktrees(worktreePath) || marker.marker || lockReason && /claude/i.test(lockReason)) return "claude-code";
5592
+ return "external";
5593
+ }
5594
+ function inspectLinkedWorktree(coord, requested) {
5595
+ if (!fs11.existsSync(requested)) throw new Error(`Not a linked worktree of this repository: ${requested}`);
5596
+ const dir = fs11.statSync(requested).isDirectory() ? requested : path9.dirname(requested);
5597
+ let layout;
5598
+ try {
5599
+ layout = discoverRepository(dir);
5600
+ } catch {
5601
+ throw new Error(`Not a linked worktree of this repository: ${requested}`);
5602
+ }
5603
+ if (!layout.commonGitDir || layout.commonGitDir !== coord.commonGitDir) {
5604
+ throw new Error(`Not a linked worktree of this repository: ${requested}`);
5605
+ }
5606
+ if (!layout.isLinkedWorktree) {
5607
+ throw new Error("Cannot adopt the primary checkout. Pass a linked worktree from git worktree list.");
5608
+ }
5609
+ const entries = listGitWorktrees(coord.repoRoot);
5610
+ const checkoutRoot = physicalPath(layout.checkoutRoot);
5611
+ const match = entries.find((entry) => {
5612
+ try {
5613
+ return physicalPath(entry.path) === checkoutRoot;
5614
+ } catch {
5615
+ return false;
5616
+ }
5617
+ });
5618
+ if (!match) throw new Error(`Not a linked worktree of this repository: ${checkoutRoot}`);
5619
+ const detached = match.detached || !match.branch;
5620
+ const branch = detached ? null : match.branch;
5621
+ return {
5622
+ checkoutRoot,
5623
+ branch,
5624
+ head: match.head,
5625
+ detached,
5626
+ dirty: worktreeDirty(checkoutRoot),
5627
+ branchCheckedOutElsewhere: branchIsCheckedOutElsewhere(entries, checkoutRoot, branch),
5628
+ source: classifySource(coord, checkoutRoot, match.lockReason),
5629
+ provenance: isKithOwnedWorktree(coord, checkoutRoot) ? "created" : "adopted",
5630
+ locked: match.locked,
5631
+ lockReason: match.lockReason
5632
+ };
5633
+ }
5634
+ function adoptionNotes(inspected) {
5635
+ if (inspected.provenance !== "adopted") return [];
5636
+ const notes = [
5637
+ "Kith did not create this worktree and will not delete it. Unregister with `kith worktree forget`, or remove it explicitly with `kith worktree remove --delete-adopted`."
5638
+ ];
5639
+ if (inspected.dirty) notes.unshift("Adopted worktree has uncommitted changes. They were left as they are.");
5640
+ if (inspected.detached) notes.unshift(detachedIntegrationError());
5641
+ else if (inspected.branchCheckedOutElsewhere && inspected.branch) notes.unshift(branchElsewhereError(inspected.branch));
5642
+ return notes;
5643
+ }
5644
+ function bindingFrom(agentId, inspected, started, alreadyRegistered) {
5645
+ return {
5646
+ agentId,
5647
+ worktreePath: inspected.checkoutRoot,
5648
+ branch: inspected.branch,
5649
+ hydrationMethod: "none",
5650
+ hydratedDirs: [],
5651
+ durationMs: Date.now() - started,
5652
+ provenance: inspected.provenance,
5653
+ source: inspected.source,
5654
+ detached: inspected.detached,
5655
+ dirty: inspected.dirty,
5656
+ branchCheckedOutElsewhere: inspected.branchCheckedOutElsewhere,
5657
+ alreadyRegistered,
5658
+ notes: adoptionNotes(inspected)
5659
+ };
5660
+ }
5661
+ function writeRegistration(coord, fencing, agentId, inspected, already, log = true) {
5662
+ coord.withTransaction(() => {
5663
+ fencing.assertSession(agentId);
5664
+ coord.db.prepare(`
5665
+ INSERT INTO worktree_registrations (
5666
+ agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at
5667
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5668
+ ON CONFLICT(agent_id) DO UPDATE SET
5669
+ worktree_path = excluded.worktree_path, provenance = excluded.provenance, source = excluded.source,
5670
+ branch = excluded.branch, head = excluded.head, detached = excluded.detached,
5671
+ branch_elsewhere = excluded.branch_elsewhere,
5672
+ dirty = CASE WHEN worktree_registrations.worktree_path = excluded.worktree_path THEN worktree_registrations.dirty ELSE excluded.dirty END,
5673
+ registered_at = CASE WHEN worktree_registrations.worktree_path = excluded.worktree_path THEN worktree_registrations.registered_at ELSE excluded.registered_at END
5674
+ `).run(
5675
+ agentId,
5676
+ inspected.checkoutRoot,
5677
+ inspected.provenance,
5678
+ inspected.source,
5679
+ inspected.branch,
5680
+ inspected.head,
5681
+ inspected.detached ? 1 : 0,
5682
+ inspected.dirty ? 1 : 0,
5683
+ inspected.branchCheckedOutElsewhere ? 1 : 0,
5684
+ Date.now()
5685
+ );
5686
+ coord.db.prepare("UPDATE agents SET worktree_path = ?, branch = ? WHERE id = ?").run(inspected.checkoutRoot, inspected.branch, agentId);
5687
+ const changed = !already || physicalPath(already.worktreePath) !== inspected.checkoutRoot || already.branch !== inspected.branch || already.detached !== inspected.detached || already.branchCheckedOutElsewhere !== inspected.branchCheckedOutElsewhere || already.source !== inspected.source;
5688
+ if (log && changed) {
5689
+ coord.logEvent(agentId, inspected.provenance === "created" ? "worktree_spawned" : "worktree_adopted", {
5690
+ worktreePath: inspected.checkoutRoot,
5691
+ branch: inspected.branch,
5692
+ source: inspected.source,
5693
+ provenance: inspected.provenance,
5694
+ detached: inspected.detached,
5695
+ dirty: inspected.dirty,
5696
+ branchCheckedOutElsewhere: inspected.branchCheckedOutElsewhere
5697
+ });
5698
+ }
5699
+ });
5700
+ }
5701
+ function adoptWorktree(coord, fencing, params) {
5702
+ fencing.assertSession(params.agentId);
5703
+ const started = Date.now();
5704
+ const requested = params.path ? path9.resolve(params.path) : process.cwd();
5705
+ const inspected = inspectLinkedWorktree(coord, requested);
5706
+ const agent = fencing.getAgent(params.agentId);
5707
+ if (agent?.worktree_path && physicalPath(agent.worktree_path) !== inspected.checkoutRoot) {
5708
+ throw new Error(`This session already has a different worktree at ${agent.worktree_path}. Forget it with \`kith worktree forget\` before adopting another.`);
5709
+ }
5710
+ const peer = fencing.listAgents(true).find((other) => other.id !== params.agentId && other.worktree_path && physicalPath(other.worktree_path) === inspected.checkoutRoot);
5711
+ if (peer) throw new Error(`Worktree is already registered to active agent '${peer.id}'.`);
5712
+ const already = readRegistration(coord, params.agentId);
5713
+ const same = Boolean(already && physicalPath(already.worktreePath) === inspected.checkoutRoot && already.branch === inspected.branch && already.detached === inspected.detached && already.branchCheckedOutElsewhere === inspected.branchCheckedOutElsewhere && already.source === inspected.source && already.provenance === inspected.provenance);
5714
+ if (!same) writeRegistration(coord, fencing, params.agentId, inspected, already);
5715
+ return bindingFrom(params.agentId, inspected, started, Boolean(already && physicalPath(already.worktreePath) === inspected.checkoutRoot));
5716
+ }
5717
+ function recordCreatedWorktree(coord, fencing, params) {
5718
+ const inspected = {
5719
+ checkoutRoot: physicalPath(params.worktreePath),
5720
+ branch: params.branch,
5721
+ head: params.head ?? "",
5722
+ detached: false,
5723
+ dirty: false,
5724
+ branchCheckedOutElsewhere: false,
5725
+ source: "kith",
5726
+ provenance: "created",
5727
+ locked: false,
5728
+ lockReason: null
5729
+ };
5730
+ writeRegistration(coord, fencing, params.agentId, inspected, readRegistration(coord, params.agentId), false);
5731
+ }
5732
+ function syncRegistration(coord, fencing, agentId) {
5733
+ const agent = fencing.getAgent(agentId);
5734
+ if (!agent?.worktree_path) return null;
5735
+ const existing = readRegistration(coord, agentId);
5736
+ if (existing) {
5737
+ try {
5738
+ if (physicalPath(existing.worktreePath) === physicalPath(agent.worktree_path)) return existing;
5739
+ } catch {
5740
+ return existing;
5741
+ }
5742
+ }
5743
+ try {
5744
+ adoptWorktree(coord, fencing, { agentId, path: agent.worktree_path, explicit: false });
5745
+ } catch {
5746
+ return readRegistration(coord, agentId);
5747
+ }
5748
+ return readRegistration(coord, agentId);
5749
+ }
5750
+ function adoptIfUnambiguous(coord, fencing, params) {
5751
+ const agent = fencing.getAgent(params.agentId);
5752
+ if (!agent || agent.status !== "active") return null;
5753
+ let layout;
5754
+ try {
5755
+ layout = discoverRepository(params.cwd);
5756
+ } catch {
5757
+ return null;
5758
+ }
5759
+ if (!layout.isLinkedWorktree || !layout.commonGitDir || layout.commonGitDir !== coord.commonGitDir) return null;
5760
+ if (agent.worktree_path) {
5761
+ try {
5762
+ if (physicalPath(agent.worktree_path) !== physicalPath(layout.checkoutRoot)) return null;
5763
+ } catch {
5764
+ return null;
5765
+ }
5766
+ }
5767
+ const peer = fencing.listAgents(true).some((other) => other.id !== params.agentId && other.worktree_path && (() => {
5768
+ try {
5769
+ return physicalPath(other.worktree_path) === physicalPath(layout.checkoutRoot);
5770
+ } catch {
5771
+ return false;
5772
+ }
5773
+ })());
5774
+ if (peer) return null;
5775
+ try {
5776
+ return adoptWorktree(coord, fencing, { agentId: params.agentId, path: layout.checkoutRoot, explicit: false });
5777
+ } catch {
5778
+ return null;
5779
+ }
5780
+ }
5781
+ function liveAdoption(coord, fencing, agent) {
5782
+ if (!agent?.worktree_path) return null;
5783
+ const registration = readRegistration(coord, agent.id);
5784
+ const adopted = registration?.provenance === "adopted" || !registration && !isKithOwnedWorktree(coord, agent.worktree_path);
5785
+ if (!adopted) return null;
5786
+ let inspected;
5787
+ try {
5788
+ inspected = inspectLinkedWorktree(coord, agent.worktree_path);
5789
+ } catch {
5790
+ return {
5791
+ worktreePath: agent.worktree_path,
5792
+ branch: agent.branch,
5793
+ detached: registration?.detached ?? !agent.branch,
5794
+ dirty: registration?.dirty ?? false,
5795
+ branchCheckedOutElsewhere: registration?.branchCheckedOutElsewhere ?? false,
5796
+ source: registration?.source ?? "external",
5797
+ provenance: "adopted",
5798
+ integrationError: registration?.detached || !agent.branch ? detachedIntegrationError() : registration?.branchCheckedOutElsewhere && agent.branch ? branchElsewhereError(agent.branch) : null,
5799
+ commitError: registration?.branchCheckedOutElsewhere && agent.branch ? branchElsewhereError(agent.branch) : null
5800
+ };
5801
+ }
5802
+ if (registration?.branch !== inspected.branch || registration?.detached !== inspected.detached || registration?.branchCheckedOutElsewhere !== inspected.branchCheckedOutElsewhere) {
5803
+ try {
5804
+ writeRegistration(coord, fencing, agent.id, inspected, registration);
5805
+ } catch {
5806
+ }
5807
+ }
5808
+ const integrationError = inspected.detached ? detachedIntegrationError() : inspected.branchCheckedOutElsewhere && inspected.branch ? branchElsewhereError(inspected.branch) : null;
5809
+ return {
5810
+ worktreePath: inspected.checkoutRoot,
5811
+ branch: inspected.branch,
5812
+ detached: inspected.detached,
5813
+ dirty: inspected.dirty,
5814
+ branchCheckedOutElsewhere: inspected.branchCheckedOutElsewhere,
5815
+ source: inspected.source,
5816
+ provenance: "adopted",
5817
+ integrationError,
5818
+ commitError: inspected.branchCheckedOutElsewhere && inspected.branch ? branchElsewhereError(inspected.branch) : null
5819
+ };
5820
+ }
5821
+ function transferWorktreeRegistration(coord, fromId, toId) {
5822
+ if (fromId === toId) return false;
5823
+ const from = coord.db.prepare("SELECT worktree_path, branch FROM agents WHERE id = ?").get(fromId);
5824
+ const to = coord.db.prepare("SELECT worktree_path FROM agents WHERE id = ?").get(toId);
5825
+ if (!from?.worktree_path || !to || to.worktree_path) return false;
5826
+ coord.db.prepare("UPDATE agents SET worktree_path = ?, branch = ? WHERE id = ?").run(from.worktree_path, from.branch, toId);
5827
+ coord.db.prepare("UPDATE agents SET worktree_path = NULL, branch = NULL WHERE id = ?").run(fromId);
5828
+ if (!registrationsTable(coord)) return true;
5829
+ const row = coord.db.prepare(`${REGISTRATION_SQL} WHERE agent_id = ?`).get(fromId);
5830
+ if (!row) return true;
5831
+ coord.db.prepare("DELETE FROM worktree_registrations WHERE agent_id = ?").run(fromId);
5832
+ coord.db.prepare(`
5833
+ INSERT INTO worktree_registrations (
5834
+ agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at
5835
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5836
+ ON CONFLICT(agent_id) DO UPDATE SET
5837
+ worktree_path = excluded.worktree_path, provenance = excluded.provenance, source = excluded.source,
5838
+ branch = excluded.branch, head = excluded.head, detached = excluded.detached, dirty = excluded.dirty,
5839
+ branch_elsewhere = excluded.branch_elsewhere, registered_at = excluded.registered_at
5840
+ `).run(
5841
+ toId,
5842
+ row.worktree_path,
5843
+ row.provenance,
5844
+ row.source,
5845
+ row.branch,
5846
+ row.head,
5847
+ Number(row.detached),
5848
+ Number(row.dirty),
5849
+ Number(row.branch_elsewhere),
5850
+ row.registered_at
5851
+ );
5852
+ return true;
5853
+ }
5854
+ function forgetWorktree(coord, fencing, agentId) {
5855
+ fencing.assertSession(agentId);
5856
+ const agent = fencing.getAgent(agentId);
5857
+ const had = Boolean(agent?.worktree_path || readRegistration(coord, agentId));
5858
+ coord.withTransaction(() => {
5859
+ fencing.assertSession(agentId);
5860
+ clearRegistration(coord, agentId);
5861
+ coord.db.prepare("UPDATE agents SET worktree_path = NULL, branch = NULL WHERE id = ?").run(agentId);
5862
+ coord.logEvent(agentId, "worktree_forgotten", { worktreePath: agent?.worktree_path ?? null });
5863
+ });
5864
+ return had;
5865
+ }
5866
+
5867
+ // src/cli/auto-session.ts
5270
5868
  var PRESENCE_TTL_MS = 12 * 60 * 60 * 1e3;
5271
5869
  var require4 = createRequire3(import.meta.url);
5272
5870
  function openSqlite(filePath) {
@@ -5333,17 +5931,17 @@ function resolveHomeDir(explicitHome) {
5333
5931
  return physicalPath(raw);
5334
5932
  }
5335
5933
  function presenceDbPath(home) {
5336
- return path9.join(resolveHomeDir(home), ".local/share/kith/presence.db");
5934
+ return path10.join(resolveHomeDir(home), ".local/share/kith/presence.db");
5337
5935
  }
5338
5936
  function withPresenceDb(home, create, fn) {
5339
5937
  const file = presenceDbPath(home);
5340
- if (!create && !fs11.existsSync(file)) return null;
5341
- const dir = path9.dirname(file);
5938
+ if (!create && !fs12.existsSync(file)) return null;
5939
+ const dir = path10.dirname(file);
5342
5940
  if (create) {
5343
- fs11.mkdirSync(dir, { recursive: true, mode: 448 });
5941
+ fs12.mkdirSync(dir, { recursive: true, mode: 448 });
5344
5942
  }
5345
5943
  if (physicalPath(dir) !== dir) return null;
5346
- if (fs11.existsSync(file) && physicalPath(file) !== file) return null;
5944
+ if (fs12.existsSync(file) && physicalPath(file) !== file) return null;
5347
5945
  const db = openSqlite(file);
5348
5946
  try {
5349
5947
  return fn(db);
@@ -5439,7 +6037,7 @@ function ancestorChain(pid) {
5439
6037
  let current = pid;
5440
6038
  for (let hop = 0; hop < 16; hop++) {
5441
6039
  try {
5442
- const line = execFileSync9("ps", ["-o", "ppid=", "-p", String(current)], {
6040
+ const line = execFileSync11("ps", ["-o", "ppid=", "-p", String(current)], {
5443
6041
  encoding: "utf8",
5444
6042
  stdio: ["ignore", "pipe", "ignore"],
5445
6043
  timeout: 500
@@ -5461,12 +6059,12 @@ function ownedByCaller(agentPid, callerPid) {
5461
6059
  }
5462
6060
 
5463
6061
  // src/core/gc.ts
5464
- import fs12 from "fs";
5465
- import path10 from "path";
5466
- import { execFileSync as execFileSync10 } from "child_process";
6062
+ import fs13 from "fs";
6063
+ import path11 from "path";
6064
+ import { execFileSync as execFileSync12 } from "child_process";
5467
6065
  function gitStatusDirty(dir) {
5468
6066
  try {
5469
- const out = execFileSync10("git", ["status", "--porcelain"], {
6067
+ const out = execFileSync12("git", ["status", "--porcelain"], {
5470
6068
  cwd: dir,
5471
6069
  encoding: "utf8",
5472
6070
  stdio: ["ignore", "pipe", "pipe"]
@@ -5479,7 +6077,7 @@ function gitStatusDirty(dir) {
5479
6077
  function gitIsMerged(repoRoot, commit) {
5480
6078
  if (!commit) return false;
5481
6079
  try {
5482
- execFileSync10("git", ["merge-base", "--is-ancestor", commit, "HEAD"], {
6080
+ execFileSync12("git", ["merge-base", "--is-ancestor", commit, "HEAD"], {
5483
6081
  cwd: repoRoot,
5484
6082
  stdio: ["ignore", "ignore", "ignore"]
5485
6083
  });
@@ -5488,10 +6086,37 @@ function gitIsMerged(repoRoot, commit) {
5488
6086
  return false;
5489
6087
  }
5490
6088
  }
6089
+ function removeCreatedWorktree(repoRoot, wtPath, force) {
6090
+ let admin = null;
6091
+ try {
6092
+ const text = fs13.readFileSync(path11.join(wtPath, ".git"), "utf8");
6093
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(text);
6094
+ if (match?.[1]) admin = path11.resolve(wtPath, match[1].trim());
6095
+ } catch {
6096
+ }
6097
+ try {
6098
+ execFileSync12("git", ["worktree", "remove", ...force ? ["--force"] : [], wtPath], {
6099
+ cwd: repoRoot,
6100
+ stdio: ["ignore", "pipe", "pipe"]
6101
+ });
6102
+ return;
6103
+ } catch {
6104
+ }
6105
+ fs13.rmSync(wtPath, { recursive: true, force: true });
6106
+ if (!admin) return;
6107
+ try {
6108
+ const layout = discoverRepository(repoRoot);
6109
+ if (!layout.commonGitDir) return;
6110
+ const adminPath = physicalPath(admin);
6111
+ const worktreesAdmin = physicalPath(path11.join(layout.commonGitDir, "worktrees"));
6112
+ if (isWithin(worktreesAdmin, adminPath) && adminPath !== worktreesAdmin) fs13.rmSync(adminPath, { recursive: true, force: true });
6113
+ } catch {
6114
+ }
6115
+ }
5491
6116
  function gitHasCommitSince(repoRoot, sinceMs, files) {
5492
6117
  if (!files.length) return false;
5493
6118
  try {
5494
- const out = execFileSync10(
6119
+ const out = execFileSync12(
5495
6120
  "git",
5496
6121
  ["log", "-1", "--format=%H", `--since=@${Math.floor(sinceMs / 1e3)}`, "--", ...files],
5497
6122
  { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
@@ -5504,7 +6129,7 @@ function gitHasCommitSince(repoRoot, sinceMs, files) {
5504
6129
  function resyncStaleIndexEntries(repoRoot) {
5505
6130
  let cachedPaths = [];
5506
6131
  try {
5507
- const out = execFileSync10("git", ["diff", "--cached", "--name-only", "-z", "HEAD"], {
6132
+ const out = execFileSync12("git", ["diff", "--cached", "--name-only", "-z", "HEAD"], {
5508
6133
  cwd: repoRoot,
5509
6134
  encoding: "utf8",
5510
6135
  stdio: ["ignore", "pipe", "ignore"]
@@ -5515,7 +6140,7 @@ function resyncStaleIndexEntries(repoRoot) {
5515
6140
  }
5516
6141
  if (cachedPaths.length === 0) return 0;
5517
6142
  try {
5518
- execFileSync10("git", ["reset", "-q", "HEAD"], {
6143
+ execFileSync12("git", ["reset", "-q", "HEAD"], {
5519
6144
  cwd: repoRoot,
5520
6145
  stdio: ["ignore", "ignore", "ignore"]
5521
6146
  });
@@ -5529,7 +6154,7 @@ function gcCoordination(directory = process.cwd(), options = {}) {
5529
6154
  const force = Boolean(options.force);
5530
6155
  const staleDays = Number.isFinite(options.staleDays) ? Math.max(0, options.staleDays) : 14;
5531
6156
  const layout = discoverRepository(directory);
5532
- const dbPath = path10.join(layout.coordDir, "state.db");
6157
+ const dbPath = path11.join(layout.coordDir, "state.db");
5533
6158
  const report = {
5534
6159
  ok: true,
5535
6160
  dryRun,
@@ -5547,7 +6172,7 @@ function gcCoordination(directory = process.cwd(), options = {}) {
5547
6172
  prunedDeadAgents: 0,
5548
6173
  prunedArtifacts: 0
5549
6174
  };
5550
- if (!fs12.existsSync(dbPath)) {
6175
+ if (!fs13.existsSync(dbPath)) {
5551
6176
  report.nothingToClean = true;
5552
6177
  return report;
5553
6178
  }
@@ -5591,18 +6216,25 @@ function gcCoordination(directory = process.cwd(), options = {}) {
5591
6216
  const pinnedTaskIds = new Set(
5592
6217
  openHandoffs.map((h) => h.task_id).filter((id) => Boolean(id))
5593
6218
  );
5594
- const worktreesDir = physicalPath(path10.join(layout.coordDir, "worktrees"));
5595
- if (fs12.existsSync(worktreesDir)) {
5596
- if (!dryRun) {
6219
+ const worktreesDir = physicalPath(path11.join(layout.coordDir, "worktrees"));
6220
+ const adoptedPaths = new Set(
6221
+ engine.worktrees.listRegistrations().filter((row) => row.provenance === "adopted").map((row) => {
5597
6222
  try {
5598
- execFileSync10("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
6223
+ return physicalPath(row.worktreePath);
5599
6224
  } catch {
6225
+ return row.worktreePath;
5600
6226
  }
5601
- }
6227
+ })
6228
+ );
6229
+ if (fs13.existsSync(worktreesDir)) {
5602
6230
  const listed = engine.worktrees.listWorktrees();
5603
6231
  for (const wt of listed) {
5604
6232
  const wtPath = physicalPath(wt.path);
5605
6233
  if (!isWithin(worktreesDir, wtPath) || wtPath === worktreesDir) continue;
6234
+ if (adoptedPaths.has(wtPath)) {
6235
+ report.preservedWorktrees.push({ path: wtPath, branch: wt.branch, reason: "adopted" });
6236
+ continue;
6237
+ }
5606
6238
  if (activeWorktreePaths.has(wtPath)) {
5607
6239
  report.preservedWorktrees.push({ path: wtPath, branch: wt.branch, reason: "active-session" });
5608
6240
  continue;
@@ -5623,44 +6255,33 @@ function gcCoordination(directory = process.cwd(), options = {}) {
5623
6255
  const removeBranch = Boolean(wt.branch && wt.branch.startsWith("kith/") && (!handoffBranches.has(wt.branch) || force));
5624
6256
  if (removeBranch) report.deletedBranches.push(wt.branch);
5625
6257
  if (!dryRun) {
5626
- try {
5627
- execFileSync10("git", ["worktree", "remove", ...force ? ["--force"] : [], wtPath], {
5628
- cwd: layout.checkoutRoot,
5629
- stdio: ["ignore", "pipe", "pipe"]
5630
- });
5631
- } catch {
5632
- fs12.rmSync(wtPath, { recursive: true, force: true });
5633
- try {
5634
- execFileSync10("git", ["worktree", "prune"], { cwd: layout.checkoutRoot, stdio: ["ignore", "ignore", "ignore"] });
5635
- } catch {
5636
- }
5637
- }
6258
+ removeCreatedWorktree(layout.checkoutRoot, wtPath, force);
5638
6259
  if (removeBranch && wt.branch) {
5639
6260
  try {
5640
- execFileSync10("git", ["branch", "-D", wt.branch], { cwd: layout.checkoutRoot, stdio: ["ignore", "pipe", "pipe"] });
6261
+ execFileSync12("git", ["branch", "-D", wt.branch], { cwd: layout.checkoutRoot, stdio: ["ignore", "pipe", "pipe"] });
5641
6262
  } catch {
5642
6263
  }
5643
6264
  }
5644
6265
  }
5645
6266
  }
5646
6267
  const remaining = new Set(engine.worktrees.listWorktrees().map((w) => physicalPath(w.path)));
5647
- for (const entry of fs12.readdirSync(worktreesDir)) {
5648
- const orphan = physicalPath(path10.join(worktreesDir, entry));
5649
- if (remaining.has(orphan) || activeWorktreePaths.has(orphan) || !force && handoffWorktrees.has(orphan)) continue;
6268
+ for (const entry of fs13.readdirSync(worktreesDir)) {
6269
+ const orphan = physicalPath(path11.join(worktreesDir, entry));
6270
+ if (remaining.has(orphan) || activeWorktreePaths.has(orphan) || adoptedPaths.has(orphan) || !force && handoffWorktrees.has(orphan)) continue;
5650
6271
  report.removedWorktrees.push(orphan);
5651
- if (!dryRun) fs12.rmSync(orphan, { recursive: true, force: true });
6272
+ if (!dryRun) fs13.rmSync(orphan, { recursive: true, force: true });
5652
6273
  }
5653
6274
  }
5654
6275
  for (const dirName of ["snapshots", "quarantine"]) {
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);
6276
+ const dir = path11.join(layout.coordDir, dirName);
6277
+ if (!fs13.existsSync(dir)) continue;
6278
+ for (const entry of fs13.readdirSync(dir)) {
6279
+ const full = path11.join(dir, entry);
5659
6280
  try {
5660
- const stat = fs12.lstatSync(full);
6281
+ const stat = fs13.lstatSync(full);
5661
6282
  if (stat.mtimeMs < cutoff) {
5662
6283
  report.prunedArtifacts++;
5663
- if (!dryRun) fs12.rmSync(full, { recursive: true, force: true });
6284
+ if (!dryRun) fs13.rmSync(full, { recursive: true, force: true });
5664
6285
  }
5665
6286
  } catch {
5666
6287
  }
@@ -5735,26 +6356,26 @@ function sleepSync(ms) {
5735
6356
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
5736
6357
  }
5737
6358
  function withCommitLock(coordDir, fn, timeoutMs = 15e3) {
5738
- fs13.mkdirSync(coordDir, { recursive: true, mode: 448 });
5739
- const lockPath = path11.join(coordDir, "commit.lock");
6359
+ fs14.mkdirSync(coordDir, { recursive: true, mode: 448 });
6360
+ const lockPath = path12.join(coordDir, "commit.lock");
5740
6361
  const started = Date.now();
5741
6362
  let fd;
5742
6363
  while (true) {
5743
6364
  try {
5744
- fd = fs13.openSync(lockPath, "wx", 384);
5745
- fs13.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
6365
+ fd = fs14.openSync(lockPath, "wx", 384);
6366
+ fs14.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
5746
6367
  break;
5747
6368
  } catch (err) {
5748
6369
  if (err.code !== "EEXIST") throw err;
5749
6370
  try {
5750
- const raw = JSON.parse(fs13.readFileSync(lockPath, "utf8"));
6371
+ const raw = JSON.parse(fs14.readFileSync(lockPath, "utf8"));
5751
6372
  if (raw.pid && raw.pid > 0) {
5752
6373
  try {
5753
6374
  process.kill(raw.pid, 0);
5754
6375
  } catch (killErr) {
5755
6376
  if (killErr.code === "ESRCH") {
5756
6377
  try {
5757
- fs13.unlinkSync(lockPath);
6378
+ fs14.unlinkSync(lockPath);
5758
6379
  continue;
5759
6380
  } catch {
5760
6381
  }
@@ -5774,12 +6395,12 @@ function withCommitLock(coordDir, fn, timeoutMs = 15e3) {
5774
6395
  } finally {
5775
6396
  if (fd !== void 0) {
5776
6397
  try {
5777
- fs13.closeSync(fd);
6398
+ fs14.closeSync(fd);
5778
6399
  } catch {
5779
6400
  }
5780
6401
  }
5781
6402
  try {
5782
- fs13.unlinkSync(lockPath);
6403
+ fs14.unlinkSync(lockPath);
5783
6404
  } catch {
5784
6405
  }
5785
6406
  }
@@ -5855,6 +6476,20 @@ function commitScopedFiles(engine, params) {
5855
6476
  }
5856
6477
  const primaryAgentId = params.agentId ?? [...callerAgentIds][0] ?? null;
5857
6478
  const worktreeRoot = (primaryAgentId ? engine.fencing.getAgent(primaryAgentId)?.worktree_path : null) ?? engine.coordDb.repoRoot;
6479
+ if (primaryAgentId) {
6480
+ const adoption = engine.worktrees.liveAdoption(engine.fencing.getAgent(primaryAgentId));
6481
+ if (adoption?.commitError) {
6482
+ return {
6483
+ ok: false,
6484
+ commit: null,
6485
+ branch: null,
6486
+ files: [],
6487
+ agentId: primaryAgentId,
6488
+ message,
6489
+ error: adoption.commitError
6490
+ };
6491
+ }
6492
+ }
5858
6493
  const dirtyFiles = listDirtyFiles(worktreeRoot);
5859
6494
  const activeLocks = engine.locks.listLocks();
5860
6495
  let targetFiles = [];
@@ -5915,7 +6550,7 @@ function commitScopedFiles(engine, params) {
5915
6550
  return withCommitLock(engine.coordDb.coordDir, () => {
5916
6551
  let headBefore = null;
5917
6552
  try {
5918
- headBefore = execFileSync11("git", ["rev-parse", "--verify", "HEAD"], {
6553
+ headBefore = execFileSync13("git", ["rev-parse", "--verify", "HEAD"], {
5919
6554
  cwd: worktreeRoot,
5920
6555
  encoding: "utf8",
5921
6556
  stdio: ["ignore", "pipe", "ignore"]
@@ -5925,7 +6560,7 @@ function commitScopedFiles(engine, params) {
5925
6560
  }
5926
6561
  let branch = null;
5927
6562
  try {
5928
- branch = execFileSync11("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
6563
+ branch = execFileSync13("git", ["symbolic-ref", "-q", "--short", "HEAD"], {
5929
6564
  cwd: worktreeRoot,
5930
6565
  encoding: "utf8",
5931
6566
  stdio: ["ignore", "pipe", "ignore"]
@@ -5933,32 +6568,32 @@ function commitScopedFiles(engine, params) {
5933
6568
  } catch {
5934
6569
  branch = null;
5935
6570
  }
5936
- const tempIndex = path11.join(
6571
+ const tempIndex = path12.join(
5937
6572
  engine.coordDb.coordDir,
5938
6573
  "shadow-index",
5939
6574
  `commit-${process.pid}-${crypto11.randomBytes(6).toString("hex")}.index`
5940
6575
  );
5941
- fs13.mkdirSync(path11.dirname(tempIndex), { recursive: true, mode: 448 });
6576
+ fs14.mkdirSync(path12.dirname(tempIndex), { recursive: true, mode: 448 });
5942
6577
  const gitEnv = { ...process.env, GIT_INDEX_FILE: tempIndex };
5943
6578
  try {
5944
6579
  if (headBefore) {
5945
- execFileSync11("git", ["read-tree", headBefore], {
6580
+ execFileSync13("git", ["read-tree", headBefore], {
5946
6581
  cwd: worktreeRoot,
5947
6582
  env: gitEnv,
5948
6583
  stdio: ["ignore", "pipe", "pipe"]
5949
6584
  });
5950
6585
  }
5951
- execFileSync11("git", ["add", "-A", "--", ...targetFiles], {
6586
+ execFileSync13("git", ["add", "-A", "--", ...targetFiles], {
5952
6587
  cwd: worktreeRoot,
5953
6588
  env: gitEnv,
5954
6589
  stdio: ["ignore", "pipe", "pipe"]
5955
6590
  });
5956
- const diffOut = headBefore ? execFileSync11("git", ["diff-index", "--cached", "--name-only", "-z", headBefore], {
6591
+ const diffOut = headBefore ? execFileSync13("git", ["diff-index", "--cached", "--name-only", "-z", headBefore], {
5957
6592
  cwd: worktreeRoot,
5958
6593
  env: gitEnv,
5959
6594
  encoding: "utf8",
5960
6595
  stdio: ["ignore", "pipe", "pipe"]
5961
- }) : execFileSync11("git", ["ls-files", "--cached", "-z"], {
6596
+ }) : execFileSync13("git", ["ls-files", "--cached", "-z"], {
5962
6597
  cwd: worktreeRoot,
5963
6598
  env: gitEnv,
5964
6599
  encoding: "utf8",
@@ -5976,14 +6611,14 @@ function commitScopedFiles(engine, params) {
5976
6611
  error: "Specified files have no changes relative to HEAD."
5977
6612
  };
5978
6613
  }
5979
- const treeSha = execFileSync11("git", ["write-tree"], {
6614
+ const treeSha = execFileSync13("git", ["write-tree"], {
5980
6615
  cwd: worktreeRoot,
5981
6616
  env: gitEnv,
5982
6617
  encoding: "utf8",
5983
6618
  stdio: ["ignore", "pipe", "pipe"]
5984
6619
  }).trim();
5985
6620
  const commitArgs = ["commit-tree", treeSha, ...headBefore ? ["-p", headBefore] : [], "-m", message];
5986
- const commitSha = execFileSync11("git", commitArgs, {
6621
+ const commitSha = execFileSync13("git", commitArgs, {
5987
6622
  cwd: worktreeRoot,
5988
6623
  env: gitEnv,
5989
6624
  encoding: "utf8",
@@ -5991,13 +6626,13 @@ function commitScopedFiles(engine, params) {
5991
6626
  }).trim();
5992
6627
  const subject2 = message.split(/\r?\n/, 1)[0];
5993
6628
  const oldRef = headBefore ?? "0000000000000000000000000000000000000000";
5994
- execFileSync11("git", ["update-ref", "-m", `commit: ${subject2}`, "HEAD", commitSha, oldRef], {
6629
+ execFileSync13("git", ["update-ref", "-m", `commit: ${subject2}`, "HEAD", commitSha, oldRef], {
5995
6630
  cwd: worktreeRoot,
5996
6631
  stdio: ["ignore", "pipe", "pipe"]
5997
6632
  });
5998
6633
  for (let attempt = 0; attempt < 5; attempt++) {
5999
6634
  try {
6000
- execFileSync11("git", ["reset", "-q", "HEAD", "--", ...committedFiles], {
6635
+ execFileSync13("git", ["reset", "-q", "HEAD", "--", ...committedFiles], {
6001
6636
  cwd: worktreeRoot,
6002
6637
  stdio: ["ignore", "pipe", "pipe"]
6003
6638
  });
@@ -6023,7 +6658,7 @@ function commitScopedFiles(engine, params) {
6023
6658
  };
6024
6659
  } finally {
6025
6660
  try {
6026
- fs13.unlinkSync(tempIndex);
6661
+ fs14.unlinkSync(tempIndex);
6027
6662
  } catch {
6028
6663
  }
6029
6664
  }
@@ -6033,6 +6668,7 @@ function commitScopedFiles(engine, params) {
6033
6668
  // src/core/mode.ts
6034
6669
  var WORKFLOW_MODES = ["worktrees", "main"];
6035
6670
  var MAIN_MODE_NOTE = "isolateWorktree was ignored: this repository works in the main checkout. Change the mode with `kith mode worktrees`.";
6671
+ var ADOPT_MAIN_MODE_NOTE = "Main-checkout mode: this adopted worktree is the workspace for claims and kith commit. Completion can run verification there and does not integrate the branch. Change the mode with `kith mode worktrees`.";
6036
6672
  var workflowModeFrom = (value) => value === "main" ? "main" : "worktrees";
6037
6673
  function parseWorkflowMode(value) {
6038
6674
  if (!WORKFLOW_MODES.includes(value)) throw new Error(`Mode must be one of: ${WORKFLOW_MODES.join(", ")}.`);
@@ -6040,10 +6676,10 @@ function parseWorkflowMode(value) {
6040
6676
  }
6041
6677
 
6042
6678
  // src/core/merge-train.ts
6043
- import { execFileSync as execFileSync12, execSync } from "child_process";
6679
+ import { execFileSync as execFileSync14, execSync } from "child_process";
6044
6680
  import crypto12 from "crypto";
6045
- import fs14 from "fs";
6046
- import path12 from "path";
6681
+ import fs15 from "fs";
6682
+ import path13 from "path";
6047
6683
  function runVerificationCommand(command, cwd, env, timeoutMs = Number(process.env.KITH_MERGE_VERIFY_TIMEOUT_MS) || 3e5) {
6048
6684
  try {
6049
6685
  const out = execSync(command, {
@@ -6102,16 +6738,16 @@ var SpeculativeMergeTrain = class {
6102
6738
  now
6103
6739
  );
6104
6740
  });
6105
- const stageDir = path12.join(this.coordDb.coordDir, "worktrees", `_merge_train_${id}`);
6106
- const lockPath = path12.join(this.coordDb.coordDir, "merge-train.lock");
6741
+ const stageDir = path13.join(this.coordDb.coordDir, "worktrees", `_merge_train_${id}`);
6742
+ const lockPath = path13.join(this.coordDb.coordDir, "merge-train.lock");
6107
6743
  let lockFd;
6108
6744
  const waitMs = Math.max(0, params.waitTimeoutMs ?? 0);
6109
6745
  const lockDeadline = Date.now() + waitMs;
6110
6746
  try {
6111
6747
  while (lockFd === void 0) {
6112
6748
  try {
6113
- lockFd = fs14.openSync(lockPath, "wx", 384);
6114
- fs14.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, entryId: id }));
6749
+ lockFd = fs15.openSync(lockPath, "wx", 384);
6750
+ fs15.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, entryId: id }));
6115
6751
  } catch {
6116
6752
  if (Date.now() >= lockDeadline) {
6117
6753
  throw new Error("Merge train is busy. If its owner crashed, inspect .coord/merge-train.lock before removing it.");
@@ -6133,13 +6769,13 @@ var SpeculativeMergeTrain = class {
6133
6769
  }
6134
6770
  }
6135
6771
  if (params.worktreePath) {
6136
- const statusOut = execFileSync12("git", ["status", "--porcelain"], {
6772
+ const statusOut = execFileSync14("git", ["status", "--porcelain"], {
6137
6773
  cwd: params.worktreePath,
6138
6774
  encoding: "utf8"
6139
6775
  }).trim();
6140
6776
  if (statusOut.length > 0) {
6141
- execFileSync12("git", ["add", "-A"], { cwd: params.worktreePath, env: sessionEnv, stdio: "ignore" });
6142
- execFileSync12(
6777
+ execFileSync14("git", ["add", "-A"], { cwd: params.worktreePath, env: sessionEnv, stdio: "ignore" });
6778
+ execFileSync14(
6143
6779
  "git",
6144
6780
  [
6145
6781
  "commit",
@@ -6150,25 +6786,25 @@ var SpeculativeMergeTrain = class {
6150
6786
  );
6151
6787
  }
6152
6788
  }
6153
- const sourceSha = execFileSync12("git", ["rev-parse", "--verify", "--end-of-options", `${params.branch}^{commit}`], {
6789
+ const sourceSha = execFileSync14("git", ["rev-parse", "--verify", "--end-of-options", `${params.branch}^{commit}`], {
6154
6790
  cwd: this.coordDb.repoRoot,
6155
6791
  encoding: "utf8",
6156
6792
  stdio: ["ignore", "pipe", "pipe"]
6157
6793
  }).trim();
6158
6794
  this.requireNoTargetOverlap(this.pathsChangedBySource(sourceSha));
6159
6795
  this.cleanupStageWorktree(stageDir);
6160
- execFileSync12("git", ["worktree", "add", "--detach", stageDir, baseHead], {
6796
+ execFileSync14("git", ["worktree", "add", "--detach", stageDir, baseHead], {
6161
6797
  cwd: this.coordDb.repoRoot,
6162
6798
  stdio: "ignore"
6163
6799
  });
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);
6800
+ const rootNodeModules = path13.join(this.coordDb.repoRoot, "node_modules");
6801
+ const stageNodeModules = path13.join(stageDir, "node_modules");
6802
+ const hydratedNodeModules = fs15.existsSync(rootNodeModules) && !fs15.existsSync(stageNodeModules);
6167
6803
  if (hydratedNodeModules) {
6168
- fs14.symlinkSync(rootNodeModules, stageNodeModules, process.platform === "win32" ? "junction" : "dir");
6804
+ fs15.symlinkSync(rootNodeModules, stageNodeModules, process.platform === "win32" ? "junction" : "dir");
6169
6805
  }
6170
6806
  try {
6171
- execFileSync12(
6807
+ execFileSync14(
6172
6808
  "git",
6173
6809
  ["merge", "--no-ff", "-m", `Merge branch '${params.branch}' (${params.agentId})`, sourceSha],
6174
6810
  {
@@ -6179,7 +6815,7 @@ var SpeculativeMergeTrain = class {
6179
6815
  }
6180
6816
  );
6181
6817
  } catch {
6182
- const conflictedFiles = execFileSync12("git", ["diff", "--name-only", "--diff-filter=U", "-z"], {
6818
+ const conflictedFiles = execFileSync14("git", ["diff", "--name-only", "--diff-filter=U", "-z"], {
6183
6819
  cwd: stageDir,
6184
6820
  encoding: "utf8"
6185
6821
  }).split("\0").filter(Boolean);
@@ -6190,11 +6826,11 @@ var SpeculativeMergeTrain = class {
6190
6826
  if (params.verificationCmd) {
6191
6827
  diagnostics = runVerificationCommand(params.verificationCmd, stageDir, sessionEnv, params.verificationTimeoutMs);
6192
6828
  }
6193
- const stageChanges = execFileSync12("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6829
+ const stageChanges = execFileSync14("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6194
6830
  cwd: stageDir,
6195
6831
  encoding: "utf8"
6196
6832
  }).split("\0").filter(Boolean);
6197
- const unchangedHydration = hydratedNodeModules && fs14.lstatSync(stageNodeModules, { throwIfNoEntry: false })?.isSymbolicLink() && physicalPath(stageNodeModules) === physicalPath(rootNodeModules);
6833
+ const unchangedHydration = hydratedNodeModules && fs15.lstatSync(stageNodeModules, { throwIfNoEntry: false })?.isSymbolicLink() && physicalPath(stageNodeModules) === physicalPath(rootNodeModules);
6198
6834
  if (this.gitHead(stageDir) !== verifiedSha || stageChanges.some((change) => !(unchangedHydration && change === "?? node_modules"))) {
6199
6835
  throw new Error("Verification changed the staging checkout. Apply fixes in the source worktree and retry with a read-only check.");
6200
6836
  }
@@ -6203,7 +6839,7 @@ var SpeculativeMergeTrain = class {
6203
6839
  }
6204
6840
  this.fencing.assertSession(params.agentId);
6205
6841
  this.requireNoTargetOverlap(this.pathsBetween(baseHead, verifiedSha));
6206
- execFileSync12("git", ["merge", "--ff-only", verifiedSha], {
6842
+ execFileSync14("git", ["merge", "--ff-only", verifiedSha], {
6207
6843
  cwd: this.coordDb.repoRoot,
6208
6844
  stdio: "ignore"
6209
6845
  });
@@ -6251,16 +6887,16 @@ var SpeculativeMergeTrain = class {
6251
6887
  };
6252
6888
  } finally {
6253
6889
  if (lockFd !== void 0) {
6254
- fs14.closeSync(lockFd);
6255
- fs14.unlinkSync(lockPath);
6890
+ fs15.closeSync(lockFd);
6891
+ fs15.unlinkSync(lockPath);
6256
6892
  }
6257
6893
  }
6258
6894
  }
6259
6895
  gitHead(cwd) {
6260
- return execFileSync12("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
6896
+ return execFileSync14("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
6261
6897
  }
6262
6898
  gitBranch(cwd) {
6263
- return execFileSync12("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
6899
+ return execFileSync14("git", ["symbolic-ref", "--quiet", "--short", "HEAD"], {
6264
6900
  cwd,
6265
6901
  encoding: "utf8",
6266
6902
  stdio: ["ignore", "pipe", "ignore"]
@@ -6268,7 +6904,7 @@ var SpeculativeMergeTrain = class {
6268
6904
  }
6269
6905
  /** Paths with uncommitted changes in the target checkout. Untracked directories end in `/`. Kith's own state is excluded. */
6270
6906
  dirtyTargetPaths() {
6271
- const records = execFileSync12("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6907
+ const records = execFileSync14("git", ["status", "--porcelain", "-z", "--untracked-files=normal"], {
6272
6908
  cwd: this.coordDb.repoRoot,
6273
6909
  encoding: "utf8"
6274
6910
  }).split("\0").filter(Boolean);
@@ -6281,7 +6917,7 @@ var SpeculativeMergeTrain = class {
6281
6917
  return paths;
6282
6918
  }
6283
6919
  diffNames(...refs) {
6284
- return execFileSync12("git", ["diff", "--name-only", "-z", "--no-renames", ...refs], {
6920
+ return execFileSync14("git", ["diff", "--name-only", "-z", "--no-renames", ...refs], {
6285
6921
  cwd: this.coordDb.repoRoot,
6286
6922
  encoding: "utf8"
6287
6923
  }).split("\0").filter(Boolean);
@@ -6289,7 +6925,7 @@ var SpeculativeMergeTrain = class {
6289
6925
  /** Paths a merge of `sourceSha` will bring into the target: the source's own changes since the merge base. */
6290
6926
  pathsChangedBySource(sourceSha) {
6291
6927
  try {
6292
- const base = execFileSync12("git", ["merge-base", "HEAD", sourceSha], {
6928
+ const base = execFileSync14("git", ["merge-base", "HEAD", sourceSha], {
6293
6929
  cwd: this.coordDb.repoRoot,
6294
6930
  encoding: "utf8",
6295
6931
  stdio: ["ignore", "pipe", "ignore"]
@@ -6318,18 +6954,18 @@ var SpeculativeMergeTrain = class {
6318
6954
  }
6319
6955
  }
6320
6956
  cleanupStageWorktree(stageDir) {
6321
- if (!fs14.existsSync(stageDir)) return;
6957
+ if (!fs15.existsSync(stageDir)) return;
6322
6958
  try {
6323
- execFileSync12("git", ["worktree", "remove", "--force", stageDir], {
6959
+ execFileSync14("git", ["worktree", "remove", "--force", stageDir], {
6324
6960
  cwd: this.coordDb.repoRoot,
6325
6961
  stdio: "ignore"
6326
6962
  });
6327
6963
  } catch {
6328
- if (fs14.existsSync(stageDir)) {
6329
- fs14.rmSync(stageDir, { recursive: true, force: true });
6964
+ if (fs15.existsSync(stageDir)) {
6965
+ fs15.rmSync(stageDir, { recursive: true, force: true });
6330
6966
  }
6331
6967
  try {
6332
- execFileSync12("git", ["worktree", "prune"], {
6968
+ execFileSync14("git", ["worktree", "prune"], {
6333
6969
  cwd: this.coordDb.repoRoot,
6334
6970
  stdio: "ignore"
6335
6971
  });
@@ -6347,11 +6983,11 @@ var SpeculativeMergeTrain = class {
6347
6983
  };
6348
6984
 
6349
6985
  // src/core/shadow-git.ts
6350
- import { execFileSync as execFileSync13 } from "child_process";
6986
+ import { execFileSync as execFileSync15 } from "child_process";
6351
6987
  import crypto13 from "crypto";
6352
- import fs15 from "fs";
6988
+ import fs16 from "fs";
6353
6989
  import os2 from "os";
6354
- import path13 from "path";
6990
+ import path14 from "path";
6355
6991
  function isGitBlob(value) {
6356
6992
  return typeof value === "string" && /^[0-9a-f]{40,64}$/i.test(value);
6357
6993
  }
@@ -6369,7 +7005,7 @@ var ShadowGitEngine = class {
6369
7005
  fencing;
6370
7006
  isGitRepository(dir = this.coordDb.repoRoot) {
6371
7007
  try {
6372
- execFileSync13("git", ["rev-parse", "--is-inside-work-tree"], {
7008
+ execFileSync15("git", ["rev-parse", "--is-inside-work-tree"], {
6373
7009
  cwd: dir,
6374
7010
  stdio: "ignore"
6375
7011
  });
@@ -6380,7 +7016,7 @@ var ShadowGitEngine = class {
6380
7016
  }
6381
7017
  blobAt(commit, filePath) {
6382
7018
  try {
6383
- const out = execFileSync13("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", filePath], { cwd: this.coordDb.repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
7019
+ const out = execFileSync15("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", filePath], { cwd: this.coordDb.repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
6384
7020
  return /^\d+ blob ([0-9a-f]+)\t/.exec(out)?.[1] ?? null;
6385
7021
  } catch {
6386
7022
  return null;
@@ -6388,7 +7024,7 @@ var ShadowGitEngine = class {
6388
7024
  }
6389
7025
  getHeadCommit(dir = this.coordDb.repoRoot) {
6390
7026
  try {
6391
- return execFileSync13("git", ["rev-parse", "HEAD"], {
7027
+ return execFileSync15("git", ["rev-parse", "HEAD"], {
6392
7028
  cwd: dir,
6393
7029
  encoding: "utf8",
6394
7030
  stdio: ["ignore", "pipe", "ignore"]
@@ -6400,7 +7036,7 @@ var ShadowGitEngine = class {
6400
7036
  getShadowIndexPath(agentId) {
6401
7037
  const safeId = agentId.replace(/[^a-zA-Z0-9_-]/g, "_");
6402
7038
  const epoch = this.fencing.assertSession(agentId);
6403
- return path13.join(this.coordDb.coordDir, "shadow-index", `${safeId}-${epoch}.index`);
7039
+ return path14.join(this.coordDb.coordDir, "shadow-index", `${safeId}-${epoch}.index`);
6404
7040
  }
6405
7041
  /**
6406
7042
  * Updates an agent's ephemeral shadow Git index (`.coord/shadow-index/<agent-id>.index`)
@@ -6416,23 +7052,23 @@ var ShadowGitEngine = class {
6416
7052
  if (!headCommit) return null;
6417
7053
  const shadowIndex = this.getShadowIndexPath(params.agentId);
6418
7054
  const env = { ...process.env, GIT_INDEX_FILE: shadowIndex };
6419
- if (!fs15.existsSync(shadowIndex)) {
6420
- execFileSync13("git", ["read-tree", headCommit], {
7055
+ if (!fs16.existsSync(shadowIndex)) {
7056
+ execFileSync15("git", ["read-tree", headCommit], {
6421
7057
  cwd: targetDir,
6422
7058
  env,
6423
7059
  stdio: "ignore"
6424
7060
  });
6425
- fs15.writeFileSync(`${shadowIndex}.base`, headCommit);
7061
+ fs16.writeFileSync(`${shadowIndex}.base`, headCommit);
6426
7062
  } else {
6427
7063
  this.rebaseShadowIndex(shadowIndex, targetDir, env, headCommit);
6428
7064
  }
6429
7065
  if (params.worktreeDir && (!params.modifiedFiles || params.modifiedFiles.length === 0)) {
6430
- execFileSync13("git", ["read-tree", headCommit], {
7066
+ execFileSync15("git", ["read-tree", headCommit], {
6431
7067
  cwd: targetDir,
6432
7068
  env,
6433
7069
  stdio: "ignore"
6434
7070
  });
6435
- execFileSync13("git", ["add", "-A"], {
7071
+ execFileSync15("git", ["add", "-A"], {
6436
7072
  cwd: targetDir,
6437
7073
  env,
6438
7074
  stdio: "ignore"
@@ -6442,34 +7078,34 @@ var ShadowGitEngine = class {
6442
7078
  for (const mod of params.modifiedFiles) {
6443
7079
  const relPath = LockEngine.normalizeFile(targetDir, mod.filePath);
6444
7080
  if (ignored.has(relPath)) continue;
6445
- const absPath = path13.join(targetDir, relPath);
6446
- const content = mod.content ?? (fs15.existsSync(absPath) ? fs15.readFileSync(absPath, "utf8") : null);
7081
+ const absPath = path14.join(targetDir, relPath);
7082
+ const content = mod.content ?? (fs16.existsSync(absPath) ? fs16.readFileSync(absPath, "utf8") : null);
6447
7083
  if (content === null) {
6448
7084
  {
6449
- execFileSync13("git", ["--literal-pathspecs", "update-index", "--force-remove", "--", relPath], {
7085
+ execFileSync15("git", ["--literal-pathspecs", "update-index", "--force-remove", "--", relPath], {
6450
7086
  cwd: targetDir,
6451
7087
  env,
6452
7088
  stdio: "ignore"
6453
7089
  });
6454
7090
  }
6455
7091
  } else {
6456
- const tracked = execFileSync13("git", ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", relPath], {
7092
+ const tracked = execFileSync15("git", ["--literal-pathspecs", "ls-files", "--stage", "-z", "--", relPath], {
6457
7093
  cwd: targetDir,
6458
7094
  env,
6459
7095
  encoding: "utf8"
6460
7096
  }).split("\0").find(Boolean);
6461
7097
  const trackedMode = tracked?.split(" ")[0];
6462
- const stat = fs15.existsSync(absPath) ? fs15.lstatSync(absPath) : null;
7098
+ const stat = fs16.existsSync(absPath) ? fs16.lstatSync(absPath) : null;
6463
7099
  if (trackedMode && !["100644", "100755"].includes(trackedMode) || stat?.isSymbolicLink()) {
6464
7100
  throw new Error(`Cannot report symlinks or special entries as source content: ${relPath}`);
6465
7101
  }
6466
7102
  const mode = trackedMode ?? (stat && stat.mode & 73 ? "100755" : "100644");
6467
- const blobSha = execFileSync13("git", ["hash-object", "-w", "--stdin"], {
7103
+ const blobSha = execFileSync15("git", ["hash-object", "-w", "--stdin"], {
6468
7104
  cwd: targetDir,
6469
7105
  input: content,
6470
7106
  encoding: "utf8"
6471
7107
  }).trim();
6472
- execFileSync13(
7108
+ execFileSync15(
6473
7109
  "git",
6474
7110
  ["update-index", "--add", "--cacheinfo", `${mode},${blobSha},${relPath}`],
6475
7111
  {
@@ -6481,12 +7117,12 @@ var ShadowGitEngine = class {
6481
7117
  }
6482
7118
  }
6483
7119
  }
6484
- const treeSha = execFileSync13("git", ["write-tree"], {
7120
+ const treeSha = execFileSync15("git", ["write-tree"], {
6485
7121
  cwd: targetDir,
6486
7122
  env,
6487
7123
  encoding: "utf8"
6488
7124
  }).trim();
6489
- const shadowCommitSha = execFileSync13(
7125
+ const shadowCommitSha = execFileSync15(
6490
7126
  "git",
6491
7127
  ["commit-tree", treeSha, "-p", headCommit, "-m", `kith-shadow:${params.agentId}`],
6492
7128
  {
@@ -6509,15 +7145,15 @@ var ShadowGitEngine = class {
6509
7145
  const baseFile = `${shadowIndex}.base`;
6510
7146
  let base = "";
6511
7147
  try {
6512
- base = fs15.readFileSync(baseFile, "utf8").trim();
7148
+ base = fs16.readFileSync(baseFile, "utf8").trim();
6513
7149
  } catch {
6514
7150
  }
6515
7151
  if (base === head) return;
6516
7152
  try {
6517
7153
  if (base) {
6518
- const raw = execFileSync13("git", ["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head], { cwd: dir, encoding: "utf8" }).split("\0");
7154
+ const raw = execFileSync15("git", ["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head], { cwd: dir, encoding: "utf8" }).split("\0");
6519
7155
  const staged = /* @__PURE__ */ new Map();
6520
- for (const line of execFileSync13("git", ["ls-files", "--stage", "-z"], { cwd: dir, env, encoding: "utf8" }).split("\0")) {
7156
+ for (const line of execFileSync15("git", ["ls-files", "--stage", "-z"], { cwd: dir, env, encoding: "utf8" }).split("\0")) {
6521
7157
  const m = /^\d+ ([0-9a-f]+) \d\t([\s\S]+)$/.exec(line);
6522
7158
  if (m) staged.set(m[2], m[1]);
6523
7159
  }
@@ -6532,9 +7168,9 @@ var ShadowGitEngine = class {
6532
7168
  const untouched = oldSha === zero ? mine === void 0 : mine === oldSha;
6533
7169
  if (untouched) info.push(newSha === zero ? `0 ${zero} ${file}` : `${newMode} ${newSha} ${file}`);
6534
7170
  }
6535
- if (info.length) execFileSync13("git", ["update-index", "--index-info", "-z"], { cwd: dir, env, input: info.join("\0") + "\0", stdio: ["pipe", "ignore", "ignore"] });
7171
+ if (info.length) execFileSync15("git", ["update-index", "--index-info", "-z"], { cwd: dir, env, input: info.join("\0") + "\0", stdio: ["pipe", "ignore", "ignore"] });
6536
7172
  }
6537
- fs15.writeFileSync(baseFile, head);
7173
+ fs16.writeFileSync(baseFile, head);
6538
7174
  } catch {
6539
7175
  }
6540
7176
  }
@@ -6580,7 +7216,7 @@ var ShadowGitEngine = class {
6580
7216
  probePairConflict(agentA, commitA, agentB, commitB) {
6581
7217
  this.fencing.assertSession(agentA);
6582
7218
  try {
6583
- const stdout = execFileSync13(
7219
+ const stdout = execFileSync15(
6584
7220
  "git",
6585
7221
  ["merge-tree", "--write-tree", "-z", commitA, commitB],
6586
7222
  {
@@ -6672,8 +7308,8 @@ var ShadowGitEngine = class {
6672
7308
  }
6673
7309
  /** Remove orphaned shadow Git index files left behind by dead or completed sessions. */
6674
7310
  pruneStaleShadowIndexes(dryRun = false) {
6675
- const indexDir = path13.join(this.coordDb.coordDir, "shadow-index");
6676
- if (!fs15.existsSync(indexDir)) return 0;
7311
+ const indexDir = path14.join(this.coordDb.coordDir, "shadow-index");
7312
+ if (!fs16.existsSync(indexDir)) return 0;
6677
7313
  const activeRows = this.coordDb.db.prepare(`
6678
7314
  SELECT a.id AS agent_id, s.epoch AS epoch
6679
7315
  FROM agents a JOIN agent_sessions s ON a.id = s.agent_id
@@ -6681,14 +7317,14 @@ var ShadowGitEngine = class {
6681
7317
  `).all();
6682
7318
  const keep = new Set(activeRows.map((r) => `${r.agent_id.replace(/[^a-zA-Z0-9_-]/g, "_")}-${r.epoch}.index`));
6683
7319
  let removed = 0;
6684
- for (const entry of fs15.readdirSync(indexDir, { withFileTypes: true })) {
7320
+ for (const entry of fs16.readdirSync(indexDir, { withFileTypes: true })) {
6685
7321
  if (!entry.isFile() || !entry.name.endsWith(".index") || keep.has(entry.name)) continue;
6686
7322
  if (dryRun) {
6687
7323
  removed++;
6688
7324
  continue;
6689
7325
  }
6690
7326
  try {
6691
- fs15.unlinkSync(path13.join(indexDir, entry.name));
7327
+ fs16.unlinkSync(path14.join(indexDir, entry.name));
6692
7328
  removed++;
6693
7329
  } catch {
6694
7330
  }
@@ -6751,7 +7387,7 @@ var ShadowGitEngine = class {
6751
7387
  const needMerge = parsed.filter((row) => !doomed.has(row.id) && row.severity === "text_conflict" && isGitBlob(row.details.baseBlob) && isGitBlob(row.details.blobA) && isGitBlob(row.details.blobB) && !mergeSettled.has(row.id));
6752
7388
  const batch = needMerge.slice(0, Math.max(0, maxMergeProbes));
6753
7389
  if (batch.length) {
6754
- const dir = fs15.mkdtempSync(path13.join(this.mergeProbeParent(), "kith-merge-probe-"));
7390
+ const dir = fs16.mkdtempSync(path14.join(this.mergeProbeParent(), "kith-merge-probe-"));
6755
7391
  stats.probeDir = dir;
6756
7392
  try {
6757
7393
  for (const row of batch) {
@@ -6761,7 +7397,7 @@ var ShadowGitEngine = class {
6761
7397
  else if (merged === "conflict") mergeSettled.add(row.id);
6762
7398
  }
6763
7399
  } finally {
6764
- fs15.rmSync(dir, { recursive: true, force: true });
7400
+ fs16.rmSync(dir, { recursive: true, force: true });
6765
7401
  }
6766
7402
  }
6767
7403
  for (const row of parsed) {
@@ -6793,7 +7429,7 @@ var ShadowGitEngine = class {
6793
7429
  for (let offset = 0; offset < files.length; offset += 200) {
6794
7430
  const chunk = files.slice(offset, offset + 200);
6795
7431
  stats.headReads++;
6796
- const out = execFileSync13("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", ...chunk], {
7432
+ const out = execFileSync15("git", ["--literal-pathspecs", "ls-tree", "-z", commit, "--", ...chunk], {
6797
7433
  cwd: this.coordDb.repoRoot,
6798
7434
  encoding: "utf8",
6799
7435
  stdio: ["ignore", "pipe", "ignore"],
@@ -6813,13 +7449,13 @@ var ShadowGitEngine = class {
6813
7449
  /** `conflict` is a real overlap. `error` is not cached, so a later read can retry the probe. */
6814
7450
  blobsMergeCleanly(dir, base, blobA, blobB) {
6815
7451
  const show = (sha, name) => {
6816
- const file = path13.join(dir, name);
6817
- const bytes = execFileSync13("git", ["cat-file", "blob", sha], {
7452
+ const file = path14.join(dir, name);
7453
+ const bytes = execFileSync15("git", ["cat-file", "blob", sha], {
6818
7454
  cwd: this.coordDb.repoRoot,
6819
7455
  stdio: ["ignore", "pipe", "ignore"],
6820
7456
  maxBuffer: 16 * 1024 * 1024
6821
7457
  });
6822
- fs15.writeFileSync(file, bytes);
7458
+ fs16.writeFileSync(file, bytes);
6823
7459
  return file;
6824
7460
  };
6825
7461
  try {
@@ -6827,7 +7463,7 @@ var ShadowGitEngine = class {
6827
7463
  const baseFile = show(base, "base");
6828
7464
  const theirs = show(blobB, "b");
6829
7465
  try {
6830
- execFileSync13("git", ["merge-file", ours, baseFile, theirs], { cwd: dir, stdio: "ignore" });
7466
+ execFileSync15("git", ["merge-file", ours, baseFile, theirs], { cwd: dir, stdio: "ignore" });
6831
7467
  return "clean";
6832
7468
  } catch (err) {
6833
7469
  const status = err.status;
@@ -6839,23 +7475,23 @@ var ShadowGitEngine = class {
6839
7475
  }
6840
7476
  /** Prefer the system temp dir. If that lives inside this checkout, step outside it. */
6841
7477
  mergeProbeParent() {
6842
- const repo = fs15.realpathSync(this.coordDb.repoRoot);
7478
+ const repo = fs16.realpathSync(this.coordDb.repoRoot);
6843
7479
  for (const candidate of [os2.tmpdir(), "/tmp", os2.homedir()]) {
6844
7480
  try {
6845
- const real = fs15.realpathSync(candidate);
6846
- const relative = path13.relative(repo, real);
6847
- if (relative.startsWith("..") || path13.isAbsolute(relative)) return real;
7481
+ const real = fs16.realpathSync(candidate);
7482
+ const relative = path14.relative(repo, real);
7483
+ if (relative.startsWith("..") || path14.isAbsolute(relative)) return real;
6848
7484
  } catch {
6849
7485
  }
6850
7486
  }
6851
- return fs15.realpathSync(os2.tmpdir());
7487
+ return fs16.realpathSync(os2.tmpdir());
6852
7488
  }
6853
7489
  hygieneCachePath() {
6854
- return path13.join(this.coordDb.coordDir, "conflict-hygiene.json");
7490
+ return path14.join(this.coordDb.coordDir, "conflict-hygiene.json");
6855
7491
  }
6856
7492
  readHygieneCache() {
6857
7493
  try {
6858
- const raw = JSON.parse(fs15.readFileSync(this.hygieneCachePath(), "utf8"));
7494
+ const raw = JSON.parse(fs16.readFileSync(this.hygieneCachePath(), "utf8"));
6859
7495
  const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
6860
7496
  return {
6861
7497
  head: typeof raw.head === "string" || raw.head === null ? raw.head : null,
@@ -6870,11 +7506,11 @@ var ShadowGitEngine = class {
6870
7506
  const file = this.hygieneCachePath();
6871
7507
  const tmp = `${file}.${process.pid}.tmp`;
6872
7508
  try {
6873
- fs15.writeFileSync(tmp, JSON.stringify(cache));
6874
- fs15.renameSync(tmp, file);
7509
+ fs16.writeFileSync(tmp, JSON.stringify(cache));
7510
+ fs16.renameSync(tmp, file);
6875
7511
  } catch {
6876
7512
  try {
6877
- fs15.unlinkSync(tmp);
7513
+ fs16.unlinkSync(tmp);
6878
7514
  } catch {
6879
7515
  }
6880
7516
  }
@@ -6899,15 +7535,15 @@ var ShadowGitEngine = class {
6899
7535
  };
6900
7536
 
6901
7537
  // src/core/workspace-contracts.ts
6902
- import { execFileSync as execFileSync14 } from "child_process";
6903
- import fs17 from "fs";
6904
- import path15 from "path";
7538
+ import { execFileSync as execFileSync16 } from "child_process";
7539
+ import fs18 from "fs";
7540
+ import path16 from "path";
6905
7541
 
6906
7542
  // src/core/observation.ts
6907
7543
  import crypto14 from "crypto";
6908
- import fs16 from "fs";
7544
+ import fs17 from "fs";
6909
7545
  import os3 from "os";
6910
- import path14 from "path";
7546
+ import path15 from "path";
6911
7547
  function extractRecentAgentFiles(rows) {
6912
7548
  const result = {};
6913
7549
  for (const row of rows) {
@@ -6966,40 +7602,41 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
6966
7602
  workspaces: [],
6967
7603
  handoffs: [],
6968
7604
  workflowMode: "worktrees",
6969
- workflowModeConfigured: false
7605
+ workflowModeConfigured: false,
7606
+ worktreeRegistrations: []
6970
7607
  };
6971
7608
  let scratch, db;
6972
7609
  try {
6973
- const file = path14.join(layout.coordDir, "state.db");
7610
+ const file = path15.join(layout.coordDir, "state.db");
6974
7611
  if (physicalPath(layout.coordDir) !== layout.coordDir || physicalPath(file) !== file) throw new Error("Coordination state must not be a symlink");
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`);
7612
+ for (let current = fs17.realpathSync.native(directory); isWithin(layout.checkoutRoot, current); current = path15.dirname(current)) {
7613
+ const local = path15.join(current, ".coord");
7614
+ if (local !== layout.coordDir && fs17.existsSync(path15.join(local, "state.db"))) throw new Error(`Legacy independent state at ${local}; preserve it before consolidation`);
6978
7615
  if (current === layout.checkoutRoot) break;
6979
7616
  }
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);
7617
+ if (!fs17.existsSync(file)) {
7618
+ if (["setup.lock", "merge-train.lock"].some((name) => fs17.existsSync(path15.join(layout.coordDir, name))) || ["-wal", "-shm", "-journal"].some((s) => fs17.existsSync(file + s)) || ["worktrees", "quarantine", "snapshots", "shadow-index", "setup"].some((name) => {
7619
+ const p = path15.join(layout.coordDir, name);
7620
+ return fs17.existsSync(p) && (!fs17.lstatSync(p).isDirectory() || fs17.readdirSync(p).length > 0);
6984
7621
  })) throw new Error("Missing database with retained sidecars; preserve the recovery set");
6985
7622
  return empty;
6986
7623
  }
6987
7624
  const files = ["", "-wal", "-shm", "-journal"].map((s) => file + s);
6988
7625
  const identity = (f) => {
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 });
7626
+ if (!fs17.existsSync(f)) return null;
7627
+ if (physicalPath(f) !== f || !fs17.lstatSync(f).isFile()) throw new Error("Database or sidecar is redirected or not a regular file");
7628
+ const s = fs17.statSync(f, { bigint: true });
6992
7629
  return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
6993
7630
  };
6994
7631
  const before = files.map(identity);
6995
- scratch = fs16.mkdtempSync(path14.join(os3.tmpdir(), "kith-observe-"));
7632
+ scratch = fs17.mkdtempSync(path15.join(os3.tmpdir(), "kith-observe-"));
6996
7633
  for (let i = 0; i < files.length; i++) if (before[i]) {
6997
- const target = path14.join(scratch, path14.basename(files[i]));
6998
- fs16.copyFileSync(files[i], target);
6999
- fs16.chmodSync(target, 384);
7634
+ const target = path15.join(scratch, path15.basename(files[i]));
7635
+ fs17.copyFileSync(files[i], target);
7636
+ fs17.chmodSync(target, 384);
7000
7637
  }
7001
7638
  if (JSON.stringify(before) !== JSON.stringify(files.map(identity))) throw new Error("Coordination state changed during snapshot; stop writers or retry");
7002
- db = new (sqliteDatabase())(path14.join(scratch, "state.db"), { readOnly: true });
7639
+ db = new (sqliteDatabase())(path15.join(scratch, "state.db"), { readOnly: true });
7003
7640
  db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN");
7004
7641
  const schemaVersion = CoordDatabase.inspectSchema(db);
7005
7642
  if (schemaVersion < 2) throw new Error("Offline observation requires schema 2 or newer; preserve state and upgrade with clients stopped");
@@ -7009,6 +7646,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
7009
7646
  const rawMode = db.prepare("SELECT value FROM meta WHERE key='workflow_mode'").get()?.value;
7010
7647
  const workflowModeConfigured = rawMode === "main" || rawMode === "worktrees";
7011
7648
  const workflowMode = workflowModeFrom(rawMode);
7649
+ const worktreeRegistrations = hasTable("worktree_registrations") ? all("SELECT agent_id, worktree_path, provenance, source, branch, head, detached, dirty, branch_elsewhere, registered_at FROM worktree_registrations ORDER BY registered_at").map(registrationFromRow) : [];
7012
7650
  const agents = all("SELECT * FROM agents ORDER BY registered_at DESC" + (options.coordinationOnly ? " LIMIT 201" : ""));
7013
7651
  const recentAgentFiles = !options.ownersOnly ? extractRecentAgentFiles(all("SELECT agent_id, event_type, payload_json FROM events WHERE event_type IN ('locks_acquired','contracts_updated','contract_breaking_change') ORDER BY id DESC LIMIT 200")) : {};
7014
7652
  if (options.coordinationOnly) {
@@ -7038,12 +7676,13 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
7038
7676
  commandGuards,
7039
7677
  mergeQueue,
7040
7678
  recentAgentFiles,
7679
+ worktreeRegistrations,
7041
7680
  truncated: [agents, tasks, resources, mutexWaiters, commandGuards, mergeQueue].some((rows) => rows.length > 200) || locks.length > 500
7042
7681
  };
7043
7682
  }
7044
7683
  if (options.ownersOnly) {
7045
7684
  db.exec("COMMIT");
7046
- return { ...empty, state: "ready", schemaVersion, agents };
7685
+ return { ...empty, state: "ready", schemaVersion, agents, worktreeRegistrations };
7047
7686
  }
7048
7687
  const state = {
7049
7688
  ...empty,
@@ -7052,6 +7691,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
7052
7691
  handoffs,
7053
7692
  workflowMode,
7054
7693
  workflowModeConfigured,
7694
+ worktreeRegistrations,
7055
7695
  fencingEpoch: Number(db.prepare("SELECT value FROM meta WHERE key='fencing_epoch'").get().value),
7056
7696
  agents,
7057
7697
  tasks: all("SELECT * FROM tasks ORDER BY priority DESC,created_at").map(({ depends_on_json, scope_globs_json, ...r }) => ({ ...r, depends_on: JSON.parse(String(depends_on_json)), scope_globs: JSON.parse(String(scope_globs_json)) })),
@@ -7073,7 +7713,7 @@ function readCoordinationState(directory = process.cwd(), options = {}) {
7073
7713
  return { ...empty, state: "unavailable", error: error instanceof Error ? error.message : String(error) };
7074
7714
  } finally {
7075
7715
  db?.close();
7076
- if (scratch) fs16.rmSync(scratch, { recursive: true, force: true });
7716
+ if (scratch) fs17.rmSync(scratch, { recursive: true, force: true });
7077
7717
  }
7078
7718
  }
7079
7719
  function readBrief(directory = process.cwd(), options = {}) {
@@ -7167,19 +7807,19 @@ function readBrief(directory = process.cwd(), options = {}) {
7167
7807
  }, { ...options, scopeGlobs });
7168
7808
  }
7169
7809
  function recoveryReport(directory = process.cwd()) {
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),
7810
+ const state = readCoordinationState(directory), retainedRoot = path15.join(state.repository.coordDir, "worktrees");
7811
+ const retained = physicalPath(retainedRoot) === retainedRoot && fs17.existsSync(retainedRoot) && fs17.lstatSync(retainedRoot).isDirectory() && !fs17.lstatSync(retainedRoot).isSymbolicLink() ? fs17.readdirSync(retainedRoot, { withFileTypes: true }).map((entry) => ({
7812
+ path: path15.join(retainedRoot, entry.name),
7173
7813
  symlink: entry.isSymbolicLink(),
7174
- agentIds: state.agents.filter((a) => a.worktree_path === path14.join(retainedRoot, entry.name)).map((a) => a.id)
7814
+ agentIds: state.agents.filter((a) => a.worktree_path === path15.join(retainedRoot, entry.name)).map((a) => a.id)
7175
7815
  })) : [];
7176
7816
  return {
7177
7817
  ...state,
7178
7818
  retainedWorktrees: retained,
7179
7819
  expiredClaims: state.locks.filter((lock) => Number(lock.expires_at) <= state.observedAt),
7180
7820
  unfinishedIntegrations: state.mergeQueue.filter((entry) => entry.status !== "merged"),
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")) }
7821
+ setupLock: { path: path15.join(state.repository.coordDir, "setup.lock"), present: fs17.existsSync(path15.join(state.repository.coordDir, "setup.lock")) },
7822
+ integrationLock: { path: path15.join(state.repository.coordDir, "merge-train.lock"), present: fs17.existsSync(path15.join(state.repository.coordDir, "merge-train.lock")) }
7183
7823
  };
7184
7824
  }
7185
7825
 
@@ -7256,7 +7896,7 @@ var MAX_REPLY_BYTES = 16 * 1024;
7256
7896
  var MAX_LINKS = 8;
7257
7897
  var MAX_SYMBOLS = 64;
7258
7898
  function git3(root, ...args) {
7259
- return execFileSync14("git", ["-c", "core.fsmonitor=false", ...args], {
7899
+ return execFileSync16("git", ["-c", "core.fsmonitor=false", ...args], {
7260
7900
  cwd: root,
7261
7901
  encoding: "utf8",
7262
7902
  stdio: ["ignore", "pipe", "pipe"],
@@ -7266,21 +7906,21 @@ function git3(root, ...args) {
7266
7906
  }).trim();
7267
7907
  }
7268
7908
  function readBounded(file) {
7269
- const fd = fs17.openSync(file, "r");
7909
+ const fd = fs18.openSync(file, "r");
7270
7910
  try {
7271
- const stat = fs17.fstatSync(fd);
7911
+ const stat = fs18.fstatSync(fd);
7272
7912
  if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) throw new Error("Contract/config file exceeds inspection limit or is not a regular file");
7273
7913
  const bytes = Buffer.alloc(MAX_SOURCE_BYTES + 1);
7274
- const size = fs17.readSync(fd, bytes, 0, bytes.length, 0);
7914
+ const size = fs18.readSync(fd, bytes, 0, bytes.length, 0);
7275
7915
  if (size > MAX_SOURCE_BYTES) throw new Error("Contract/config file exceeds inspection limit");
7276
7916
  return bytes.subarray(0, size).toString("utf8");
7277
7917
  } finally {
7278
- fs17.closeSync(fd);
7918
+ fs18.closeSync(fd);
7279
7919
  }
7280
7920
  }
7281
7921
  function resolveFile(base) {
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);
7922
+ for (const name of [base, `${base}.ts`, `${base}.tsx`, `${base}.d.ts`, `${base}.js`, `${base}.jsx`, path16.join(base, "index.ts"), path16.join(base, "index.js")]) {
7923
+ if (fs18.existsSync(name) && fs18.statSync(name).isFile()) return physicalPath(name);
7284
7924
  }
7285
7925
  }
7286
7926
  function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
@@ -7295,8 +7935,8 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
7295
7935
  const activeRoot = layout.checkoutRoot;
7296
7936
  let config = null;
7297
7937
  for (const name of ["tsconfig.json", "jsconfig.json"]) {
7298
- const file = path15.join(activeRoot, name);
7299
- if (!fs17.existsSync(file)) continue;
7938
+ const file = path16.join(activeRoot, name);
7939
+ if (!fs18.existsSync(file)) continue;
7300
7940
  repositoryFile(activeRoot, file);
7301
7941
  config = parseJsoncObject(readBounded(file));
7302
7942
  if (!config) unavailable(`Cannot parse ${name}; aliases were not inspected.`);
@@ -7314,11 +7954,11 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
7314
7954
  unavailable("Worktree repository identity differs from the caller.");
7315
7955
  return report;
7316
7956
  }
7317
- const bases = [.../* @__PURE__ */ new Set([activeRoot, caller.checkoutRoot])].map((root) => path15.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : "."));
7957
+ const bases = [.../* @__PURE__ */ new Set([activeRoot, caller.checkoutRoot])].map((root) => path16.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : "."));
7318
7958
  let symbolBudget = MAX_SYMBOLS;
7319
7959
  const aliases = Object.entries(options.paths).sort(([a], [b]) => b.length - a.length);
7320
7960
  if (aliases.length > 32) unavailable("Alias limit reached; inspection is partial.");
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("*", "")))));
7961
+ const externalTargets = (targets) => Array.isArray(targets) && targets.slice(0, 8).some((target) => typeof target === "string" && !isWithin(caller.checkoutRoot, physicalPath(path16.resolve(bases[bases.length - 1], target.replace("*", "")))));
7322
7962
  const selected = imports ? [...new Set(imports)].slice(0, 32) : aliases.slice(0, 32).filter(([a]) => !a.includes("*")).map(([a]) => a);
7323
7963
  if (imports && imports.length > 32) unavailable("Import limit reached; inspection is partial.");
7324
7964
  if (!imports && aliases.some(([a, targets]) => a.includes("*") && externalTargets(targets))) unavailable("Wildcard aliases are checked for concrete imports after edits; not enumerated by status.");
@@ -7341,7 +7981,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
7341
7981
  for (const target of targets.slice(0, 8)) {
7342
7982
  if (typeof target !== "string" || (target.match(/\*/g)?.length ?? 0) > 1) continue;
7343
7983
  for (const base of bases) {
7344
- externalFile = resolveFile(path15.resolve(base, target.replace("*", substitution)));
7984
+ externalFile = resolveFile(path16.resolve(base, target.replace("*", substitution)));
7345
7985
  if (externalFile) break;
7346
7986
  }
7347
7987
  if (externalFile) break;
@@ -7351,7 +7991,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
7351
7991
  continue;
7352
7992
  }
7353
7993
  if (isWithin(activeRoot, externalFile)) continue;
7354
- const sibling = discoverRepository(path15.dirname(externalFile));
7994
+ const sibling = discoverRepository(path16.dirname(externalFile));
7355
7995
  if (!sibling.commonGitDir || sibling.commonGitDir === layout.commonGitDir) {
7356
7996
  unavailable(`'${specifier}' does not select a separate Git repository; no external source was read.`);
7357
7997
  continue;
@@ -7391,7 +8031,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
7391
8031
  try {
7392
8032
  const wt = discoverRepository(agent.worktree_path);
7393
8033
  if (wt.checkoutRoot !== physicalPath(agent.worktree_path) || wt.commonGitDir !== sibling.commonGitDir) throw new Error("Worktree identity changed");
7394
- const file = path15.join(wt.checkoutRoot, relative);
8034
+ const file = path16.join(wt.checkoutRoot, relative);
7395
8035
  repositoryFile(wt.checkoutRoot, file);
7396
8036
  const current = AstAnalyzer.extractExports(readBounded(file));
7397
8037
  const original = new Map(extracted.map((s) => [s.symbolName, s.astHash]));
@@ -7405,7 +8045,7 @@ function inspectWorkspaceContracts(repoRoot, worktreeDir, imports) {
7405
8045
  }
7406
8046
  }
7407
8047
  if (agents.length > 8) unavailable(`'${specifier}' owner/worktree inspection limit reached.`);
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 };
8048
+ const link = { alias: specifier, sourceRepo: siblingRoot, sourceRepoName: path16.basename(siblingRoot), filePath: relative, absolutePath: externalFile, symbols, exportsComplete, ownershipAvailable, dirtyInCheckout, lockedByAgent: locked ? String(locked.owner_agent_id) : null, activeWorktreeDrifts: drifts };
7409
8049
  report.linkedContracts.push(link);
7410
8050
  if (Buffer.byteLength(JSON.stringify(report)) > MAX_REPLY_BYTES - 3e3) {
7411
8051
  report.linkedContracts.pop();
@@ -7447,9 +8087,9 @@ function verifyCrossRepoImportsForFile(params) {
7447
8087
  }
7448
8088
 
7449
8089
  // src/core/worktree-cow.ts
7450
- import { execFileSync as execFileSync15 } from "child_process";
7451
- import fs18 from "fs";
7452
- import path16 from "path";
8090
+ import { execFileSync as execFileSync17 } from "child_process";
8091
+ import fs19 from "fs";
8092
+ import path17 from "path";
7453
8093
  var CoWWorktreeManager = class _CoWWorktreeManager {
7454
8094
  constructor(coordDb, fencing) {
7455
8095
  this.coordDb = coordDb;
@@ -7469,34 +8109,40 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
7469
8109
  const safeId = params.agentId.replace(/[^a-zA-Z0-9_-]/g, "-");
7470
8110
  const branch = params.branch ?? `kith/${safeId}`;
7471
8111
  const baseRef = params.baseRef ?? "HEAD";
7472
- const worktreePath = path16.join(this.coordDb.coordDir, "worktrees", safeId);
8112
+ const worktreePath = path17.join(this.coordDb.coordDir, "worktrees", safeId);
7473
8113
  if (!this.fencing.getAgent(params.agentId)) throw new Error(`Unknown agent: ${params.agentId}`);
7474
8114
  if (!safeId || safeId === "." || safeId === "..") throw new Error("Invalid agent ID");
7475
- if (fs18.existsSync(worktreePath)) {
8115
+ if (fs19.existsSync(worktreePath)) {
7476
8116
  throw new Error(`Worktree already exists: ${worktreePath}. Commit or preserve its work before removing it.`);
7477
8117
  }
7478
- fs18.mkdirSync(path16.dirname(worktreePath), { recursive: true });
7479
- execFileSync15("git", ["worktree", "add", "-b", branch, worktreePath, baseRef], {
8118
+ fs19.mkdirSync(path17.dirname(worktreePath), { recursive: true });
8119
+ execFileSync17("git", ["worktree", "add", "-b", branch, worktreePath, baseRef], {
7480
8120
  cwd: this.coordDb.repoRoot,
7481
8121
  stdio: "ignore"
7482
8122
  });
7483
8123
  const hydratedDirs = [];
7484
8124
  let hydrationMethod = "none";
7485
8125
  for (const dirName of _CoWWorktreeManager.HYDRATABLE_DIRS) {
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;
8126
+ const srcDir = path17.join(this.coordDb.repoRoot, dirName);
8127
+ const destDir = path17.join(worktreePath, dirName);
8128
+ if (!fs19.existsSync(srcDir) || fs19.existsSync(destDir)) continue;
7489
8129
  const method = this.cloneDirectoryCoW(srcDir, destDir);
7490
8130
  if (hydrationMethod !== "copy") hydrationMethod = method;
7491
8131
  hydratedDirs.push(dirName);
7492
8132
  }
7493
8133
  for (const envName of _CoWWorktreeManager.ENV_FILES) {
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);
8134
+ const srcEnv = path17.join(this.coordDb.repoRoot, envName);
8135
+ const destEnv = path17.join(worktreePath, envName);
8136
+ if (fs19.existsSync(srcEnv) && !fs19.existsSync(destEnv)) {
8137
+ fs19.copyFileSync(srcEnv, destEnv);
7498
8138
  }
7499
8139
  }
8140
+ let head = null;
8141
+ try {
8142
+ head = execFileSync17("git", ["rev-parse", "HEAD"], { cwd: worktreePath, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8143
+ } catch {
8144
+ head = null;
8145
+ }
7500
8146
  this.coordDb.withTransaction(() => {
7501
8147
  this.fencing.assertSession(params.agentId);
7502
8148
  this.coordDb.db.prepare(`UPDATE agents SET worktree_path = ?, branch = ? WHERE id = ?`).run(worktreePath, branch, params.agentId);
@@ -7506,6 +8152,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
7506
8152
  hydrationMethod,
7507
8153
  hydratedDirs
7508
8154
  });
8155
+ recordCreatedWorktree(this.coordDb, this.fencing, { agentId: params.agentId, worktreePath, branch, head });
7509
8156
  });
7510
8157
  return {
7511
8158
  agentId: params.agentId,
@@ -7513,14 +8160,21 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
7513
8160
  branch,
7514
8161
  hydrationMethod,
7515
8162
  hydratedDirs,
7516
- durationMs: Date.now() - start
8163
+ durationMs: Date.now() - start,
8164
+ provenance: "created",
8165
+ source: "kith",
8166
+ detached: false,
8167
+ dirty: false,
8168
+ branchCheckedOutElsewhere: false,
8169
+ alreadyRegistered: false,
8170
+ notes: []
7517
8171
  };
7518
8172
  }
7519
8173
  cloneDirectoryCoW(srcDir, destDir) {
7520
8174
  const cowTimeoutMs = Number(process.env.KITH_COW_TIMEOUT_MS) || 6e4;
7521
8175
  if (process.platform === "darwin") {
7522
8176
  try {
7523
- execFileSync15("cp", ["-cR", srcDir, destDir], {
8177
+ execFileSync17("cp", ["-cR", srcDir, destDir], {
7524
8178
  stdio: "ignore",
7525
8179
  timeout: cowTimeoutMs
7526
8180
  });
@@ -7529,7 +8183,7 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
7529
8183
  }
7530
8184
  } else if (process.platform === "linux") {
7531
8185
  try {
7532
- execFileSync15("cp", ["--reflink=always", "-R", srcDir, destDir], {
8186
+ execFileSync17("cp", ["--reflink=always", "-R", srcDir, destDir], {
7533
8187
  stdio: "ignore",
7534
8188
  timeout: cowTimeoutMs
7535
8189
  });
@@ -7537,59 +8191,91 @@ var CoWWorktreeManager = class _CoWWorktreeManager {
7537
8191
  } catch {
7538
8192
  }
7539
8193
  }
7540
- fs18.rmSync(destDir, { recursive: true, force: true });
7541
- fs18.cpSync(srcDir, destDir, { recursive: true, dereference: false });
8194
+ fs19.rmSync(destDir, { recursive: true, force: true });
8195
+ fs19.cpSync(srcDir, destDir, { recursive: true, dereference: false });
7542
8196
  return "copy";
7543
8197
  }
7544
- removeWorktree(agentId) {
8198
+ removeWorktree(agentId, options) {
7545
8199
  this.fencing.assertSession(agentId);
8200
+ const registration = readRegistration(this.coordDb, agentId);
8201
+ const agentPath = this.fencing.getAgent(agentId)?.worktree_path ?? null;
8202
+ const adopted = registration?.provenance === "adopted" || Boolean(agentPath && !isKithOwnedWorktree(this.coordDb, agentPath));
8203
+ if (adopted) {
8204
+ if (!options?.deleteAdopted) {
8205
+ throw new Error(`Refusing to remove an adopted worktree Kith did not create (${agentPath ?? registration?.worktreePath}). The directory was left in place. Pass --delete-adopted to remove it explicitly, or \`kith worktree forget\` to unregister it.`);
8206
+ }
8207
+ const target = agentPath ?? registration?.worktreePath;
8208
+ if (!target || !fs19.existsSync(target)) {
8209
+ throw new Error(`Adopted worktree directory is missing (${target ?? "unknown"}). Nothing was deleted. Use \`kith worktree forget\` to drop the registration.`);
8210
+ }
8211
+ this.removeCheckout(target, true);
8212
+ this.clearAgentWorktree(agentId);
8213
+ return true;
8214
+ }
7546
8215
  const safeId = agentId.replace(/[^a-zA-Z0-9_-]/g, "-");
7547
- const worktreePath = path16.join(this.coordDb.coordDir, "worktrees", safeId);
7548
- if (!fs18.existsSync(worktreePath)) return false;
7549
- const registered = this.fencing.getAgent(agentId)?.worktree_path;
8216
+ const worktreePath = path17.join(this.coordDb.coordDir, "worktrees", safeId);
8217
+ if (!fs19.existsSync(worktreePath)) return false;
8218
+ const registered = agentPath;
7550
8219
  if (!registered || physicalPath(registered) !== physicalPath(worktreePath) || this.fencing.listAgents(true).some((agent) => agent.id !== agentId && agent.worktree_path && physicalPath(agent.worktree_path) === physicalPath(worktreePath))) {
7551
8220
  throw new Error("Refusing to remove a worktree that is not exclusively registered to this agent.");
7552
8221
  }
7553
- const status = execFileSync15("git", ["status", "--porcelain", "--untracked-files=normal", "--ignored=matching"], {
8222
+ this.removeCheckout(worktreePath, false);
8223
+ this.clearAgentWorktree(agentId);
8224
+ return true;
8225
+ }
8226
+ removeCheckout(worktreePath, adopted) {
8227
+ const status = execFileSync17("git", ["status", "--porcelain", "--untracked-files=normal", "--ignored=matching"], {
7554
8228
  cwd: worktreePath,
7555
8229
  encoding: "utf8"
7556
8230
  });
7557
8231
  if (status.trim()) {
7558
8232
  throw new Error(`Refusing to remove dirty worktree: ${worktreePath}. Commit or preserve changed, untracked, and ignored files first.`);
7559
8233
  }
7560
- execFileSync15("git", ["worktree", "remove", worktreePath], {
7561
- cwd: this.coordDb.repoRoot,
7562
- stdio: ["ignore", "pipe", "pipe"]
7563
- });
8234
+ try {
8235
+ execFileSync17("git", ["worktree", "remove", worktreePath], {
8236
+ cwd: this.coordDb.repoRoot,
8237
+ stdio: ["ignore", "pipe", "pipe"]
8238
+ });
8239
+ } catch (err) {
8240
+ if (!adopted) throw err;
8241
+ const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
8242
+ throw new Error(`git worktree remove failed; the adopted directory was left in place. ${stderr}`.trim());
8243
+ }
8244
+ }
8245
+ clearAgentWorktree(agentId) {
7564
8246
  this.coordDb.withTransaction(() => {
7565
8247
  this.fencing.assertSession(agentId);
8248
+ clearRegistration(this.coordDb, agentId);
7566
8249
  this.coordDb.db.prepare(`UPDATE agents SET worktree_path = NULL, branch = NULL WHERE id = ?`).run(agentId);
7567
8250
  });
7568
- return true;
7569
8251
  }
7570
8252
  listWorktrees() {
7571
- try {
7572
- const out = execFileSync15("git", ["worktree", "list", "--porcelain"], {
7573
- cwd: this.coordDb.repoRoot,
7574
- encoding: "utf8"
7575
- });
7576
- const entries = [];
7577
- let current = null;
7578
- for (const line of out.split(/\r?\n/)) {
7579
- if (line.startsWith("worktree ")) {
7580
- if (current) entries.push(current);
7581
- current = { path: line.slice("worktree ".length).trim(), head: "", branch: null };
7582
- } else if (line.startsWith("HEAD ") && current) {
7583
- current.head = line.slice("HEAD ".length).trim();
7584
- } else if (line.startsWith("branch ") && current) {
7585
- current.branch = line.slice("branch ".length).replace(/^refs\/heads\//, "").trim();
7586
- }
7587
- }
7588
- if (current) entries.push(current);
7589
- return entries;
7590
- } catch {
7591
- return [];
7592
- }
8253
+ return listGitWorktrees(this.coordDb.repoRoot);
8254
+ }
8255
+ registrationFor(agentId) {
8256
+ return readRegistration(this.coordDb, agentId);
8257
+ }
8258
+ listRegistrations() {
8259
+ return listRegistrations(this.coordDb);
8260
+ }
8261
+ adoptWorktree(params) {
8262
+ return adoptWorktree(this.coordDb, this.fencing, {
8263
+ agentId: params.agentId,
8264
+ path: params.path,
8265
+ explicit: params.explicit !== false
8266
+ });
8267
+ }
8268
+ adoptIfUnambiguous(params) {
8269
+ return adoptIfUnambiguous(this.coordDb, this.fencing, params);
8270
+ }
8271
+ syncRegistration(agentId) {
8272
+ return syncRegistration(this.coordDb, this.fencing, agentId);
8273
+ }
8274
+ liveAdoption(agent) {
8275
+ return liveAdoption(this.coordDb, this.fencing, agent);
8276
+ }
8277
+ forgetWorktree(agentId) {
8278
+ return forgetWorktree(this.coordDb, this.fencing, agentId);
7593
8279
  }
7594
8280
  };
7595
8281
 
@@ -7700,7 +8386,7 @@ var KithEngine = class {
7700
8386
  warnings: []
7701
8387
  };
7702
8388
  }
7703
- const content = params.content ?? (fs19.existsSync(path17.join(targetRoot, file)) ? fs19.readFileSync(path17.join(targetRoot, file), "utf8") : "");
8389
+ const content = params.content ?? (fs20.existsSync(path18.join(targetRoot, file)) ? fs20.readFileSync(path18.join(targetRoot, file), "utf8") : "");
7704
8390
  const contractReport = this.depGraph.recordFileModification(
7705
8391
  params.agentId,
7706
8392
  file,
@@ -7777,10 +8463,10 @@ var KithEngine = class {
7777
8463
  const held = this.coordDb.db.prepare(`SELECT pattern FROM locks WHERE owner_agent_id = ?`).all(agentId).map((l) => l.pattern.replace(/^file:/, ""));
7778
8464
  const mine = activeConflicts.filter((c) => c.agent_a === agentId || held.some((p) => c.file_path === p || LockEngine.patternsOverlap(p, c.file_path)));
7779
8465
  const keyOf = (c) => `${c.file_path}\0${c.agent_a === agentId ? c.agent_b : c.agent_a}`;
7780
- const seenFile = path17.join(this.coordDb.coordDir, "delta-seen", `${agentId.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`);
8466
+ const seenFile = path18.join(this.coordDb.coordDir, "delta-seen", `${agentId.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`);
7781
8467
  let seen = { keys: [], others: 0 };
7782
8468
  try {
7783
- seen = JSON.parse(fs19.readFileSync(seenFile, "utf8"));
8469
+ seen = JSON.parse(fs20.readFileSync(seenFile, "utf8"));
7784
8470
  } catch {
7785
8471
  }
7786
8472
  const seenKeys = new Set(seen.keys);
@@ -7795,8 +8481,8 @@ var KithEngine = class {
7795
8481
  try {
7796
8482
  const keys = mine.map(keyOf).sort();
7797
8483
  if (fresh.length || others !== seen.others || keys.length !== seen.keys.length) {
7798
- fs19.mkdirSync(path17.dirname(seenFile), { recursive: true });
7799
- fs19.writeFileSync(seenFile, JSON.stringify({ keys, others }));
8484
+ fs20.mkdirSync(path18.dirname(seenFile), { recursive: true });
8485
+ fs20.writeFileSync(seenFile, JSON.stringify({ keys, others }));
7800
8486
  }
7801
8487
  } catch {
7802
8488
  }
@@ -7844,7 +8530,8 @@ ${kept.join("\n")}` : "";
7844
8530
  handoffs: handoffBlock(this.handoffs.unresolved(10), { summaryMax: 300, filesMax: 5 }),
7845
8531
  mutexWaiters: this.coordDb.db.prepare("SELECT ticket,mutex_name,owner_agent_id,session_epoch,expires_at FROM mutex_waiters ORDER BY ticket").all(),
7846
8532
  commandGuards: this.coordDb.db.prepare("SELECT mutex_name,owner_agent_id,worker_pid,supervisor_pid FROM mutex_runs ORDER BY mutex_name").all(),
7847
- workspaces: observeWorkspaces(this.coordDb.repoRoot, agents)
8533
+ workspaces: observeWorkspaces(this.coordDb.repoRoot, agents),
8534
+ worktreeRegistrations: this.worktrees.listRegistrations()
7848
8535
  };
7849
8536
  }
7850
8537
  previewIntegration(agentId) {
@@ -7852,13 +8539,19 @@ ${kept.join("\n")}` : "";
7852
8539
  return previewIntegration(this.coordDb.repoRoot, this.fencing.getAgent(agentId));
7853
8540
  }
7854
8541
  beginWork(params) {
7855
- const mode = this.workflowMode(), isolate = mode === "main" ? false : params.isolateWorktree;
7856
- const notes = mode === "main" && params.isolateWorktree ? [MAIN_MODE_NOTE] : [];
8542
+ this.worktrees.syncRegistration(params.agentId);
8543
+ const mode = this.workflowMode();
8544
+ const adopting = Boolean(params.adoptWorktree || params.worktreePath);
8545
+ const isolate = mode === "main" ? false : Boolean(params.isolateWorktree) && !adopting;
8546
+ const notes = [
8547
+ ...mode === "main" && params.isolateWorktree && !adopting ? [MAIN_MODE_NOTE] : [],
8548
+ ...mode === "main" && adopting ? [ADOPT_MAIN_MODE_NOTE] : []
8549
+ ];
7857
8550
  const intent = this.intents.declareIntent(params);
7858
8551
  let worktree = null;
7859
- if (intent.ok && isolate && intent.task) {
8552
+ if (intent.ok && (isolate || adopting) && intent.task) {
7860
8553
  try {
7861
- worktree = this.worktrees.spawnWorktree({ agentId: params.agentId });
8554
+ worktree = adopting ? this.worktrees.adoptWorktree({ agentId: params.agentId, path: params.worktreePath, explicit: true }) : this.claimWorktree(params.agentId);
7862
8555
  } catch (err) {
7863
8556
  this.coordDb.withTransaction(() => {
7864
8557
  this.coordDb.db.prepare("DELETE FROM locks WHERE task_id = ?").run(intent.task.id);
@@ -7871,6 +8564,9 @@ ${kept.join("\n")}` : "";
7871
8564
  this.coordDb.repoRoot,
7872
8565
  worktree?.worktreePath ?? this.fencing.getAgent(params.agentId)?.worktree_path ?? void 0
7873
8566
  );
8567
+ if (worktree && "notes" in worktree && Array.isArray(worktree.notes)) {
8568
+ for (const note of worktree.notes) if (!notes.includes(note)) notes.push(note);
8569
+ }
7874
8570
  return {
7875
8571
  ...intent,
7876
8572
  worktree,
@@ -7883,13 +8579,19 @@ ${kept.join("\n")}` : "";
7883
8579
  };
7884
8580
  }
7885
8581
  claimNextTask(params) {
7886
- const mode = this.workflowMode(), isolate = mode === "main" ? false : params.isolateWorktree;
7887
- const notes = mode === "main" && params.isolateWorktree ? [MAIN_MODE_NOTE] : [];
8582
+ this.worktrees.syncRegistration(params.agentId);
8583
+ const mode = this.workflowMode();
8584
+ const adopting = Boolean(params.adoptWorktree || params.worktreePath);
8585
+ const isolate = mode === "main" ? false : Boolean(params.isolateWorktree) && !adopting;
8586
+ const notes = [
8587
+ ...mode === "main" && params.isolateWorktree && !adopting ? [MAIN_MODE_NOTE] : [],
8588
+ ...mode === "main" && adopting ? [ADOPT_MAIN_MODE_NOTE] : []
8589
+ ];
7888
8590
  const claimedRes = this.intents.claimNextTask(params.agentId);
7889
8591
  let worktree = null;
7890
- if (claimedRes.claimed && isolate && claimedRes.task) {
8592
+ if (claimedRes.claimed && (isolate || adopting) && claimedRes.task) {
7891
8593
  try {
7892
- worktree = this.claimWorktree(params.agentId);
8594
+ worktree = adopting ? this.worktrees.adoptWorktree({ agentId: params.agentId, path: params.worktreePath, explicit: true }) : this.claimWorktree(params.agentId);
7893
8595
  } catch (err) {
7894
8596
  this.coordDb.withTransaction(() => {
7895
8597
  this.coordDb.db.prepare("DELETE FROM locks WHERE task_id = ?").run(claimedRes.task.id);
@@ -7903,6 +8605,9 @@ ${kept.join("\n")}` : "";
7903
8605
  this.coordDb.repoRoot,
7904
8606
  worktree?.worktreePath ?? this.fencing.getAgent(params.agentId)?.worktree_path ?? void 0
7905
8607
  );
8608
+ if (worktree && "notes" in worktree && Array.isArray(worktree.notes)) {
8609
+ for (const note of worktree.notes) if (!notes.includes(note)) notes.push(note);
8610
+ }
7906
8611
  return {
7907
8612
  ...claimedRes,
7908
8613
  worktree,
@@ -7919,26 +8624,43 @@ ${kept.join("\n")}` : "";
7919
8624
  this.fencing.assertSession(agentId);
7920
8625
  const agent = this.fencing.getAgent(agentId);
7921
8626
  if (!agent.worktree_path) return this.worktrees.spawnWorktree({ agentId });
8627
+ const registration = this.worktrees.registrationFor(agentId);
8628
+ const adopted = registration?.provenance === "adopted" || !registration && !isKithOwnedWorktree(this.coordDb, agent.worktree_path);
8629
+ if (adopted) return this.worktrees.adoptWorktree({ agentId, path: agent.worktree_path, explicit: true });
7922
8630
  const root = physicalPath(agent.worktree_path);
7923
8631
  const owner = discoverRepository(this.coordDb.repoRoot);
7924
8632
  const layout = discoverRepository(root);
7925
- const git4 = (...args) => execFileSync16("git", args, {
8633
+ const git4 = (...args) => execFileSync18("git", args, {
7926
8634
  cwd: root,
7927
8635
  encoding: "utf8",
7928
8636
  stdio: ["ignore", "pipe", "pipe"],
7929
8637
  timeout: 5e3
7930
8638
  }).trim();
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)) {
8639
+ if (!isWithin(physicalPath(path18.join(this.coordDb.coordDir, "worktrees")), root) || !layout.isLinkedWorktree || layout.checkoutRoot !== root || layout.commonGitDir !== owner.commonGitDir || !agent.branch || git4("symbolic-ref", "--short", "HEAD") !== agent.branch || !this.worktrees.listWorktrees().some((w) => physicalPath(w.path) === root && w.branch === agent.branch) || this.fencing.listAgents(true).some((a) => a.id !== agentId && a.worktree_path && physicalPath(a.worktree_path) === root)) {
7932
8640
  throw new Error("Saved worktree identity or ownership changed; inspect and preserve it before claiming another task.");
7933
8641
  }
7934
8642
  if (git4("status", "--porcelain", "--untracked-files=normal")) {
7935
8643
  throw new Error("Saved worktree has unfinished changes; preserve or finish them before claiming another task.");
7936
8644
  }
7937
- const head = execFileSync16("git", ["rev-parse", "HEAD"], { cwd: this.coordDb.repoRoot, encoding: "utf8" }).trim();
8645
+ const head = execFileSync18("git", ["rev-parse", "HEAD"], { cwd: this.coordDb.repoRoot, encoding: "utf8" }).trim();
7938
8646
  if (git4("rev-parse", "HEAD") !== head) {
7939
8647
  throw new Error("Saved worktree is ahead or behind the current checkout; integrate or replace it explicitly before claiming another task.");
7940
8648
  }
7941
- return { agentId, worktreePath: root, branch: agent.branch, hydrationMethod: "none", hydratedDirs: [], durationMs: 0 };
8649
+ return {
8650
+ agentId,
8651
+ worktreePath: root,
8652
+ branch: agent.branch,
8653
+ hydrationMethod: "none",
8654
+ hydratedDirs: [],
8655
+ durationMs: 0,
8656
+ provenance: "created",
8657
+ source: "kith",
8658
+ detached: false,
8659
+ dirty: false,
8660
+ branchCheckedOutElsewhere: false,
8661
+ alreadyRegistered: true,
8662
+ notes: []
8663
+ };
7942
8664
  }
7943
8665
  async claimNextTaskWhenAvailable(params) {
7944
8666
  return this.waitForOwnedClaim(params, () => this.claimNextTask(params));
@@ -7962,7 +8684,24 @@ ${kept.join("\n")}` : "";
7962
8684
  completeWork(params) {
7963
8685
  this.fencing.assertSession(params.agentId);
7964
8686
  const agent = this.fencing.getAgent(params.agentId);
7965
- const branch = params.mergeBranch ?? agent?.branch;
8687
+ const adoption = this.worktrees.liveAdoption(agent);
8688
+ if (this.workflowMode() === "main" && adoption) {
8689
+ if (params.verificationCmd) {
8690
+ try {
8691
+ runVerificationCommand(params.verificationCmd, adoption.worktreePath, this.fencing.sessionEnvironment(params.agentId));
8692
+ } catch (err) {
8693
+ return { ok: false, mergeResult: null, error: err instanceof Error ? err.message : String(err) };
8694
+ }
8695
+ }
8696
+ const completedTasks2 = this.intents.completeTask(params);
8697
+ this.fencing.completeAgentSession(params.agentId);
8698
+ this.shadowGit.pruneStaleShadowIndexes();
8699
+ return { ok: true, completedTasks: completedTasks2, mergeResult: null, notes: [ADOPT_MAIN_MODE_NOTE] };
8700
+ }
8701
+ if (adoption?.integrationError) {
8702
+ return { ok: false, mergeResult: null, error: adoption.integrationError };
8703
+ }
8704
+ const branch = params.mergeBranch ?? adoption?.branch ?? agent?.branch;
7966
8705
  const mergeResult = branch ? this.mergeTrain.enqueueAndMerge({
7967
8706
  agentId: params.agentId,
7968
8707
  branch,
@@ -8014,28 +8753,47 @@ export {
8014
8753
  ShadowGitEngine,
8015
8754
  SpeculativeMergeTrain,
8016
8755
  StaleFencingTokenError,
8756
+ adoptIfUnambiguous,
8757
+ adoptWorktree,
8758
+ branchElsewhereError,
8759
+ branchIsCheckedOutElsewhere,
8017
8760
  buildSwarmPrompts,
8018
8761
  caseSensitivePaths,
8762
+ clearRegistration,
8019
8763
  commandTargetsFileForWrite,
8020
8764
  commitScopedFiles,
8765
+ detachedIntegrationError,
8021
8766
  discoverChildRepositories,
8022
8767
  discoverRepository,
8023
8768
  extractRecentAgentFiles,
8769
+ forgetWorktree,
8024
8770
  gcCoordination,
8025
8771
  inspectWorkspaceContracts,
8772
+ isKithOwnedWorktree,
8026
8773
  isReadOnlyShellCommand,
8027
8774
  isWithin,
8775
+ kithWorktreesRoot,
8776
+ listGitWorktrees,
8777
+ listRegistrations,
8778
+ liveAdoption,
8028
8779
  observeWorkspaces,
8780
+ parseWorktreePorcelain,
8029
8781
  physicalPath,
8030
8782
  previewIntegration,
8783
+ primaryCheckoutOf,
8031
8784
  readBrief,
8032
8785
  readCoordinationState,
8786
+ readRegistration,
8787
+ recordCreatedWorktree,
8033
8788
  recoveryReport,
8034
8789
  refUpdateResyncRoots,
8790
+ registrationFromRow,
8035
8791
  repositoryFile,
8036
8792
  resyncStaleIndexEntries,
8037
8793
  runVerificationCommand,
8038
8794
  sqliteDatabase,
8795
+ syncRegistration,
8796
+ transferWorktreeRegistration,
8039
8797
  verifyCrossRepoImportsForFile,
8040
8798
  worktreeChanges
8041
8799
  };