@aibexhq/aibex-link 0.0.8 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +656 -151
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import path from "node:path";
2
- import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, appendFileSync, openSync, readSync, closeSync, cpSync, accessSync, constants } from "node:fs";
2
+ import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, cpSync, statSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
3
3
  import { randomBytes, createHash } from "node:crypto";
4
- import { platform, arch, release, homedir } from "node:os";
4
+ import { platform, arch, release, tmpdir, homedir } from "node:os";
5
+ import { execFile } from "node:child_process";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { createConnection } from "node:net";
7
- import { execFile } from "node:child_process";
8
8
  const encoder = new TextEncoder();
9
9
  function utf8(text) {
10
10
  return new Uint8Array(encoder.encode(text));
@@ -888,6 +888,10 @@ async function collectReport(options) {
888
888
  if (options.activations && options.activations.length > 0) {
889
889
  report.activations = options.activations;
890
890
  }
891
+ if (options.worktrees) report.worktrees = options.worktrees;
892
+ if (options.releases && options.releases.length > 0) {
893
+ report.releases = options.releases;
894
+ }
891
895
  return report;
892
896
  }
893
897
  function buildHeartbeat(input) {
@@ -907,15 +911,625 @@ function buildHeartbeat(input) {
907
911
  sessions: input.report.sessions,
908
912
  acks: input.acks
909
913
  };
910
- const { repos, access, features, setup_terminals, activations } = input.report;
914
+ const {
915
+ repos,
916
+ access,
917
+ features,
918
+ setup_terminals,
919
+ activations,
920
+ worktrees,
921
+ releases
922
+ } = input.report;
911
923
  if (repos) heartbeat.repos = repos;
912
924
  if (access) heartbeat.access = access;
913
925
  if (features) heartbeat.features = features;
914
926
  if (setup_terminals) heartbeat.setup_terminals = setup_terminals;
915
927
  if (activations) heartbeat.activations = activations;
928
+ if (worktrees) heartbeat.worktrees = worktrees;
929
+ if (releases) heartbeat.releases = releases;
916
930
  if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
917
931
  return heartbeat;
918
932
  }
933
+ const GITHUB_HOST = "github.com";
934
+ const REPO_SCAN_MS = 6e4;
935
+ const GITHUB_REMOTE = [
936
+ /^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
937
+ /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
938
+ ];
939
+ function parseGitHubRemote(url) {
940
+ for (const pattern of GITHUB_REMOTE) {
941
+ const match = pattern.exec(url.trim());
942
+ if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
943
+ }
944
+ return void 0;
945
+ }
946
+ function git(cwd, args, environment) {
947
+ return new Promise((resolve) => {
948
+ execFile(
949
+ "git",
950
+ ["-C", cwd, ...args],
951
+ environment ? { env: { ...process.env, ...environment } } : {},
952
+ (failure, stdout, stderr) => resolve({
953
+ ok: failure === null,
954
+ stdout: stdout.trim(),
955
+ stderr: stderr.trim()
956
+ })
957
+ );
958
+ });
959
+ }
960
+ function directories(parent) {
961
+ try {
962
+ return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
963
+ } catch {
964
+ return [];
965
+ }
966
+ }
967
+ async function scanRepos(reposDirectory) {
968
+ const github = path.join(reposDirectory, GITHUB_HOST);
969
+ const candidates = directories(github).flatMap(
970
+ (owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
971
+ );
972
+ const found = await Promise.all(
973
+ candidates.map(async (directory) => {
974
+ const origin = await git(directory, [
975
+ "config",
976
+ "--get",
977
+ "remote.origin.url"
978
+ ]);
979
+ const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
980
+ return repo ? { repo, path: directory } : void 0;
981
+ })
982
+ );
983
+ return found.filter((checkout) => checkout !== void 0);
984
+ }
985
+ class Repos {
986
+ constructor(reposDirectory, now = Date.now) {
987
+ this.reposDirectory = reposDirectory;
988
+ this.now = now;
989
+ }
990
+ scanned = [];
991
+ scannedAt = Number.NEGATIVE_INFINITY;
992
+ async list(options = {}) {
993
+ if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
994
+ this.scanned = await scanRepos(this.reposDirectory);
995
+ this.scannedAt = this.now();
996
+ }
997
+ return this.scanned;
998
+ }
999
+ /** The checkout for a repository, rescanning once when it is not known. */
1000
+ async find(repo) {
1001
+ const match = (checkouts) => checkouts.find(
1002
+ (checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
1003
+ );
1004
+ return match(await this.list()) ?? match(await this.list({ fresh: true }));
1005
+ }
1006
+ }
1007
+ const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
1008
+ function carryList(reposConfig) {
1009
+ const value = readJson(reposConfig);
1010
+ const carry = value?.carry;
1011
+ if (!Array.isArray(carry)) return DEFAULT_CARRY;
1012
+ return carry.filter(
1013
+ (entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
1014
+ );
1015
+ }
1016
+ function salvageReference(threadId) {
1017
+ return `refs/aibex/salvage/${threadId}`;
1018
+ }
1019
+ async function defaultBranch(checkout) {
1020
+ const head = await git(checkout, [
1021
+ "symbolic-ref",
1022
+ "--short",
1023
+ "refs/remotes/origin/HEAD"
1024
+ ]);
1025
+ return head.ok && head.stdout.startsWith("origin/") ? head.stdout.slice("origin/".length) : "main";
1026
+ }
1027
+ async function restoreWorktree(options) {
1028
+ const { checkout, worktreePath, branch, salvage } = options;
1029
+ const added = await git(checkout, [
1030
+ "worktree",
1031
+ "add",
1032
+ "--quiet",
1033
+ "-B",
1034
+ branch,
1035
+ worktreePath,
1036
+ `${salvage}^1`
1037
+ ]);
1038
+ if (!added.ok) {
1039
+ return { ok: false, reason: added.stderr || "git worktree add failed" };
1040
+ }
1041
+ for (const step of [
1042
+ ["read-tree", "-u", "--reset", salvage],
1043
+ ["reset", "--quiet"]
1044
+ ]) {
1045
+ const result = await git(worktreePath, step);
1046
+ if (!result.ok) {
1047
+ return {
1048
+ ok: false,
1049
+ reason: `git ${step[0]} failed while restoring ${salvage}: ${result.stderr}`
1050
+ };
1051
+ }
1052
+ }
1053
+ return { ok: true };
1054
+ }
1055
+ async function prepareWorktree(options) {
1056
+ const { checkout, threadId } = options;
1057
+ const worktreePath = path.join(options.workDirectory, threadId);
1058
+ const branch = `aibex/${threadId}`;
1059
+ const fetched = await git(checkout, ["fetch", "--quiet", "origin"]);
1060
+ const base = options.baseRef ?? await defaultBranch(checkout);
1061
+ let restored;
1062
+ const known = await git(checkout, [
1063
+ "rev-parse",
1064
+ "--verify",
1065
+ "--quiet",
1066
+ `refs/heads/${branch}`
1067
+ ]);
1068
+ if (!existsSync(path.join(worktreePath, ".git"))) {
1069
+ mkdirSync(options.workDirectory, { recursive: true });
1070
+ const salvage = await git(checkout, [
1071
+ "rev-parse",
1072
+ "--verify",
1073
+ "--quiet",
1074
+ salvageReference(threadId)
1075
+ ]);
1076
+ const salvagedHead = salvage.ok ? await git(checkout, ["rev-parse", `${salvage.stdout}^1`]) : void 0;
1077
+ if (salvage.ok && (!known.ok || salvagedHead?.ok && salvagedHead.stdout === known.stdout)) {
1078
+ const rebuilt = await restoreWorktree({
1079
+ checkout,
1080
+ worktreePath,
1081
+ branch,
1082
+ salvage: salvage.stdout
1083
+ });
1084
+ if (!rebuilt.ok) return rebuilt;
1085
+ restored = salvage.stdout;
1086
+ }
1087
+ }
1088
+ if (restored === void 0 && !existsSync(path.join(worktreePath, ".git"))) {
1089
+ const added = await git(
1090
+ checkout,
1091
+ known.ok ? ["worktree", "add", "--quiet", worktreePath, branch] : [
1092
+ "worktree",
1093
+ "add",
1094
+ "--quiet",
1095
+ "-b",
1096
+ branch,
1097
+ worktreePath,
1098
+ `origin/${base}`
1099
+ ]
1100
+ );
1101
+ if (!added.ok) {
1102
+ const why = added.stderr || `git worktree add failed`;
1103
+ return {
1104
+ ok: false,
1105
+ reason: fetched.ok ? why : `${why} (git fetch failed too: ${fetched.stderr})`
1106
+ };
1107
+ }
1108
+ }
1109
+ const carried = [];
1110
+ for (const file of carryList(options.reposConfig)) {
1111
+ const from = path.join(checkout, file);
1112
+ const to = path.join(worktreePath, file);
1113
+ if (!existsSync(from) || existsSync(to)) continue;
1114
+ const tracked = await git(checkout, [
1115
+ "ls-files",
1116
+ "--error-unmatch",
1117
+ "--",
1118
+ file
1119
+ ]);
1120
+ if (tracked.ok) continue;
1121
+ mkdirSync(path.dirname(to), { recursive: true });
1122
+ cpSync(from, to, { recursive: true });
1123
+ carried.push(file);
1124
+ }
1125
+ return {
1126
+ ok: true,
1127
+ worktree: { path: worktreePath, branch, base },
1128
+ carried,
1129
+ ...restored === void 0 ? {} : { restored }
1130
+ };
1131
+ }
1132
+ const WORKTREE_SCAN_MS = 6e4;
1133
+ const HALF_MADE_AGE_MS = 10 * 6e4;
1134
+ const THREAD_ID = /^t_[A-Za-z0-9]{8,64}$/u;
1135
+ const SALVAGE_IDENTITY = {
1136
+ GIT_AUTHOR_NAME: "aibex",
1137
+ GIT_AUTHOR_EMAIL: "aibex@localhost",
1138
+ GIT_COMMITTER_NAME: "aibex",
1139
+ GIT_COMMITTER_EMAIL: "aibex@localhost"
1140
+ };
1141
+ function threadDirectories(work) {
1142
+ try {
1143
+ return readdirSync(work, { withFileTypes: true }).filter((entry) => entry.isDirectory() && THREAD_ID.test(entry.name)).map((entry) => entry.name).toSorted();
1144
+ } catch {
1145
+ return [];
1146
+ }
1147
+ }
1148
+ function isWorktree(directory) {
1149
+ try {
1150
+ statSync(path.join(directory, ".git"));
1151
+ return true;
1152
+ } catch {
1153
+ return false;
1154
+ }
1155
+ }
1156
+ async function checkoutOf(worktree) {
1157
+ const common = await git(worktree, [
1158
+ "rev-parse",
1159
+ "--path-format=absolute",
1160
+ "--git-common-dir"
1161
+ ]);
1162
+ return common.ok && common.stdout ? path.dirname(common.stdout) : void 0;
1163
+ }
1164
+ async function hasUnpushed(worktree) {
1165
+ const count = await git(worktree, [
1166
+ "rev-list",
1167
+ "--count",
1168
+ "HEAD",
1169
+ "--not",
1170
+ "--remotes"
1171
+ ]);
1172
+ return count.ok && Number(count.stdout) > 0;
1173
+ }
1174
+ async function isDirty(worktree, carry) {
1175
+ const status = await git(worktree, [
1176
+ "status",
1177
+ "--porcelain",
1178
+ "-z",
1179
+ "--untracked-files=all"
1180
+ ]);
1181
+ if (!status.ok) return false;
1182
+ const entries = status.stdout.split("\0");
1183
+ for (let index = 0; index < entries.length; index++) {
1184
+ const entry = entries[index] ?? "";
1185
+ if (entry === "") continue;
1186
+ const code = entry.slice(0, 2);
1187
+ const file = entry.slice(3);
1188
+ if (code[0] === "R" || code[0] === "C") index++;
1189
+ const carried = code === "??" && carry.some((item) => file === item || file.startsWith(`${item}/`));
1190
+ if (!carried) return true;
1191
+ }
1192
+ return false;
1193
+ }
1194
+ async function scanWorktrees(work, reposConfig) {
1195
+ const carry = carryList(reposConfig);
1196
+ const listings = [];
1197
+ for (const threadId of threadDirectories(work)) {
1198
+ const directory = path.join(work, threadId);
1199
+ let createdAt;
1200
+ try {
1201
+ createdAt = statSync(directory).mtime.toISOString();
1202
+ } catch {
1203
+ continue;
1204
+ }
1205
+ const listing = {
1206
+ thread_id: threadId,
1207
+ dirty: false,
1208
+ unpushed: false,
1209
+ created_at: createdAt
1210
+ };
1211
+ if (isWorktree(directory)) {
1212
+ const head = await git(directory, ["rev-parse", "--verify", "HEAD"]);
1213
+ if (head.ok && /^[0-9a-f]{40}$/u.test(head.stdout)) {
1214
+ listing.head = head.stdout;
1215
+ listing.dirty = await isDirty(directory, carry);
1216
+ listing.unpushed = await hasUnpushed(directory);
1217
+ }
1218
+ }
1219
+ listings.push(listing);
1220
+ }
1221
+ return listings;
1222
+ }
1223
+ async function salvageCommit(options) {
1224
+ const { worktree } = options;
1225
+ const scratch = mkdtempSync(path.join(tmpdir(), "aibex-salvage-"));
1226
+ const environment = {
1227
+ ...SALVAGE_IDENTITY,
1228
+ GIT_INDEX_FILE: path.join(scratch, "index")
1229
+ };
1230
+ try {
1231
+ const steps = [
1232
+ ["read-tree", options.head],
1233
+ ["add", "--all", "--", "."]
1234
+ ];
1235
+ for (const file of options.carry) {
1236
+ const tracked = await git(worktree, [
1237
+ "cat-file",
1238
+ "-e",
1239
+ `${options.head}:${file}`
1240
+ ]);
1241
+ if (!tracked.ok) {
1242
+ steps.push([
1243
+ "rm",
1244
+ "-r",
1245
+ "--cached",
1246
+ "--quiet",
1247
+ "--ignore-unmatch",
1248
+ "--",
1249
+ file
1250
+ ]);
1251
+ }
1252
+ }
1253
+ for (const step of steps) {
1254
+ const result = await git(worktree, step, environment);
1255
+ if (!result.ok) {
1256
+ return {
1257
+ ok: false,
1258
+ reason: `git ${step[0]} failed: ${result.stderr}`
1259
+ };
1260
+ }
1261
+ }
1262
+ const tree = await git(worktree, ["write-tree"], environment);
1263
+ if (!tree.ok) {
1264
+ return { ok: false, reason: `git write-tree failed: ${tree.stderr}` };
1265
+ }
1266
+ const commit = await git(
1267
+ worktree,
1268
+ [
1269
+ "commit-tree",
1270
+ tree.stdout,
1271
+ "-p",
1272
+ options.head,
1273
+ ...options.previous ? ["-p", options.previous] : [],
1274
+ "-m",
1275
+ `aibex salvage ${options.threadId} epoch ${options.epoch}`
1276
+ ],
1277
+ environment
1278
+ );
1279
+ if (!commit.ok) {
1280
+ return { ok: false, reason: `git commit-tree failed: ${commit.stderr}` };
1281
+ }
1282
+ return { ok: true, commit: commit.stdout };
1283
+ } finally {
1284
+ rmSync(scratch, { recursive: true, force: true });
1285
+ }
1286
+ }
1287
+ async function releaseWorktree(options) {
1288
+ const { threadId } = options;
1289
+ if (options.sessionListed) {
1290
+ return {
1291
+ outcome: "refused",
1292
+ reason: "a session for this thread is listed"
1293
+ };
1294
+ }
1295
+ if (!THREAD_ID.test(threadId)) {
1296
+ return { outcome: "refused", reason: "not a thread id" };
1297
+ }
1298
+ const worktree = path.join(options.work, threadId);
1299
+ let exists = true;
1300
+ try {
1301
+ statSync(worktree);
1302
+ } catch {
1303
+ exists = false;
1304
+ }
1305
+ if (!exists) {
1306
+ let saved;
1307
+ for (const checkout2 of options.checkouts) {
1308
+ await git(checkout2, ["worktree", "prune"]);
1309
+ const dropped2 = await dropBranch(checkout2, threadId, options.epoch);
1310
+ if (!dropped2.ok) return { outcome: "refused", reason: dropped2.reason };
1311
+ saved = dropped2.salvage ?? saved;
1312
+ }
1313
+ return saved === void 0 ? { outcome: "released" } : { outcome: "released", salvage: saved };
1314
+ }
1315
+ if (!isWorktree(worktree)) {
1316
+ rmSync(worktree, { recursive: true, force: true });
1317
+ return { outcome: "released" };
1318
+ }
1319
+ const checkout = await checkoutOf(worktree);
1320
+ const head = await git(worktree, ["rev-parse", "--verify", "HEAD"]);
1321
+ if (!checkout || !head.ok) {
1322
+ return {
1323
+ outcome: "refused",
1324
+ reason: `not a usable worktree: ${head.stderr || "no checkout"}`
1325
+ };
1326
+ }
1327
+ const reference = salvageReference(threadId);
1328
+ const carry = carryList(options.reposConfig);
1329
+ const dirty = await isDirty(worktree, carry);
1330
+ const unpushed = await hasUnpushed(worktree);
1331
+ let salvage;
1332
+ if (dirty || unpushed) {
1333
+ const previous = await git(checkout, [
1334
+ "rev-parse",
1335
+ "--verify",
1336
+ "--quiet",
1337
+ reference
1338
+ ]);
1339
+ const made = await salvageCommit({
1340
+ worktree,
1341
+ threadId,
1342
+ epoch: options.epoch,
1343
+ head: head.stdout,
1344
+ carry,
1345
+ previous: previous.ok ? previous.stdout : void 0
1346
+ });
1347
+ if (!made.ok) return { outcome: "refused", reason: made.reason };
1348
+ const updated = await git(checkout, [
1349
+ "update-ref",
1350
+ "-m",
1351
+ `aibex salvage ${threadId}`,
1352
+ reference,
1353
+ made.commit
1354
+ ]);
1355
+ if (!updated.ok) {
1356
+ return {
1357
+ outcome: "refused",
1358
+ reason: `could not write ${reference}: ${updated.stderr}`
1359
+ };
1360
+ }
1361
+ salvage = made.commit;
1362
+ }
1363
+ const removed = await git(checkout, [
1364
+ "worktree",
1365
+ "remove",
1366
+ "--force",
1367
+ worktree
1368
+ ]);
1369
+ if (!removed.ok) {
1370
+ return {
1371
+ outcome: "refused",
1372
+ reason: `git worktree remove failed: ${removed.stderr}`
1373
+ };
1374
+ }
1375
+ const dropped = await dropBranch(checkout, threadId, options.epoch);
1376
+ if (!dropped.ok) return { outcome: "refused", reason: dropped.reason };
1377
+ salvage = dropped.salvage ?? salvage;
1378
+ return salvage === void 0 ? { outcome: "released" } : { outcome: "released", salvage };
1379
+ }
1380
+ async function dropBranch(checkout, threadId, epoch) {
1381
+ const branch = `aibex/${threadId}`;
1382
+ const known = await git(checkout, [
1383
+ "rev-parse",
1384
+ "--verify",
1385
+ "--quiet",
1386
+ `refs/heads/${branch}`
1387
+ ]);
1388
+ if (!known.ok) return { ok: true };
1389
+ const reference = salvageReference(threadId);
1390
+ const previous = await git(checkout, [
1391
+ "rev-parse",
1392
+ "--verify",
1393
+ "--quiet",
1394
+ reference
1395
+ ]);
1396
+ const unsaved = await git(checkout, [
1397
+ "rev-list",
1398
+ "--count",
1399
+ known.stdout,
1400
+ "--not",
1401
+ "--remotes",
1402
+ ...previous.ok ? [previous.stdout] : []
1403
+ ]);
1404
+ if (!unsaved.ok) {
1405
+ return { ok: false, reason: `git rev-list failed: ${unsaved.stderr}` };
1406
+ }
1407
+ let salvage;
1408
+ if (Number(unsaved.stdout) > 0) {
1409
+ const commit = await git(
1410
+ checkout,
1411
+ [
1412
+ "commit-tree",
1413
+ `${known.stdout}^{tree}`,
1414
+ "-p",
1415
+ known.stdout,
1416
+ ...previous.ok ? ["-p", previous.stdout] : [],
1417
+ "-m",
1418
+ `aibex salvage ${threadId} epoch ${epoch}`
1419
+ ],
1420
+ SALVAGE_IDENTITY
1421
+ );
1422
+ if (!commit.ok) {
1423
+ return { ok: false, reason: `git commit-tree failed: ${commit.stderr}` };
1424
+ }
1425
+ const updated = await git(checkout, [
1426
+ "update-ref",
1427
+ "-m",
1428
+ `aibex salvage ${threadId}`,
1429
+ reference,
1430
+ commit.stdout
1431
+ ]);
1432
+ if (!updated.ok) {
1433
+ return {
1434
+ ok: false,
1435
+ reason: `could not write ${reference}: ${updated.stderr}`
1436
+ };
1437
+ }
1438
+ salvage = commit.stdout;
1439
+ }
1440
+ const deleted = await git(checkout, ["branch", "-D", "--quiet", branch]);
1441
+ if (!deleted.ok) {
1442
+ return { ok: false, reason: `git branch -D failed: ${deleted.stderr}` };
1443
+ }
1444
+ return salvage === void 0 ? { ok: true } : { ok: true, salvage };
1445
+ }
1446
+ async function sweep(options) {
1447
+ const removed = [];
1448
+ for (const checkout of options.checkouts) {
1449
+ await git(checkout, ["worktree", "prune"]);
1450
+ }
1451
+ let names = [];
1452
+ try {
1453
+ names = readdirSync(options.sessionsDirectory);
1454
+ } catch {
1455
+ }
1456
+ const records = new Set(
1457
+ names.filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5))
1458
+ );
1459
+ for (const name of names) {
1460
+ if (!name.endsWith(".spool") || records.has(name.slice(0, -6))) continue;
1461
+ rmSync(path.join(options.sessionsDirectory, name), { force: true });
1462
+ removed.push(path.join(options.sessionsDirectory, name));
1463
+ }
1464
+ for (const threadId of threadDirectories(options.work)) {
1465
+ const directory = path.join(options.work, threadId);
1466
+ if (isWorktree(directory)) continue;
1467
+ try {
1468
+ if (options.now - statSync(directory).mtimeMs < HALF_MADE_AGE_MS)
1469
+ continue;
1470
+ } catch {
1471
+ continue;
1472
+ }
1473
+ rmSync(directory, { recursive: true, force: true });
1474
+ removed.push(directory);
1475
+ }
1476
+ return removed;
1477
+ }
1478
+ class Reaper {
1479
+ constructor(options) {
1480
+ this.options = options;
1481
+ }
1482
+ listing = [];
1483
+ scannedAt = Number.NEGATIVE_INFINITY;
1484
+ pending = [];
1485
+ inFlight = [];
1486
+ now() {
1487
+ return (this.options.now ?? Date.now)();
1488
+ }
1489
+ /** The listing and the outcomes to report in the next heartbeat. */
1490
+ async report() {
1491
+ const now = this.now();
1492
+ if (now - this.scannedAt >= (this.options.scanMs ?? WORKTREE_SCAN_MS)) {
1493
+ this.listing = await scanWorktrees(
1494
+ this.options.work,
1495
+ this.options.reposConfig
1496
+ );
1497
+ this.scannedAt = now;
1498
+ }
1499
+ this.inFlight = [...this.pending];
1500
+ return { worktrees: this.listing, releases: this.inFlight };
1501
+ }
1502
+ /** The poll that carried the last report succeeded. */
1503
+ delivered() {
1504
+ this.pending = this.pending.filter(
1505
+ (result) => !this.inFlight.includes(result)
1506
+ );
1507
+ this.inFlight = [];
1508
+ }
1509
+ /** Handles one `work.release`. */
1510
+ async release(command, sessionListed) {
1511
+ const outcome = await releaseWorktree({
1512
+ work: this.options.work,
1513
+ threadId: command.thread_id,
1514
+ epoch: command.epoch,
1515
+ reposConfig: this.options.reposConfig,
1516
+ checkouts: await this.options.checkouts(),
1517
+ sessionListed
1518
+ });
1519
+ const result = {
1520
+ command_id: command.command_id,
1521
+ thread_id: command.thread_id,
1522
+ epoch: command.epoch,
1523
+ ...outcome
1524
+ };
1525
+ this.options.log(
1526
+ outcome.outcome === "released" ? `${command.thread_id}: worktree released${outcome.salvage ? `; its work is saved at ${salvageReference(command.thread_id)} (${outcome.salvage})` : ""}` : `${command.thread_id}: release refused: ${outcome.reason}`
1527
+ );
1528
+ this.pending.push(result);
1529
+ this.scannedAt = Number.NEGATIVE_INFINITY;
1530
+ return result;
1531
+ }
1532
+ }
919
1533
  const LOG_TAIL_LINES = 50;
920
1534
  class LinkLog {
921
1535
  constructor(write = (line) => process.stdout.write(`${line}
@@ -1672,79 +2286,6 @@ class Relay {
1672
2286
  for (const message of queued) event(message);
1673
2287
  }
1674
2288
  }
1675
- const GITHUB_HOST = "github.com";
1676
- const REPO_SCAN_MS = 6e4;
1677
- const GITHUB_REMOTE = [
1678
- /^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
1679
- /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
1680
- ];
1681
- function parseGitHubRemote(url) {
1682
- for (const pattern of GITHUB_REMOTE) {
1683
- const match = pattern.exec(url.trim());
1684
- if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
1685
- }
1686
- return void 0;
1687
- }
1688
- function git(cwd, args) {
1689
- return new Promise((resolve) => {
1690
- execFile(
1691
- "git",
1692
- ["-C", cwd, ...args],
1693
- (failure, stdout, stderr) => resolve({
1694
- ok: failure === null,
1695
- stdout: stdout.trim(),
1696
- stderr: stderr.trim()
1697
- })
1698
- );
1699
- });
1700
- }
1701
- function directories(parent) {
1702
- try {
1703
- return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
1704
- } catch {
1705
- return [];
1706
- }
1707
- }
1708
- async function scanRepos(reposDirectory) {
1709
- const github = path.join(reposDirectory, GITHUB_HOST);
1710
- const candidates = directories(github).flatMap(
1711
- (owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
1712
- );
1713
- const found = await Promise.all(
1714
- candidates.map(async (directory) => {
1715
- const origin = await git(directory, [
1716
- "config",
1717
- "--get",
1718
- "remote.origin.url"
1719
- ]);
1720
- const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
1721
- return repo ? { repo, path: directory } : void 0;
1722
- })
1723
- );
1724
- return found.filter((checkout) => checkout !== void 0);
1725
- }
1726
- class Repos {
1727
- constructor(reposDirectory, now = Date.now) {
1728
- this.reposDirectory = reposDirectory;
1729
- this.now = now;
1730
- }
1731
- scanned = [];
1732
- scannedAt = Number.NEGATIVE_INFINITY;
1733
- async list(options = {}) {
1734
- if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
1735
- this.scanned = await scanRepos(this.reposDirectory);
1736
- this.scannedAt = this.now();
1737
- }
1738
- return this.scanned;
1739
- }
1740
- /** The checkout for a repository, rescanning once when it is not known. */
1741
- async find(repo) {
1742
- const match = (checkouts) => checkouts.find(
1743
- (checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
1744
- );
1745
- return match(await this.list()) ?? match(await this.list({ fresh: true }));
1746
- }
1747
- }
1748
2289
  const HARNESSES = {
1749
2290
  // The input box: a full-width rule, then `❯` and the placeholder. The
1750
2291
  // folder trust dialog also starts a line with `❯`, but never under a rule.
@@ -1920,79 +2461,6 @@ class Transcript {
1920
2461
  rmSync(this.spoolFile, { force: true });
1921
2462
  }
1922
2463
  }
1923
- const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
1924
- function carryList(reposConfig) {
1925
- const value = readJson(reposConfig);
1926
- const carry = value?.carry;
1927
- if (!Array.isArray(carry)) return DEFAULT_CARRY;
1928
- return carry.filter(
1929
- (entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
1930
- );
1931
- }
1932
- async function defaultBranch(checkout) {
1933
- const head = await git(checkout, [
1934
- "symbolic-ref",
1935
- "--short",
1936
- "refs/remotes/origin/HEAD"
1937
- ]);
1938
- return head.ok && head.stdout.startsWith("origin/") ? head.stdout.slice("origin/".length) : "main";
1939
- }
1940
- async function prepareWorktree(options) {
1941
- const { checkout, threadId } = options;
1942
- const worktreePath = path.join(options.workDirectory, threadId);
1943
- const branch = `aibex/${threadId}`;
1944
- const fetched = await git(checkout, ["fetch", "--quiet", "origin"]);
1945
- const base = options.baseRef ?? await defaultBranch(checkout);
1946
- if (!existsSync(path.join(worktreePath, ".git"))) {
1947
- mkdirSync(options.workDirectory, { recursive: true });
1948
- const known = await git(checkout, [
1949
- "rev-parse",
1950
- "--verify",
1951
- "--quiet",
1952
- `refs/heads/${branch}`
1953
- ]);
1954
- const added = await git(
1955
- checkout,
1956
- known.ok ? ["worktree", "add", "--quiet", worktreePath, branch] : [
1957
- "worktree",
1958
- "add",
1959
- "--quiet",
1960
- "-b",
1961
- branch,
1962
- worktreePath,
1963
- `origin/${base}`
1964
- ]
1965
- );
1966
- if (!added.ok) {
1967
- const why = added.stderr || `git worktree add failed`;
1968
- return {
1969
- ok: false,
1970
- reason: fetched.ok ? why : `${why} (git fetch failed too: ${fetched.stderr})`
1971
- };
1972
- }
1973
- }
1974
- const carried = [];
1975
- for (const file of carryList(options.reposConfig)) {
1976
- const from = path.join(checkout, file);
1977
- const to = path.join(worktreePath, file);
1978
- if (!existsSync(from) || existsSync(to)) continue;
1979
- const tracked = await git(checkout, [
1980
- "ls-files",
1981
- "--error-unmatch",
1982
- "--",
1983
- file
1984
- ]);
1985
- if (tracked.ok) continue;
1986
- mkdirSync(path.dirname(to), { recursive: true });
1987
- cpSync(from, to, { recursive: true });
1988
- carried.push(file);
1989
- }
1990
- return {
1991
- ok: true,
1992
- worktree: { path: worktreePath, branch, base },
1993
- carried
1994
- };
1995
- }
1996
2464
  const DEFAULT_SESSION_TIMINGS = {
1997
2465
  readyTimeoutMs: 6e4,
1998
2466
  checkMs: 250,
@@ -2668,6 +3136,11 @@ class Sessions {
2668
3136
  return;
2669
3137
  }
2670
3138
  record.worktree = prepared.worktree;
3139
+ if (prepared.restored !== void 0) {
3140
+ this.options.log.line(
3141
+ `${record.thread_id}: rebuilt its worktree from salvaged work (${prepared.restored})`
3142
+ );
3143
+ }
2671
3144
  const socket = this.options.terminalSocket;
2672
3145
  let client;
2673
3146
  try {
@@ -3162,6 +3635,7 @@ function main() {
3162
3635
  const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
3163
3636
  let poller;
3164
3637
  let sessions;
3638
+ let reaper;
3165
3639
  if (identity) {
3166
3640
  sessions = new Sessions({
3167
3641
  paths,
@@ -3187,6 +3661,16 @@ function main() {
3187
3661
  log
3188
3662
  });
3189
3663
  const running = sessions;
3664
+ reaper = new Reaper({
3665
+ work: paths.work,
3666
+ reposConfig: paths.reposConfig,
3667
+ checkouts: async () => {
3668
+ const checkouts = await repos.list();
3669
+ return checkouts.map((checkout) => checkout.path);
3670
+ },
3671
+ log: (line) => log.line(line)
3672
+ });
3673
+ const reaping = reaper;
3190
3674
  const relay = new Relay({
3191
3675
  host: identity.host,
3192
3676
  herd: new HerdClient(identity),
@@ -3220,18 +3704,27 @@ function main() {
3220
3704
  features: ["sessions", "relay", "setup"],
3221
3705
  sessions: running.list(),
3222
3706
  setupTerminals: await setup.list(),
3223
- activations: activations.list()
3707
+ activations: activations.list(),
3708
+ ...await reaping.report()
3224
3709
  }),
3225
3710
  handleCommand: async (command) => {
3226
3711
  if (command.type === "relay.open") {
3227
3712
  await relay.open();
3228
3713
  return true;
3229
3714
  }
3715
+ if (command.type === "work.release") {
3716
+ const listed = running.list().some(
3717
+ (session) => session.thread_id === command.thread_id && session.state !== "ended"
3718
+ );
3719
+ await reaping.release(command, listed);
3720
+ return true;
3721
+ }
3230
3722
  if (command.type !== "terminal.open") return running.handle(command);
3231
3723
  await setup.open(command);
3232
3724
  return true;
3233
3725
  },
3234
3726
  afterPoll: async (answer) => {
3727
+ reaping.delivered();
3235
3728
  activations.confirm(answer.activations_confirmed);
3236
3729
  await running.afterPoll(answer);
3237
3730
  },
@@ -3298,6 +3791,18 @@ function main() {
3298
3791
  if (poller && sessions) {
3299
3792
  const [started, recorded] = [poller, sessions];
3300
3793
  void (async () => {
3794
+ try {
3795
+ const checkouts = await repos.list();
3796
+ const swept = await sweep({
3797
+ checkouts: checkouts.map((checkout) => checkout.path),
3798
+ work: paths.work,
3799
+ sessionsDirectory: path.join(hostDirectory, "sessions"),
3800
+ now: Date.now()
3801
+ });
3802
+ for (const removed of swept) log.line(`removed litter ${removed}`);
3803
+ } catch (error) {
3804
+ log.line(`the start-up sweep failed: ${String(error)}`);
3805
+ }
3301
3806
  try {
3302
3807
  await recorded.resume();
3303
3808
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibexhq/aibex-link",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "description": "The process aibexd runs to link a machine to an Aibex herd",
5
5
  "homepage": "https://github.com/aibexhq",
6
6
  "bugs": {