@aibexhq/aibex-link 0.0.12 → 0.0.13

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 +252 -110
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, statSync, cpSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
1
+ import { readFileSync, mkdirSync, writeFileSync, chmodSync, renameSync, rmSync, existsSync, readdirSync, realpathSync, lstatSync, cpSync, statSync, mkdtempSync, appendFileSync, openSync, readSync, closeSync, accessSync, constants } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
4
4
  import { execFile } from "node:child_process";
@@ -700,6 +700,239 @@ class Access {
700
700
  return { accept: file.accept, integrations: file.integrations };
701
701
  }
702
702
  }
703
+ const GITHUB_HOST = "github.com";
704
+ const REPO_SCAN_MS = 6e4;
705
+ const GITHUB_REMOTE = [
706
+ /^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
707
+ /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
708
+ ];
709
+ function parseGitHubRemote(url) {
710
+ for (const pattern of GITHUB_REMOTE) {
711
+ const match = pattern.exec(url.trim());
712
+ if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
713
+ }
714
+ return void 0;
715
+ }
716
+ function git(cwd, args, environment) {
717
+ return new Promise((resolve) => {
718
+ execFile(
719
+ "git",
720
+ ["-C", cwd, ...args],
721
+ environment ? { env: { ...process.env, ...environment } } : {},
722
+ (failure, stdout, stderr) => resolve({
723
+ ok: failure === null,
724
+ stdout: stdout.trim(),
725
+ stderr: stderr.trim()
726
+ })
727
+ );
728
+ });
729
+ }
730
+ function directories(parent) {
731
+ try {
732
+ return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
733
+ } catch {
734
+ return [];
735
+ }
736
+ }
737
+ async function scanRepos(reposDirectory) {
738
+ const github = path.join(reposDirectory, GITHUB_HOST);
739
+ const candidates = directories(github).flatMap(
740
+ (owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
741
+ );
742
+ const found = await Promise.all(
743
+ candidates.map(async (directory) => {
744
+ const origin = await git(directory, [
745
+ "config",
746
+ "--get",
747
+ "remote.origin.url"
748
+ ]);
749
+ const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
750
+ return repo ? { repo, path: directory } : void 0;
751
+ })
752
+ );
753
+ return found.filter((checkout) => checkout !== void 0);
754
+ }
755
+ class Repos {
756
+ constructor(reposDirectory, now = Date.now) {
757
+ this.reposDirectory = reposDirectory;
758
+ this.now = now;
759
+ }
760
+ scanned = [];
761
+ scannedAt = Number.NEGATIVE_INFINITY;
762
+ async list(options = {}) {
763
+ if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
764
+ this.scanned = await scanRepos(this.reposDirectory);
765
+ this.scannedAt = this.now();
766
+ }
767
+ return this.scanned;
768
+ }
769
+ /** The checkout for a repository, rescanning once when it is not known. */
770
+ async find(repo) {
771
+ const match = (checkouts) => checkouts.find(
772
+ (checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
773
+ );
774
+ return match(await this.list()) ?? match(await this.list({ fresh: true }));
775
+ }
776
+ }
777
+ const REPO_FILE = ".aibex/repo.json";
778
+ const CARRY_MAX = 20;
779
+ const CARRY_ENTRY_MAX = 200;
780
+ const REPO_FILE_MAX_BYTES = 64 * 1024;
781
+ function carryEntryProblem(entry) {
782
+ if (typeof entry !== "string") return "is not a string";
783
+ if (entry === "") return "is empty";
784
+ if (entry.length > CARRY_ENTRY_MAX)
785
+ return `is longer than ${CARRY_ENTRY_MAX} characters`;
786
+ if (entry.includes("\0") || entry.includes("\\"))
787
+ return "holds a backslash or a NUL";
788
+ if (path.isAbsolute(entry) || path.win32.isAbsolute(entry))
789
+ return "is absolute";
790
+ if (/[*?[]/u.test(entry) || entry.startsWith(":"))
791
+ return 'holds a glob character or starts with ":"';
792
+ const parts = entry.split("/");
793
+ if (parts.some((part) => part === "" || part === "." || part === ".."))
794
+ return 'is not a plain relative path (no "..", ".", "//" or trailing "/")';
795
+ if (parts.some((part) => part.toLowerCase() === ".git"))
796
+ return "is inside .git";
797
+ return void 0;
798
+ }
799
+ function carryList(worktree) {
800
+ const file = path.join(worktree, REPO_FILE);
801
+ let stats;
802
+ try {
803
+ stats = lstatSync(file);
804
+ } catch {
805
+ return { carry: [], problems: [] };
806
+ }
807
+ if (!stats.isFile()) {
808
+ return { carry: [], problems: [`${REPO_FILE} is not a regular file`] };
809
+ }
810
+ if (stats.size > REPO_FILE_MAX_BYTES) {
811
+ return {
812
+ carry: [],
813
+ problems: [`${REPO_FILE} is larger than ${REPO_FILE_MAX_BYTES} bytes`]
814
+ };
815
+ }
816
+ let parsed;
817
+ try {
818
+ parsed = JSON.parse(readFileSync(file, "utf8"));
819
+ } catch {
820
+ return { carry: [], problems: [`${REPO_FILE} is not valid JSON`] };
821
+ }
822
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
823
+ return { carry: [], problems: [`${REPO_FILE} is not a JSON object`] };
824
+ }
825
+ const value = parsed.carry;
826
+ if (value === void 0) return { carry: [], problems: [] };
827
+ if (!Array.isArray(value)) {
828
+ return { carry: [], problems: [`${REPO_FILE}: "carry" is not a list`] };
829
+ }
830
+ const carry = [];
831
+ const problems = [];
832
+ if (value.length > CARRY_MAX) {
833
+ problems.push(
834
+ `${REPO_FILE}: "carry" lists ${value.length} entries; only the first ${CARRY_MAX} are read`
835
+ );
836
+ }
837
+ for (const entry of value.slice(0, CARRY_MAX)) {
838
+ const problem = carryEntryProblem(entry);
839
+ if (problem !== void 0) {
840
+ problems.push(
841
+ `${REPO_FILE}: carry entry ${JSON.stringify(entry)} skipped: it ${problem}`
842
+ );
843
+ } else if (!carry.includes(entry)) {
844
+ carry.push(entry);
845
+ }
846
+ }
847
+ return { carry, problems };
848
+ }
849
+ function inside(parent, child) {
850
+ const relative = path.relative(parent, child);
851
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
852
+ }
853
+ function realAncestor(target) {
854
+ let current = target;
855
+ for (; ; ) {
856
+ try {
857
+ return realpathSync(current);
858
+ } catch {
859
+ const parent = path.dirname(current);
860
+ if (parent === current) return current;
861
+ current = parent;
862
+ }
863
+ }
864
+ }
865
+ async function carryInto(checkout, worktree) {
866
+ const { carry, problems } = carryList(worktree);
867
+ const carried = [];
868
+ let checkoutReal;
869
+ let worktreeReal;
870
+ try {
871
+ checkoutReal = realpathSync(checkout);
872
+ worktreeReal = realpathSync(worktree);
873
+ } catch (error) {
874
+ problems.push(`carry skipped: ${error.message}`);
875
+ return { carried, problems };
876
+ }
877
+ for (const entry of carry) {
878
+ const from = path.join(checkout, entry);
879
+ const to = path.join(worktree, entry);
880
+ const skip = (why) => problems.push(`carry entry ${JSON.stringify(entry)} skipped: ${why}`);
881
+ let source;
882
+ try {
883
+ source = lstatSync(from);
884
+ } catch {
885
+ continue;
886
+ }
887
+ if (source.isSymbolicLink()) {
888
+ skip("it is a symbolic link in the checkout");
889
+ continue;
890
+ }
891
+ if (!source.isFile() && !source.isDirectory()) {
892
+ skip("it is not a file or a directory");
893
+ continue;
894
+ }
895
+ if (!inside(checkoutReal, realpathSync(from))) {
896
+ skip("it leads out of the checkout");
897
+ continue;
898
+ }
899
+ if (existsSync(to) || isLink(to)) continue;
900
+ const tracked = await git(checkout, [
901
+ "--literal-pathspecs",
902
+ "ls-files",
903
+ "--error-unmatch",
904
+ "--",
905
+ entry
906
+ ]);
907
+ if (tracked.ok) continue;
908
+ if (!inside(worktreeReal, realAncestor(path.dirname(to)))) {
909
+ skip("it leads out of the worktree");
910
+ continue;
911
+ }
912
+ try {
913
+ mkdirSync(path.dirname(to), { recursive: true });
914
+ cpSync(from, to, {
915
+ recursive: true,
916
+ filter: (item) => !lstatSync(item).isSymbolicLink()
917
+ });
918
+ carried.push(entry);
919
+ } catch (error) {
920
+ skip(`the copy failed: ${error.message}`);
921
+ }
922
+ }
923
+ return { carried, problems };
924
+ }
925
+ function isLink(file) {
926
+ try {
927
+ return lstatSync(file).isSymbolicLink();
928
+ } catch {
929
+ return false;
930
+ }
931
+ }
932
+ function retiredReposConfigNotice(file) {
933
+ if (!existsSync(file)) return void 0;
934
+ return `${file} is no longer read: nothing is carried into worktrees unless a repository lists it under "carry" in its own ${REPO_FILE}`;
935
+ }
703
936
  const DEFAULT_ALIVE_INTERVAL_MS = 15e3;
704
937
  const DEFAULT_POLL_BACKOFF_INITIAL_MS = 5e3;
705
938
  const DEFAULT_POLL_BACKOFF_MAX_MS = 5 * 6e4;
@@ -988,7 +1221,7 @@ function linkPaths(hostDirectory) {
988
1221
  work: path.join(state, "work"),
989
1222
  scratch: path.join(state, "scratch"),
990
1223
  bin: path.join(state, "bin"),
991
- reposConfig: path.join(state, "repos.json"),
1224
+ retiredReposConfig: path.join(state, "repos.json"),
992
1225
  config: path.join(state, "config.json"),
993
1226
  access: path.join(hostDirectory, "access.json")
994
1227
  };
@@ -1098,80 +1331,6 @@ function buildHeartbeat(input) {
1098
1331
  if (input.diagnostics) heartbeat.diagnostics = input.diagnostics;
1099
1332
  return heartbeat;
1100
1333
  }
1101
- const GITHUB_HOST = "github.com";
1102
- const REPO_SCAN_MS = 6e4;
1103
- const GITHUB_REMOTE = [
1104
- /^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u,
1105
- /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
1106
- ];
1107
- function parseGitHubRemote(url) {
1108
- for (const pattern of GITHUB_REMOTE) {
1109
- const match = pattern.exec(url.trim());
1110
- if (match?.[1] && match[2]) return { owner: match[1], name: match[2] };
1111
- }
1112
- return void 0;
1113
- }
1114
- function git(cwd, args, environment) {
1115
- return new Promise((resolve) => {
1116
- execFile(
1117
- "git",
1118
- ["-C", cwd, ...args],
1119
- environment ? { env: { ...process.env, ...environment } } : {},
1120
- (failure, stdout, stderr) => resolve({
1121
- ok: failure === null,
1122
- stdout: stdout.trim(),
1123
- stderr: stderr.trim()
1124
- })
1125
- );
1126
- });
1127
- }
1128
- function directories(parent) {
1129
- try {
1130
- return readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).toSorted();
1131
- } catch {
1132
- return [];
1133
- }
1134
- }
1135
- async function scanRepos(reposDirectory) {
1136
- const github = path.join(reposDirectory, GITHUB_HOST);
1137
- const candidates = directories(github).flatMap(
1138
- (owner) => directories(path.join(github, owner)).map((name) => path.join(github, owner, name)).filter((directory) => existsSync(path.join(directory, ".git")))
1139
- );
1140
- const found = await Promise.all(
1141
- candidates.map(async (directory) => {
1142
- const origin = await git(directory, [
1143
- "config",
1144
- "--get",
1145
- "remote.origin.url"
1146
- ]);
1147
- const repo = origin.ok ? parseGitHubRemote(origin.stdout) : void 0;
1148
- return repo ? { repo, path: directory } : void 0;
1149
- })
1150
- );
1151
- return found.filter((checkout) => checkout !== void 0);
1152
- }
1153
- class Repos {
1154
- constructor(reposDirectory, now = Date.now) {
1155
- this.reposDirectory = reposDirectory;
1156
- this.now = now;
1157
- }
1158
- scanned = [];
1159
- scannedAt = Number.NEGATIVE_INFINITY;
1160
- async list(options = {}) {
1161
- if (options.fresh || this.now() - this.scannedAt >= REPO_SCAN_MS) {
1162
- this.scanned = await scanRepos(this.reposDirectory);
1163
- this.scannedAt = this.now();
1164
- }
1165
- return this.scanned;
1166
- }
1167
- /** The checkout for a repository, rescanning once when it is not known. */
1168
- async find(repo) {
1169
- const match = (checkouts) => checkouts.find(
1170
- (checkout) => checkout.repo.owner.toLowerCase() === repo.owner.toLowerCase() && checkout.repo.name.toLowerCase() === repo.name.toLowerCase()
1171
- );
1172
- return match(await this.list()) ?? match(await this.list({ fresh: true }));
1173
- }
1174
- }
1175
1334
  const THREAD_ID$1 = /^t_[A-Za-z0-9]{8,64}$/u;
1176
1335
  function prepareScratch(scratch, threadId) {
1177
1336
  if (!THREAD_ID$1.test(threadId))
@@ -1224,15 +1383,6 @@ function removeScratch(scratch, threadId) {
1224
1383
  if (!THREAD_ID$1.test(threadId)) return;
1225
1384
  rmSync(path.join(scratch, threadId), { recursive: true, force: true });
1226
1385
  }
1227
- const DEFAULT_CARRY = [".mcp.json", ".claude/settings.local.json"];
1228
- function carryList(reposConfig) {
1229
- const value = readJson(reposConfig);
1230
- const carry = value?.carry;
1231
- if (!Array.isArray(carry)) return DEFAULT_CARRY;
1232
- return carry.filter(
1233
- (entry) => typeof entry === "string" && entry !== "" && !path.isAbsolute(entry) && !entry.split(/[/\\]/u).includes("..")
1234
- );
1235
- }
1236
1386
  function salvageReference(threadId) {
1237
1387
  return `refs/aibex/salvage/${threadId}`;
1238
1388
  }
@@ -1326,26 +1476,12 @@ async function prepareWorktree(options) {
1326
1476
  };
1327
1477
  }
1328
1478
  }
1329
- const carried = [];
1330
- for (const file of carryList(options.reposConfig)) {
1331
- const from = path.join(checkout, file);
1332
- const to = path.join(worktreePath, file);
1333
- if (!existsSync(from) || existsSync(to)) continue;
1334
- const tracked = await git(checkout, [
1335
- "ls-files",
1336
- "--error-unmatch",
1337
- "--",
1338
- file
1339
- ]);
1340
- if (tracked.ok) continue;
1341
- mkdirSync(path.dirname(to), { recursive: true });
1342
- cpSync(from, to, { recursive: true });
1343
- carried.push(file);
1344
- }
1479
+ const { carried, problems } = await carryInto(checkout, worktreePath);
1345
1480
  return {
1346
1481
  ok: true,
1347
1482
  worktree: { path: worktreePath, branch, base },
1348
1483
  carried,
1484
+ carryProblems: problems,
1349
1485
  ...restored === void 0 ? {} : { restored }
1350
1486
  };
1351
1487
  }
@@ -1411,8 +1547,7 @@ async function isDirty(worktree, carry) {
1411
1547
  }
1412
1548
  return false;
1413
1549
  }
1414
- async function scanWorktrees(work, reposConfig) {
1415
- const carry = carryList(reposConfig);
1550
+ async function scanWorktrees(work) {
1416
1551
  const listings = [];
1417
1552
  for (const threadId of threadDirectories(work)) {
1418
1553
  const directory = path.join(work, threadId);
@@ -1432,7 +1567,7 @@ async function scanWorktrees(work, reposConfig) {
1432
1567
  const head = await git(directory, ["rev-parse", "--verify", "HEAD"]);
1433
1568
  if (head.ok && /^[0-9a-f]{40}$/u.test(head.stdout)) {
1434
1569
  listing.head = head.stdout;
1435
- listing.dirty = await isDirty(directory, carry);
1570
+ listing.dirty = await isDirty(directory, carryList(directory).carry);
1436
1571
  listing.unpushed = await hasUnpushed(directory);
1437
1572
  }
1438
1573
  }
@@ -1545,7 +1680,7 @@ async function releaseWorktree(options) {
1545
1680
  };
1546
1681
  }
1547
1682
  const reference = salvageReference(threadId);
1548
- const carry = carryList(options.reposConfig);
1683
+ const carry = carryList(worktree).carry;
1549
1684
  const dirty = await isDirty(worktree, carry);
1550
1685
  const unpushed = await hasUnpushed(worktree);
1551
1686
  let salvage;
@@ -1711,7 +1846,7 @@ class Reaper {
1711
1846
  const now = this.now();
1712
1847
  if (now - this.scannedAt >= (this.options.scanMs ?? WORKTREE_SCAN_MS)) {
1713
1848
  this.listing = [
1714
- ...await scanWorktrees(this.options.work, this.options.reposConfig),
1849
+ ...await scanWorktrees(this.options.work),
1715
1850
  ...scanScratch(this.options.scratch)
1716
1851
  ];
1717
1852
  this.scannedAt = now;
@@ -1743,7 +1878,6 @@ class Reaper {
1743
1878
  work: this.options.work,
1744
1879
  threadId: command.thread_id,
1745
1880
  epoch: command.epoch,
1746
- reposConfig: this.options.reposConfig,
1747
1881
  checkouts: await this.options.checkouts(),
1748
1882
  sessionListed
1749
1883
  });
@@ -3721,8 +3855,7 @@ class Sessions {
3721
3855
  checkout: checkout.path,
3722
3856
  workDirectory: this.options.paths.work,
3723
3857
  threadId: record.thread_id,
3724
- baseRef: request.base_ref,
3725
- reposConfig: this.options.paths.reposConfig
3858
+ baseRef: request.base_ref
3726
3859
  });
3727
3860
  if (stale()) return;
3728
3861
  if (!prepared.ok) {
@@ -3731,6 +3864,14 @@ class Sessions {
3731
3864
  }
3732
3865
  record.worktree = prepared.worktree;
3733
3866
  directory = prepared.worktree.path;
3867
+ if (prepared.carried.length > 0) {
3868
+ this.options.log.line(
3869
+ `${record.thread_id}: carried ${prepared.carried.join(", ")} from the checkout`
3870
+ );
3871
+ }
3872
+ for (const problem of prepared.carryProblems) {
3873
+ this.options.log.line(`${record.thread_id}: ${problem}`);
3874
+ }
3734
3875
  if (prepared.restored !== void 0) {
3735
3876
  this.options.log.line(
3736
3877
  `${record.thread_id}: rebuilt its worktree from salvaged work (${prepared.restored})`
@@ -4113,6 +4254,8 @@ function main() {
4113
4254
  const access = new Access(paths.access);
4114
4255
  const repos = new Repos(paths.repos);
4115
4256
  rmSync(path.join(hostDirectory, "activations.json"), { force: true });
4257
+ const retired = retiredReposConfigNotice(paths.retiredReposConfig);
4258
+ if (retired !== void 0) log.line(retired);
4116
4259
  const terminalSocket = process.env.AIBEX_TERMINAL_SOCKET;
4117
4260
  const terminalsDirectory = process.env.AIBEX_TERMINALS_DIR;
4118
4261
  let poller;
@@ -4156,7 +4299,6 @@ function main() {
4156
4299
  reaper = new Reaper({
4157
4300
  work: paths.work,
4158
4301
  scratch: paths.scratch,
4159
- reposConfig: paths.reposConfig,
4160
4302
  checkouts: async () => {
4161
4303
  const checkouts = await repos.list();
4162
4304
  return checkouts.map((checkout) => checkout.path);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibexhq/aibex-link",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
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": {