pi-straw-boss 0.80.0 → 0.80.2

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.
@@ -4393,7 +4393,7 @@ function checkStages(stages) {
4393
4393
 
4394
4394
  // src/train/appsconfig.ts
4395
4395
  import { existsSync as existsSync8, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "node:fs";
4396
- import { basename as basename2, dirname as dirname6, join as join12, resolve as resolve2 } from "node:path";
4396
+ import { basename as basename2, dirname as dirname6, join as join12, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
4397
4397
  var MIGRATION = "see docs/how-it-works.md, Moving a project to 0.65.0";
4398
4398
  function gitRoot(dir) {
4399
4399
  for (let d = dir; ; d = dirname6(d)) {
@@ -4479,6 +4479,62 @@ function repoRoot(dir) {
4479
4479
  return real2(root);
4480
4480
  }
4481
4481
  }
4482
+ function gitDirs(root) {
4483
+ try {
4484
+ const dot = join12(root, ".git"), named2 = statSync7(dot).isFile() ? /^gitdir:\s*(.+)$/m.exec(readFileSync12(dot, "utf8"))[1].trim() : dot, gitdir = realpathSync2(resolve2(root, named2));
4485
+ return [gitdir, commonOf(gitdir)];
4486
+ } catch {
4487
+ return [];
4488
+ }
4489
+ }
4490
+ function commonOf(gitdir) {
4491
+ const file = join12(gitdir, "commondir");
4492
+ return existsSync8(file) ? realpathSync2(resolve2(gitdir, readFileSync12(file, "utf8").trim())) : gitdir;
4493
+ }
4494
+ function appRepos(dir, app) {
4495
+ const read = readApps(dir), at2 = read.ok ? read.apps.find((a) => a.name === app)?.dir : void 0;
4496
+ if (typeof at2 !== "string") return [];
4497
+ const top = resolve2(gitRoot(dir)), home = repoRoot(dir);
4498
+ const inside2 = (path, root) => path.startsWith(root + sep2);
4499
+ const own2 = (root) => {
4500
+ const folder = resolve2(root, at2);
4501
+ if (!inside2(folder, root)) return [];
4502
+ try {
4503
+ const real2 = realpathSync2(root), mine = gitDirs(top), allowed = [real2, home, ...mine], within2 = (path) => allowed.some((a) => path === a || inside2(path, a));
4504
+ for (let d = realpathSync2(folder); inside2(d, real2); d = dirname6(d)) {
4505
+ const dot = join12(d, ".git"), stat = statSync7(dot, { throwIfNoEntry: false });
4506
+ if (!stat) continue;
4507
+ const named2 = stat.isDirectory() ? dot : stat.isFile() ? /^gitdir:\s*(.+)$/m.exec(readFileSync12(dot, "utf8"))?.[1]?.trim() : void 0;
4508
+ if (named2 === void 0) return [];
4509
+ const gitdir = realpathSync2(resolve2(d, named2)), common = commonOf(gitdir);
4510
+ if (common === mine[1] || !existsSync8(join12(gitdir, "HEAD"))) return [];
4511
+ return within2(gitdir) && within2(common) ? [d] : [];
4512
+ }
4513
+ } catch {
4514
+ }
4515
+ return [];
4516
+ };
4517
+ return [.../* @__PURE__ */ new Set([...own2(top), ...own2(home)])];
4518
+ }
4519
+ function appLinkPaths(dir, app) {
4520
+ const read = readApps(dir), at2 = read.ok ? read.apps.find((a) => a.name === app)?.dir : void 0, root = resolve2(gitRoot(dir)), paths = [];
4521
+ if (typeof at2 !== "string") return { root, paths };
4522
+ for (let d = resolve2(root, at2); d.startsWith(root + sep2); d = dirname6(d)) paths.push(relative2(root, d).split(sep2).join("/"));
4523
+ return { root, paths };
4524
+ }
4525
+ function gitmodulesPaths(root) {
4526
+ let text4;
4527
+ try {
4528
+ text4 = readFileSync12(join12(root, ".gitmodules"), "utf8");
4529
+ } catch {
4530
+ return [];
4531
+ }
4532
+ return [...text4.matchAll(/^[ \t]*path[ \t]*=[ \t]*(.*?)[ \t]*$/gm)].map((m) => m[1].replace(/^"(.*)"$/, "$1").replace(/\/+$/, "")).filter(Boolean);
4533
+ }
4534
+ function carRepos(dir, app, fallback = dir) {
4535
+ const found = appRepos(dir, app);
4536
+ return found.length ? found : [fallback];
4537
+ }
4482
4538
  function checkoutProject(dir) {
4483
4539
  const { file } = appsFile(dir);
4484
4540
  let config;
@@ -6734,6 +6790,10 @@ export {
6734
6790
  openRefusal,
6735
6791
  projectAppsDir,
6736
6792
  repoRoot,
6793
+ appRepos,
6794
+ appLinkPaths,
6795
+ gitmodulesPaths,
6796
+ carRepos,
6737
6797
  checkoutProject,
6738
6798
  TRAIN,
6739
6799
  isSessionRole,
@@ -13,6 +13,7 @@ import {
13
13
  boardPath,
14
14
  boardState,
15
15
  callControl,
16
+ carRepos,
16
17
  carsFolderOk,
17
18
  checkAcceptRef,
18
19
  checkCar,
@@ -88,7 +89,7 @@ import {
88
89
  writeBoard,
89
90
  writeJson,
90
91
  writerAlive
91
- } from "./chunk-GEBLT4XW.mjs";
92
+ } from "./chunk-576U3FLU.mjs";
92
93
 
93
94
  // src/server/cli.ts
94
95
  import { existsSync as existsSync2, realpathSync as realpathSync3 } from "node:fs";
@@ -224,7 +225,7 @@ async function runProcs(ctx, flags, { out, err }) {
224
225
 
225
226
  // src/server/traincmds.ts
226
227
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync as realpathSync2 } from "node:fs";
227
- import { availableParallelism, loadavg, userInfo } from "node:os";
228
+ import { availableParallelism, devNull, loadavg, userInfo } from "node:os";
228
229
  import { dirname as dirname2, join, resolve as resolve3 } from "node:path";
229
230
  var MAX_INPUT = 256 * 1024;
230
231
  var usage = (io, text) => (io.err(`${text}
@@ -285,7 +286,7 @@ function check(flags, io) {
285
286
  if (accept.refusal) refusals.push(accept.refusal);
286
287
  if (slip?.refusal) refusals.push(slip.refusal);
287
288
  if (!setting.ok) refusals.push(setting.refusal);
288
- let required = setting.ok ? setting.accept : [];
289
+ let required = setting.ok ? setting.accept : [], repos = [cwd];
289
290
  if (!accept.refusal && !slip?.refusal && setting.ok) {
290
291
  const app = typeof flags.app === "string" ? flags.app : slip ? parseSlip(slip.text).fields.car : evidenceApp(accept.text);
291
292
  const dir = projectAppsDir(cwd);
@@ -293,20 +294,20 @@ function check(flags, io) {
293
294
  if (app) refusals.push(`sb: app ${app} could not be checked: ${noAppsWhere(cwd)}; run train check in the project's checkout`);
294
295
  } else {
295
296
  const found = app ? readAppIntegration(dir, app) : { ok: false, refusal: "sb: the project has an apps.json, so name the app to check against: --app <name>" };
296
- if (found.ok) required = [.../* @__PURE__ */ new Set([...required, ...found.accept])];
297
+ if (found.ok) required = [.../* @__PURE__ */ new Set([...required, ...found.accept])], repos = carRepos(dir, app, cwd);
297
298
  else refusals.push(found.refusal);
298
299
  }
299
300
  }
300
301
  if (!accept.refusal && !slip?.refusal && setting.ok && !refusals.length) {
301
302
  const exists = io.exists ?? ((path) => existsSync(resolve3(cwd, path)));
302
- const isAncestor = io.isAncestor ?? ((older, newer2) => {
303
+ const isAncestor = io.isAncestor ?? ((older, newer2) => repos.some((at) => {
303
304
  try {
304
- execFileSyncExe("git", ["merge-base", "--is-ancestor", older, newer2], { cwd, stdio: "ignore", timeout: 15e3, killSignal: "SIGKILL" });
305
+ execFileSyncExe("git", ["--no-replace-objects", "-c", "core.commitGraph=false", "merge-base", "--is-ancestor", older, newer2], { cwd: at, stdio: "ignore", timeout: 15e3, killSignal: "SIGKILL", env: { ...process.env, GIT_GRAFT_FILE: devNull } });
305
306
  return true;
306
307
  } catch {
307
308
  return false;
308
309
  }
309
- });
310
+ }));
310
311
  const options = { appAccept: required, exists, isAncestor };
311
312
  refusals.push(...slip ? checkCar(slip.text, accept.text, options) : none ? checkAcceptRef("none", required) : checkEvidence(accept.text, options));
312
313
  }
@@ -40,6 +40,8 @@ import {
40
40
  answers,
41
41
  appCookieFor,
42
42
  appFromRequest,
43
+ appLinkPaths,
44
+ appRepos,
43
45
  applyAcl,
44
46
  asciiJson,
45
47
  awaitAclMarker,
@@ -78,6 +80,7 @@ import {
78
80
  fileOf,
79
81
  findIntercom,
80
82
  forAllies,
83
+ gitmodulesPaths,
81
84
  graphOf,
82
85
  headId,
83
86
  headModel,
@@ -212,7 +215,7 @@ import {
212
215
  writeStartError,
213
216
  writerAlive,
214
217
  yardPath
215
- } from "./chunk-GEBLT4XW.mjs";
218
+ } from "./chunk-576U3FLU.mjs";
216
219
 
217
220
  // src/server/main.ts
218
221
  import { homedir as homedir15 } from "node:os";
@@ -17311,6 +17314,7 @@ function reachClass(line3) {
17311
17314
  if (/Could not resolve host|Connection refused|Connection timed out|timed out|Failed to connect|Network is unreachable|Could not read from remote repository|unable to access|Connection reset|Connection closed/i.test(line3)) return "connection";
17312
17315
  return void 0;
17313
17316
  }
17317
+ var remoteWord = (own) => own === void 0 ? "the project's remote" : `the remote of app ${own.slice(0, 64)}'s repository`;
17314
17318
  var unreached = (text11, line3) => Object.assign(refusal3(text11), { reach: reachClass(line3) });
17315
17319
  var same3 = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
17316
17320
  var MIRROR_FLAGS = ["-c", "core.commitGraph=false", "-c", "fetch.writeCommitGraph=false", "-c", "gc.auto=0", "-c", "maintenance.auto=false", "-c", "core.multiPackIndex=false"];
@@ -17411,8 +17415,10 @@ var CarBook = class {
17411
17415
  bySession = /* @__PURE__ */ new Map();
17412
17416
  forwards = [];
17413
17417
  trains = /* @__PURE__ */ new Map();
17414
- /** The remote the first train of each project was opened on in this server's life: a later open that read another one is not trusted for `landed`. */
17418
+ /** The remote the first train of each project was opened on in this server's life: a later open that read another one is not trusted for `landed`. An app that is a repository of its own has a remote of its own, kept under `<project>/<app>` (a project's name holds no slash), so the two are never compared with each other. */
17415
17419
  remotes = /* @__PURE__ */ new Map();
17420
+ /** The first kind of each app (`<project>/<app>`) at the first open of this server's life that listed it, with the remote read then (R0802-F001, R0802D-F001): own repository (with its remote or null) or the project's. An app that changes kind later is not trusted for `landed`: its remote has no first value to differ from. An app no open listed yet holds none. */
17421
+ kinds = /* @__PURE__ */ new Map();
17416
17422
  /** When each failed `landed` check of a car (project/train/head) happened, within the window. */
17417
17423
  failures = /* @__PURE__ */ new Map();
17418
17424
  chain = Promise.resolve();
@@ -17460,12 +17466,63 @@ var CarBook = class {
17460
17466
  return void 0;
17461
17467
  }
17462
17468
  }
17469
+ /** The first remote `remoteOf` reads in the folders of an app's own repository (`appRepos`: the checkout's, then the main checkout's). */
17470
+ async ownRemote(repos) {
17471
+ for (const repo of repos) {
17472
+ const url = await this.remoteOf(repo);
17473
+ if (url) return url;
17474
+ }
17475
+ return void 0;
17476
+ }
17477
+ /**
17478
+ * Whether the project's own git says `app` is a submodule though no checkout of it is found (R0802-F002: `git submodule deinit`, a clone without `--recurse-submodules`): the app's `dir`, or a folder above it below the root, is a gitlink in the index of `checkout` (mode 160000) or a
17479
+ * `path` of its `.gitmodules`. Such an app's commits are not the project's, and no remote of its own can be read: it is its own repository with no remote, and the project's remote does not stand in.
17480
+ */
17481
+ async gitlink(checkout, app) {
17482
+ const { root, paths } = appLinkPaths(checkout, app);
17483
+ if (!paths.length) return false;
17484
+ const named = new Set(gitmodulesPaths(root));
17485
+ if (paths.some((p) => named.has(p))) return true;
17486
+ for (const path of paths) {
17487
+ try {
17488
+ await this.d.git(root, ["rev-parse", "--verify", "-q", `:0:${path}`]);
17489
+ if ((await this.d.git(root, ["--literal-pathspecs", "ls-files", "-s", "-z", "--", path])).split("\0").some((line3) => line3.startsWith("160000 ") && line3.split(" ")[1] === path)) return true;
17490
+ } catch {
17491
+ }
17492
+ }
17493
+ return false;
17494
+ }
17495
+ /**
17496
+ * The remote of each app of the checkout's apps.json that is a repository of its own (`appRepos`: a git submodule of the project, whose commits are not on the project's remote; R0801-F004): `remote.origin.url` of the app's checkout inside the project's, read the way
17497
+ * `remoteOf` reads the project's, and null when that names none that is safe to fetch from, or when the app is a submodule with no checkout (`gitlink`). An app that is not listed has the project's commits and the project's remote. Read at the open with `remoteOf`, before the train exists.
17498
+ */
17499
+ async appRemotesOf(checkout) {
17500
+ if (!checkout || !isAbsolute7(checkout)) return {};
17501
+ const apps = readApps(checkout), out = [];
17502
+ for (const name2 of new Set(apps.ok ? apps.apps.flatMap((a) => typeof a.name === "string" ? [a.name] : []) : [])) {
17503
+ const repos = appRepos(checkout, name2);
17504
+ if (repos.length) out.push([name2, await this.ownRemote(repos) ?? null]);
17505
+ else if (await this.gitlink(checkout, name2)) out.push([name2, null]);
17506
+ }
17507
+ return Object.fromEntries(out);
17508
+ }
17509
+ /** The names the checkout's apps.json lists (none when it is missing or unreadable). */
17510
+ async appNamesOf(checkout) {
17511
+ if (!checkout || !isAbsolute7(checkout)) return [];
17512
+ const apps = readApps(checkout);
17513
+ return [...new Set(apps.ok ? apps.apps.flatMap((a) => typeof a.name === "string" ? [a.name] : []) : [])];
17514
+ }
17463
17515
  /** A train the tower opened. The first note of a code is kept: a repeated open (the opener's ledger answers it) does not change what was read at the first. */
17464
17516
  noteTrain(t) {
17465
17517
  const key2 = `${t.project}/${t.code}`;
17466
17518
  if (this.trains.has(key2)) return;
17467
17519
  this.trains.set(key2, { ...t, heads: [...new Set(t.heads)].slice(0, 64), at: iso(this.d.now()) });
17468
17520
  if (t.url && !this.remotes.has(t.project)) this.remotes.set(t.project, t.url);
17521
+ for (const app of /* @__PURE__ */ new Set([...t.apps ?? [], ...Object.keys(t.appUrls ?? {})])) {
17522
+ const k = `${t.project}/${app}`;
17523
+ if (!this.kinds.has(k)) this.kinds.set(k, t.appUrls && Object.hasOwn(t.appUrls, app) ? { own: true, url: t.appUrls[app] ?? null } : { own: false, url: null });
17524
+ }
17525
+ for (const [app, url] of Object.entries(t.appUrls ?? {})) if (url && !this.remotes.has(`${t.project}/${app}`)) this.remotes.set(`${t.project}/${app}`, url);
17469
17526
  }
17470
17527
  trainOf(project, code) {
17471
17528
  return this.trains.get(`${project}/${code}`);
@@ -17692,7 +17749,7 @@ var CarBook = class {
17692
17749
  if (receipt.train !== train.code) throw refusal3(`sb: car ${label} was not received for train ${train.code} (the integrator received it for ${String(receipt.train).slice(0, 40)}), so this train does not set it`);
17693
17750
  if (receipt.by.session !== record2.integrator) throw refusal3(`sb: car ${label} was not received by this train's integrator, so this train does not set it`);
17694
17751
  if (state === "dropped" && (!isAbsolute7(String(fields.evidence)) || !this.d.exists(String(fields.evidence)))) throw refusal3(`sb: dropped.evidence ${String(fields.evidence).slice(0, 200)} is not a file that exists (give its absolute path)`);
17695
- if (state === "landed") await this.landed(project, record2, head, String(fields.commit), label);
17752
+ if (state === "landed") await this.landed(project, record2, head, String(fields.commit), label, file2.app);
17696
17753
  }
17697
17754
  let next2;
17698
17755
  try {
@@ -17721,13 +17778,14 @@ var CarBook = class {
17721
17778
  return { state, at: entry.at, file: name2, coordinator: next2.coordinator, ...notice ? { notice } : {}, ...unchecked ? { unchecked } : {} };
17722
17779
  }
17723
17780
  /**
17724
- * A commit is landed when git, run here, finds it on the real remote's branch of the base. The remote is the one the server read from the tower's checkout at the open; the base is the one the manifest named. The tip of that branch is read by `git ls-remote` run
17781
+ * A commit is landed when git, run here, finds it on the real remote's branch of the base. The remote is the one the server read from the tower's checkout at the open, and for a car of an app that is a repository of its own (a submodule of the project) the one it read
17782
+ * from that app's checkout there (`appRemotesOf`, 0.80.2): the app's commits are on no branch of the project's remote. The base is the one the manifest named. The tip of that branch is read by `git ls-remote` run
17725
17783
  * with no repository (cwd the file system's root, no GIT_DIR, a ceiling there), so no repository configuration is read. The fetch goes into a bare repository the server makes for this check alone under its folder (mode 700), with an empty template, and the folder is
17726
17784
  * removed after it, so nothing a train wrote there earlier decides the answer (RR-F001, RR-F004). The fetch must bring exactly that tip, every object is checked as it comes in, and the mirror must hold nothing but what init and fetch wrote: the same config, no alternates,
17727
17785
  * no loose object, packs git wrote (RR2-F001). Not proof against a train that wins a race inside the few seconds of a check, and a refusal does not say it did not: it is the bar, and the refusals are logged. A push the train makes itself to the base counts: the train runs
17728
17786
  * the merge (§3.3). Failed checks of one car are limited (RR2-F001): three in ten minutes close it until the window passes.
17729
17787
  */
17730
- async landed(project, record2, head, commit, label) {
17788
+ async landed(project, record2, head, commit, label, app) {
17731
17789
  const key2 = `${project}/${record2.code}/${head}`, now = this.d.now();
17732
17790
  const failed = (this.failures.get(key2) ?? []).filter((t) => now - t < FAIL_WINDOW_MS);
17733
17791
  this.failures.set(key2, failed);
@@ -17739,39 +17797,47 @@ var CarBook = class {
17739
17797
  throw refusal3(word2);
17740
17798
  }
17741
17799
  try {
17742
- await this.checkLanded(project, record2, commit, label);
17800
+ await this.checkLanded(project, record2, commit, label, app);
17743
17801
  } catch (error) {
17744
17802
  failed.push(now);
17745
17803
  log(error.message, false);
17746
17804
  throw error;
17747
17805
  }
17748
17806
  }
17749
- async checkLanded(project, record2, commit, label) {
17807
+ async checkLanded(project, record2, commit, label, app) {
17750
17808
  const code = record2.code, base = record2.base;
17751
17809
  if (!base || !BASE_RE.test(base) || base.includes("..")) throw refusal3(`sb: the manifest of train ${code} names no usable base (base: <branch>)`);
17752
- if (!record2.url) throw refusal3(`sb: the remote of project ${project} was not read when train ${code} opened (the open names none or none that is safe to fetch from, or this server learned of the train after a restart), so ${label}'s commit cannot be checked`);
17753
- const url = record2.url, first2 = this.remotes.get(project);
17754
- if (first2 !== void 0 && first2 !== url) throw refusal3(`sb: the remote of project ${project} changed between two opens of this server (${blankUser(first2).slice(0, 120)}, then ${blankUser(url).slice(0, 120)}); landed is not checked against a remote that moved`);
17755
- await this.withBase({ project, url, base, key: code, state: "landed" }, async (git, tip) => {
17810
+ const own = record2.appUrls && Object.hasOwn(record2.appUrls, app) ? record2.appUrls[app] : void 0, mine = own !== void 0, of = mine ? `app ${app.slice(0, 64)} of project ${project}` : `project ${project}`;
17811
+ const url = mine ? own ?? void 0 : record2.url, remote = remoteWord(mine ? app : void 0);
17812
+ if (!url) throw refusal3(`sb: the remote of ${of} was not read when train ${code} opened (the open names none or none that is safe to fetch from, or this server learned of the train after a restart), so ${label}'s commit cannot be checked`);
17813
+ const then = this.kinds.get(`${project}/${app}`);
17814
+ if (then && then.own !== mine) {
17815
+ const was = mine ? this.remotes.get(project) : then.url, word2 = (u, its) => `${its ? "its own repository's" : "the project's"}${u ? `, ${blankUser(u).slice(0, 120)}` : ""}`;
17816
+ throw refusal3(`sb: the remote of app ${app.slice(0, 64)} of project ${project} changed between two opens of this server (${word2(was, !mine)}, then ${word2(url, mine)}); landed is not checked against a remote that moved`);
17817
+ }
17818
+ const first2 = this.remotes.get(mine ? `${project}/${app}` : project);
17819
+ if (first2 !== void 0 && first2 !== url) throw refusal3(`sb: the remote of ${of} changed between two opens of this server (${blankUser(first2).slice(0, 120)}, then ${blankUser(url).slice(0, 120)}); landed is not checked against a remote that moved`);
17820
+ await this.withBase({ project, url, base, key: code, state: "landed", remote }, async (git, tip) => {
17756
17821
  try {
17757
17822
  await git("merge-base", "--is-ancestor", commit, tip);
17758
17823
  } catch {
17759
- throw refusal3(`sb: landed.commit ${commit.slice(0, 12)} is not on ${base} of the project's remote: a car has landed only when its commit is on the base's branch there`);
17824
+ throw refusal3(`sb: landed.commit ${commit.slice(0, 12)} is not on ${base} of ${remote}: a car has landed only when its commit is on the base's branch there`);
17760
17825
  }
17761
17826
  });
17762
17827
  }
17763
17828
  /**
17764
17829
  * A car lands once (#15): `received` is refused for a head that git, run here, finds on the base's branch of the project's remote already. Nothing the book remembers is asked, so it holds after a restart, when the book no longer knows that the car landed, and
17765
- * for a head somebody pushed to the base by hand. The remote and the base are read now: the remote of the checkout of the integrator's workspace (where an open reads it) and the app's `integration.base` in that checkout's apps.json. The fetch is the one of
17830
+ * for a head somebody pushed to the base by hand. The remote and the base are read now: the remote of the checkout of the integrator's workspace (where an open reads it), or of the app's own checkout inside it when the app is a repository of its own (a submodule of the
17831
+ * project: its commits are on its own remote, and on the project's remote this check found none of them, so it let a landed car in; R0801-F004, 0.80.2), and the app's `integration.base` in that checkout's apps.json. The fetch is the one of
17766
17832
  * `landed`, into a mirror of its own. When the checkout's remote cannot be read nothing is checked (`cars-received-unchecked` is logged, and the integrator's tool says so): an open reads the remote from the same checkout, so a train of such a project has no remote and
17767
17833
  * cannot set `landed` either. When the remote is read but the app names no usable `integration.base`, `received` is refused (car-forward-F003; the boss's rule that a car is never landed twice wins), and so it is when git fails for any reason but reaching the remote. When
17768
17834
  * `ls-remote` or the fetch fails because the remote cannot be reached or authenticated (the server's git has no credential helper, RR3-F002; repository not found counts), the car is received unchecked with that class as the reason (0.77.2). A head that is not in the base's history is the usual car. A car merged by squash or rebase has no head on the base and is not found here.
17769
17835
  */
17770
17836
  async unlanded(project, app, head, label, look3) {
17771
- const where = await this.baseOf(look3, app);
17837
+ const where = await this.baseOf(look3, app), remote = remoteWord(where.own ? app : void 0);
17772
17838
  if ("unread" in where) {
17773
17839
  this.d.log?.("cars-received-unchecked", { project, car: label.slice(0, 40), reason: "unread" });
17774
- return { unchecked: `the remote of the integrator's workspace checkout could not be read, so whether head ${head.slice(0, 12)} is on the base already was not checked` };
17840
+ return { unchecked: `the remote of ${where.own ? `app ${app.slice(0, 64)}'s own repository in ` : ""}the integrator's workspace checkout could not be read, so whether head ${head.slice(0, 12)} is on the base already was not checked` };
17775
17841
  }
17776
17842
  if ("refused" in where) {
17777
17843
  const word2 = `sb: car ${label} is not received: ${where.refused}, so whether its head ${head.slice(0, 12)} is on the base already cannot be checked. A car that is on the base is never received again: the boss sets integration.base of app ${app}`;
@@ -17781,7 +17847,7 @@ var CarBook = class {
17781
17847
  const { url, base } = where;
17782
17848
  let on;
17783
17849
  try {
17784
- on = await this.withBase({ project, url, base, key: "receipt", state: "received" }, async (git, tip) => {
17850
+ on = await this.withBase({ project, url, base, key: "receipt", state: "received", remote }, async (git, tip) => {
17785
17851
  if (tip === head) return true;
17786
17852
  try {
17787
17853
  await git("cat-file", "-e", `${head}^{commit}`);
@@ -17800,16 +17866,19 @@ var CarBook = class {
17800
17866
  const reach = error.reach;
17801
17867
  if (reach) {
17802
17868
  this.d.log?.("cars-received-unchecked", { project, car: label.slice(0, 40), reason: reach });
17803
- return { unchecked: `the server could not reach the project's remote${hostOf2(url) ? ` at ${hostOf2(url)}` : ""} (${reach}: ${error.message.replace(/^sb: /, "").slice(0, 200)}), so whether head ${head.slice(0, 12)} is on ${base} already was not checked` };
17869
+ return { unchecked: `the server could not reach ${remote}${hostOf2(url) ? ` at ${hostOf2(url)}` : ""} (${reach}: ${error.message.replace(/^sb: /, "").slice(0, 200)}), so whether head ${head.slice(0, 12)} is on ${base} already was not checked` };
17804
17870
  }
17805
- const word2 = `sb: car ${label} is not received: whether its head ${head.slice(0, 12)} is on ${base} of the project's remote already could not be checked (${error.message.replace(/^sb: /, "").slice(0, 300)}). A car that is on the base is never received again, so the check has to run: try again`;
17871
+ const word2 = `sb: car ${label} is not received: whether its head ${head.slice(0, 12)} is on ${base} of ${remote} already could not be checked (${error.message.replace(/^sb: /, "").slice(0, 300)}). A car that is on the base is never received again, so the check has to run: try again`;
17806
17872
  this.d.log?.("cars-received-refused", { project, car: label.slice(0, 40), reason: word2.slice(0, 200) });
17807
17873
  throw refusal3(word2);
17808
17874
  }
17809
- if (on) throw refusal3(landedWord(label, head, `is on ${base} of the project's remote already`));
17875
+ if (on) throw refusal3(landedWord(label, head, `is on ${base} of ${remote} already`));
17810
17876
  return {};
17811
17877
  }
17812
- /** Where a car of `app` lands, read now and from nothing the book holds: the remote of the checkout of the session's workspace (its own folder when the workspace has none) and the app's `integration.base` in that checkout's apps.json. `unread` when the remote cannot be read, `refused` (why) when the remote is read and the base is not there or not usable. */
17878
+ /**
17879
+ * Where a car of `app` lands, read now and from nothing the book holds: the remote of the checkout of the session's workspace (its own folder when the workspace has none) and the app's `integration.base` in that checkout's apps.json. `own` says the app is a repository of its
17880
+ * own there (`appRepos`, or a submodule with no checkout: `gitlink`): the remote is then that of the app's checkout, and never the project's. `unread` when the remote cannot be read, `refused` (why) when the remote is read and the base is not there or not usable.
17881
+ */
17813
17882
  async baseOf(look3, app) {
17814
17883
  let checkout;
17815
17884
  try {
@@ -17818,21 +17887,22 @@ var CarBook = class {
17818
17887
  checkout = void 0;
17819
17888
  }
17820
17889
  checkout ??= look3.cwd;
17821
- const url = await this.remoteOf(checkout);
17822
- if (!checkout || !url) return { unread: true };
17890
+ const repos = checkout && isAbsolute7(checkout) ? appRepos(checkout, app) : [], own = repos.length > 0 || !!checkout && isAbsolute7(checkout) && await this.gitlink(checkout, app);
17891
+ const url = own ? await this.ownRemote(repos) : await this.remoteOf(checkout);
17892
+ if (!checkout || !url) return { own, unread: true };
17823
17893
  const apps = readApps(checkout), entry = apps.ok ? apps.apps.find((a) => a.name === app) : void 0;
17824
- if (!apps.ok) return { refused: "the apps.json of the integrator's workspace checkout cannot be read" };
17825
- if (!entry) return { refused: `the apps.json of the integrator's workspace checkout names no app ${app}` };
17894
+ if (!apps.ok) return { own, refused: "the apps.json of the integrator's workspace checkout cannot be read" };
17895
+ if (!entry) return { own, refused: `the apps.json of the integrator's workspace checkout names no app ${app}` };
17826
17896
  const base = isObject(entry.integration) ? entry.integration.base : void 0;
17827
- if (typeof base !== "string" || !BASE_RE.test(base) || base.includes("..")) return { refused: `app ${app} names no usable integration.base in the apps.json of the integrator's workspace checkout` };
17828
- return { url, base };
17897
+ if (typeof base !== "string" || !BASE_RE.test(base) || base.includes("..")) return { own, refused: `app ${app} names no usable integration.base in the apps.json of the integrator's workspace checkout` };
17898
+ return { own, url, base };
17829
17899
  }
17830
17900
  /**
17831
17901
  * The base's branch of a remote, fetched for one check and removed after it: the steps the comment of `landed` gives, which the check at `received` shares. `answer` gets git in the mirror and the tip `ls-remote` read; the mirror is inspected once more after it
17832
17902
  * answered. `key` names the mirror's one ref, and `state` the state the refusals speak of.
17833
17903
  */
17834
17904
  async withBase(o, answer) {
17835
- const { project, url, base, key: code, state } = o;
17905
+ const { project, url, base, key: code, state, remote } = o;
17836
17906
  let work, mirror = "", hosts = "";
17837
17907
  try {
17838
17908
  mkdirSync12(this.d.dir, { recursive: true, mode: 448 });
@@ -17854,10 +17924,10 @@ var CarBook = class {
17854
17924
  listed2 = await this.d.git(parse3(this.d.dir).root, [...REMOTE_FLAGS, "ls-remote", "--exit-code", "--", url, ref], env);
17855
17925
  } catch (error) {
17856
17926
  const line3 = firstLine(error);
17857
- throw unreached(`sb: git ls-remote of ${base} from the project's remote failed: ${line3}`, line3);
17927
+ throw unreached(`sb: git ls-remote of ${base} from ${remote} failed: ${line3}`, line3);
17858
17928
  }
17859
17929
  const tip = listed2.split("\n").map((l) => l.split(" ")).find(([, name2]) => name2 === ref)?.[0];
17860
- if (!tip || !/^[0-9a-f]{40,64}$/.test(tip)) throw refusal3(`sb: the project's remote lists no branch ${base}`);
17930
+ if (!tip || !/^[0-9a-f]{40,64}$/.test(tip)) throw refusal3(`sb: ${remote} lists no branch ${base}`);
17861
17931
  try {
17862
17932
  await this.d.git(mirror, ["init", "--bare", "-q", "--template=", "."]);
17863
17933
  } catch (error) {
@@ -17874,7 +17944,7 @@ var CarBook = class {
17874
17944
  const moved = mirrorMoved(mirror, fresh.look);
17875
17945
  if (moved.length) throw tampered(moved);
17876
17946
  }
17877
- throw unreached(`sb: git fetch of ${base} from the project's remote failed: ${line3}`, line3);
17947
+ throw unreached(`sb: git fetch of ${base} from ${remote} failed: ${line3}`, line3);
17878
17948
  }
17879
17949
  const fetched = inspectMirror(mirror, code, "fetch", fresh.look);
17880
17950
  if (fetched.problems.length) throw tampered(fetched.problems);
@@ -24293,16 +24363,17 @@ function noteTrains(open8, d) {
24293
24363
  let before;
24294
24364
  if (input.role === "train" && d.cars) {
24295
24365
  try {
24296
- before = { facts: openingFacts(input.request), url: await d.cars.remoteOf(await d.checkout()) };
24366
+ const checkout = await d.checkout();
24367
+ before = { facts: openingFacts(input.request), url: await d.cars.remoteOf(checkout), appUrls: await d.cars.appRemotesOf(checkout), apps: await d.cars.appNamesOf(checkout) };
24297
24368
  } catch (cause) {
24298
24369
  d.error("cars", cause.message);
24299
24370
  }
24300
24371
  }
24301
24372
  const opened = await open8(input);
24302
24373
  if (opened.train && before) {
24303
- const { facts, url } = before;
24374
+ const { facts, url, appUrls, apps } = before;
24304
24375
  try {
24305
- d.cars?.noteTrain({ project: opened.train.project, code: opened.train.code, session: opened.main, pane: opened.pane, integrator: opened.sender, ...facts.base ? { base: facts.base } : {}, heads: facts.heads, ...url && !opened.repeated ? { url } : {} });
24376
+ d.cars?.noteTrain({ project: opened.train.project, code: opened.train.code, session: opened.main, pane: opened.pane, integrator: opened.sender, ...facts.base ? { base: facts.base } : {}, heads: facts.heads, ...url && !opened.repeated ? { url } : {}, ...opened.repeated ? {} : { appUrls, apps } });
24306
24377
  } catch (cause) {
24307
24378
  d.error("cars", cause.message);
24308
24379
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.80.0",
3
+ "version": "0.80.2",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -3,7 +3,7 @@ import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, w
3
3
  import { hostname } from "node:os";
4
4
  import { isAbsolute, join, parse } from "node:path";
5
5
  import { carsDir, trainboardDir } from "../train/board.ts";
6
- import { readApps } from "../train/appsconfig.ts";
6
+ import { appLinkPaths, appRepos, gitmodulesPaths, readApps } from "../train/appsconfig.ts";
7
7
  import { addState, type CarFile, carFileName, type CarState, type CarView, coordinatorWord, emptyCar, endOf, headsIn, landedWord, type NoticeRecord, type Setter, type SlipFacts, slipsInText, type StateEntry, stateLine, type StateNotice, validateStateFields } from "../train/cars.ts";
8
8
  import { isCode, isName, isObject, SHA_RE } from "../train/spec.ts";
9
9
  import { writePrivate } from "../trainboard.ts";
@@ -99,7 +99,7 @@ export interface BookDeps {
99
99
  * A train the tower opened: what the server read from the manifest it was handed (the base and the heads of the cars) and from the tower's checkout (the remote), both before the train's process existed, and the open's own result.
100
100
  * `url` is absent for a train the server only learns of from a repeated open after a restart: the checkout may have been changed by the train since.
101
101
  */
102
- export interface TrainRecord { project: string; code: string; session: string; pane: string; integrator: string; base?: string; heads: string[]; url?: string; at: string }
102
+ export interface TrainRecord { project: string; code: string; session: string; pane: string; integrator: string; base?: string; heads: string[]; url?: string; /** The remote of each app that is a repository of its own (`appRemotesOf`), read with `url`; absent when `url` would be. */ appUrls?: Record<string, string | null>; /** The names the checkout's apps.json listed at that open (R0802D-F001). */ apps?: string[]; at: string }
103
103
  /** A forward the tower's code stamped (runtools.ts): the event it came in, the session that sent it there, the sessions it went to, and the slips it carries as the server read them. */
104
104
  export interface ForwardRecord { fwd: string; from: string; to: string[]; slips: SlipFacts[]; at: number }
105
105
  interface Registration { session: string; pid: number; started: string; pane: string; at: number }
@@ -130,6 +130,8 @@ export function reachClass(line: string): "auth" | "connection" | "repository-no
130
130
  if (/Could not resolve host|Connection refused|Connection timed out|timed out|Failed to connect|Network is unreachable|Could not read from remote repository|unable to access|Connection reset|Connection closed/i.test(line)) return "connection";
131
131
  return undefined;
132
132
  }
133
+ /** The remote a check fetches from, in the refusals' words: the project's, or that of an app that is a repository of its own (a submodule of the project, 0.80.2). */
134
+ const remoteWord = (own: string | undefined) => (own === undefined ? "the project's remote" : `the remote of app ${own.slice(0, 64)}'s repository`);
133
135
  /** A refusal of a remote git could not reach: `reach` names the class. */
134
136
  const unreached = (text: string, line: string) => Object.assign(refusal(text), { reach: reachClass(line) });
135
137
  const same = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
@@ -228,8 +230,10 @@ export class CarBook {
228
230
  private readonly bySession = new Map<string, string>();
229
231
  private forwards: ForwardRecord[] = [];
230
232
  private readonly trains = new Map<string, TrainRecord>();
231
- /** The remote the first train of each project was opened on in this server's life: a later open that read another one is not trusted for `landed`. */
233
+ /** The remote the first train of each project was opened on in this server's life: a later open that read another one is not trusted for `landed`. An app that is a repository of its own has a remote of its own, kept under `<project>/<app>` (a project's name holds no slash), so the two are never compared with each other. */
232
234
  private readonly remotes = new Map<string, string>();
235
+ /** The first kind of each app (`<project>/<app>`) at the first open of this server's life that listed it, with the remote read then (R0802-F001, R0802D-F001): own repository (with its remote or null) or the project's. An app that changes kind later is not trusted for `landed`: its remote has no first value to differ from. An app no open listed yet holds none. */
236
+ private readonly kinds = new Map<string, { own: boolean; url: string | null }>();
233
237
  /** When each failed `landed` check of a car (project/train/head) happened, within the window. */
234
238
  private readonly failures = new Map<string, number[]>();
235
239
  private chain: Promise<unknown> = Promise.resolve();
@@ -271,12 +275,61 @@ export class CarBook {
271
275
  if (!checkout || !isAbsolute(checkout)) return undefined;
272
276
  try { return safeUrl((await this.d.git(checkout, ["config", "--get", "remote.origin.url"])).trim()); } catch { return undefined; }
273
277
  }
278
+ /** The first remote `remoteOf` reads in the folders of an app's own repository (`appRepos`: the checkout's, then the main checkout's). */
279
+ private async ownRemote(repos: readonly string[]): Promise<string | undefined> {
280
+ for (const repo of repos) { const url = await this.remoteOf(repo); if (url) return url; }
281
+ return undefined;
282
+ }
283
+ /**
284
+ * Whether the project's own git says `app` is a submodule though no checkout of it is found (R0802-F002: `git submodule deinit`, a clone without `--recurse-submodules`): the app's `dir`, or a folder above it below the root, is a gitlink in the index of `checkout` (mode 160000) or a
285
+ * `path` of its `.gitmodules`. Such an app's commits are not the project's, and no remote of its own can be read: it is its own repository with no remote, and the project's remote does not stand in.
286
+ */
287
+ private async gitlink(checkout: string, app: string): Promise<boolean> {
288
+ const { root, paths } = appLinkPaths(checkout, app);
289
+ if (!paths.length) return false;
290
+ const named = new Set(gitmodulesPaths(root));
291
+ if (paths.some((p) => named.has(p))) return true;
292
+ for (const path of paths) {
293
+ // An entry of the index at exactly this path (a folder of the project has none), then its mode: one line, whatever the folder holds.
294
+ try {
295
+ await this.d.git(root, ["rev-parse", "--verify", "-q", `:0:${path}`]);
296
+ if ((await this.d.git(root, ["--literal-pathspecs", "ls-files", "-s", "-z", "--", path])).split("\0").some((line) => line.startsWith("160000 ") && line.split("\t")[1] === path)) return true;
297
+ } catch { /* no entry at this path */ }
298
+ }
299
+ return false;
300
+ }
301
+ /**
302
+ * The remote of each app of the checkout's apps.json that is a repository of its own (`appRepos`: a git submodule of the project, whose commits are not on the project's remote; R0801-F004): `remote.origin.url` of the app's checkout inside the project's, read the way
303
+ * `remoteOf` reads the project's, and null when that names none that is safe to fetch from, or when the app is a submodule with no checkout (`gitlink`). An app that is not listed has the project's commits and the project's remote. Read at the open with `remoteOf`, before the train exists.
304
+ */
305
+ async appRemotesOf(checkout: string | undefined): Promise<Record<string, string | null>> {
306
+ if (!checkout || !isAbsolute(checkout)) return {};
307
+ const apps = readApps(checkout), out: [string, string | null][] = [];
308
+ // One git at a time: a project of many submodule apps starts no burst of processes at an open.
309
+ for (const name of new Set(apps.ok ? apps.apps.flatMap((a) => (typeof a.name === "string" ? [a.name] : [])) : [])) {
310
+ const repos = appRepos(checkout, name);
311
+ if (repos.length) out.push([name, (await this.ownRemote(repos)) ?? null]);
312
+ else if (await this.gitlink(checkout, name)) out.push([name, null]);
313
+ }
314
+ return Object.fromEntries(out);
315
+ }
316
+ /** The names the checkout's apps.json lists (none when it is missing or unreadable). */
317
+ async appNamesOf(checkout: string | undefined): Promise<string[]> {
318
+ if (!checkout || !isAbsolute(checkout)) return [];
319
+ const apps = readApps(checkout);
320
+ return [...new Set(apps.ok ? apps.apps.flatMap((a) => (typeof a.name === "string" ? [a.name] : [])) : [])];
321
+ }
274
322
  /** A train the tower opened. The first note of a code is kept: a repeated open (the opener's ledger answers it) does not change what was read at the first. */
275
323
  noteTrain(t: Omit<TrainRecord, "at">): void {
276
324
  const key = `${t.project}/${t.code}`;
277
325
  if (this.trains.has(key)) return;
278
326
  this.trains.set(key, { ...t, heads: [...new Set(t.heads)].slice(0, 64), at: iso(this.d.now()) });
279
327
  if (t.url && !this.remotes.has(t.project)) this.remotes.set(t.project, t.url);
328
+ for (const app of new Set([...(t.apps ?? []), ...Object.keys(t.appUrls ?? {})])) {
329
+ const k = `${t.project}/${app}`;
330
+ if (!this.kinds.has(k)) this.kinds.set(k, t.appUrls && Object.hasOwn(t.appUrls, app) ? { own: true, url: t.appUrls[app] ?? null } : { own: false, url: null });
331
+ }
332
+ for (const [app, url] of Object.entries(t.appUrls ?? {})) if (url && !this.remotes.has(`${t.project}/${app}`)) this.remotes.set(`${t.project}/${app}`, url);
280
333
  }
281
334
  trainOf(project: string, code: string): TrainRecord | undefined { return this.trains.get(`${project}/${code}`); }
282
335
  /**
@@ -502,7 +555,7 @@ export class CarBook {
502
555
  if (receipt.train !== train!.code) throw refusal(`sb: car ${label} was not received for train ${train!.code} (the integrator received it for ${String(receipt.train).slice(0, 40)}), so this train does not set it`);
503
556
  if (receipt.by.session !== record.integrator) throw refusal(`sb: car ${label} was not received by this train's integrator, so this train does not set it`);
504
557
  if (state === "dropped" && (!isAbsolute(String(fields.evidence)) || !this.d.exists(String(fields.evidence)))) throw refusal(`sb: dropped.evidence ${String(fields.evidence).slice(0, 200)} is not a file that exists (give its absolute path)`);
505
- if (state === "landed") await this.landed(project, record, head, String(fields.commit), label);
558
+ if (state === "landed") await this.landed(project, record, head, String(fields.commit), label, file.app);
506
559
  }
507
560
  let next: CarFile;
508
561
  try { next = addState(file, { state, fields, by: setter, at: iso(this.d.now()) }); } catch (error) { throw refusal((error as Error).message); }
@@ -526,13 +579,14 @@ export class CarBook {
526
579
  }
527
580
 
528
581
  /**
529
- * A commit is landed when git, run here, finds it on the real remote's branch of the base. The remote is the one the server read from the tower's checkout at the open; the base is the one the manifest named. The tip of that branch is read by `git ls-remote` run
582
+ * A commit is landed when git, run here, finds it on the real remote's branch of the base. The remote is the one the server read from the tower's checkout at the open, and for a car of an app that is a repository of its own (a submodule of the project) the one it read
583
+ * from that app's checkout there (`appRemotesOf`, 0.80.2): the app's commits are on no branch of the project's remote. The base is the one the manifest named. The tip of that branch is read by `git ls-remote` run
530
584
  * with no repository (cwd the file system's root, no GIT_DIR, a ceiling there), so no repository configuration is read. The fetch goes into a bare repository the server makes for this check alone under its folder (mode 700), with an empty template, and the folder is
531
585
  * removed after it, so nothing a train wrote there earlier decides the answer (RR-F001, RR-F004). The fetch must bring exactly that tip, every object is checked as it comes in, and the mirror must hold nothing but what init and fetch wrote: the same config, no alternates,
532
586
  * no loose object, packs git wrote (RR2-F001). Not proof against a train that wins a race inside the few seconds of a check, and a refusal does not say it did not: it is the bar, and the refusals are logged. A push the train makes itself to the base counts: the train runs
533
587
  * the merge (§3.3). Failed checks of one car are limited (RR2-F001): three in ten minutes close it until the window passes.
534
588
  */
535
- private async landed(project: string, record: TrainRecord, head: string, commit: string, label: string): Promise<void> {
589
+ private async landed(project: string, record: TrainRecord, head: string, commit: string, label: string, app: string): Promise<void> {
536
590
  const key = `${project}/${record.code}/${head}`, now = this.d.now();
537
591
  const failed = (this.failures.get(key) ?? []).filter((t) => now - t < FAIL_WINDOW_MS);
538
592
  this.failures.set(key, failed);
@@ -543,34 +597,44 @@ export class CarBook {
543
597
  log(word, true);
544
598
  throw refusal(word);
545
599
  }
546
- try { await this.checkLanded(project, record, commit, label); } catch (error) {
600
+ try { await this.checkLanded(project, record, commit, label, app); } catch (error) {
547
601
  failed.push(now);
548
602
  log((error as Error).message, false);
549
603
  throw error;
550
604
  }
551
605
  }
552
- private async checkLanded(project: string, record: TrainRecord, commit: string, label: string): Promise<void> {
606
+ private async checkLanded(project: string, record: TrainRecord, commit: string, label: string, app: string): Promise<void> {
553
607
  const code = record.code, base = record.base;
554
608
  if (!base || !BASE_RE.test(base) || base.includes("..")) throw refusal(`sb: the manifest of train ${code} names no usable base (base: <branch>)`);
555
- if (!record.url) throw refusal(`sb: the remote of project ${project} was not read when train ${code} opened (the open names none or none that is safe to fetch from, or this server learned of the train after a restart), so ${label}'s commit cannot be checked`);
556
- const url = record.url, first = this.remotes.get(project);
557
- if (first !== undefined && first !== url) throw refusal(`sb: the remote of project ${project} changed between two opens of this server (${blankUser(first).slice(0, 120)}, then ${blankUser(url).slice(0, 120)}); landed is not checked against a remote that moved`);
558
- await this.withBase({ project, url, base, key: code, state: "landed" }, async (git, tip) => {
559
- try { await git("merge-base", "--is-ancestor", commit, tip); } catch { throw refusal(`sb: landed.commit ${commit.slice(0, 12)} is not on ${base} of the project's remote: a car has landed only when its commit is on the base's branch there`); }
609
+ // The app was a repository of its own when the train opened: its remote is the one read then, and the project's remote is never asked in its place.
610
+ const own = record.appUrls && Object.hasOwn(record.appUrls, app) ? record.appUrls[app] : undefined, mine = own !== undefined, of = mine ? `app ${app.slice(0, 64)} of project ${project}` : `project ${project}`;
611
+ const url = mine ? own ?? undefined : record.url, remote = remoteWord(mine ? app : undefined);
612
+ if (!url) throw refusal(`sb: the remote of ${of} was not read when train ${code} opened (the open names none or none that is safe to fetch from, or this server learned of the train after a restart), so ${label}'s commit cannot be checked`);
613
+ // R0802-F001: the app was the project's at the first open of this server's life and is a repository of its own now, or the other way round: neither remote has a first value of its kind to differ from, so the change itself is the refusal.
614
+ const then = this.kinds.get(`${project}/${app}`);
615
+ if (then && then.own !== mine) {
616
+ const was = mine ? this.remotes.get(project) : then.url, word = (u: string | null | undefined, its: boolean) => `${its ? "its own repository's" : "the project's"}${u ? `, ${blankUser(u).slice(0, 120)}` : ""}`;
617
+ throw refusal(`sb: the remote of app ${app.slice(0, 64)} of project ${project} changed between two opens of this server (${word(was, !mine)}, then ${word(url, mine)}); landed is not checked against a remote that moved`);
618
+ }
619
+ const first = this.remotes.get(mine ? `${project}/${app}` : project);
620
+ if (first !== undefined && first !== url) throw refusal(`sb: the remote of ${of} changed between two opens of this server (${blankUser(first).slice(0, 120)}, then ${blankUser(url).slice(0, 120)}); landed is not checked against a remote that moved`);
621
+ await this.withBase({ project, url, base, key: code, state: "landed", remote }, async (git, tip) => {
622
+ try { await git("merge-base", "--is-ancestor", commit, tip); } catch { throw refusal(`sb: landed.commit ${commit.slice(0, 12)} is not on ${base} of ${remote}: a car has landed only when its commit is on the base's branch there`); }
560
623
  });
561
624
  }
562
625
  /**
563
626
  * A car lands once (#15): `received` is refused for a head that git, run here, finds on the base's branch of the project's remote already. Nothing the book remembers is asked, so it holds after a restart, when the book no longer knows that the car landed, and
564
- * for a head somebody pushed to the base by hand. The remote and the base are read now: the remote of the checkout of the integrator's workspace (where an open reads it) and the app's `integration.base` in that checkout's apps.json. The fetch is the one of
627
+ * for a head somebody pushed to the base by hand. The remote and the base are read now: the remote of the checkout of the integrator's workspace (where an open reads it), or of the app's own checkout inside it when the app is a repository of its own (a submodule of the
628
+ * project: its commits are on its own remote, and on the project's remote this check found none of them, so it let a landed car in; R0801-F004, 0.80.2), and the app's `integration.base` in that checkout's apps.json. The fetch is the one of
565
629
  * `landed`, into a mirror of its own. When the checkout's remote cannot be read nothing is checked (`cars-received-unchecked` is logged, and the integrator's tool says so): an open reads the remote from the same checkout, so a train of such a project has no remote and
566
630
  * cannot set `landed` either. When the remote is read but the app names no usable `integration.base`, `received` is refused (car-forward-F003; the boss's rule that a car is never landed twice wins), and so it is when git fails for any reason but reaching the remote. When
567
631
  * `ls-remote` or the fetch fails because the remote cannot be reached or authenticated (the server's git has no credential helper, RR3-F002; repository not found counts), the car is received unchecked with that class as the reason (0.77.2). A head that is not in the base's history is the usual car. A car merged by squash or rebase has no head on the base and is not found here.
568
632
  */
569
633
  private async unlanded(project: string, app: string, head: string, label: string, look: Look): Promise<{ unchecked?: string }> {
570
- const where = await this.baseOf(look, app);
634
+ const where = await this.baseOf(look, app), remote = remoteWord(where.own ? app : undefined);
571
635
  if ("unread" in where) {
572
636
  this.d.log?.("cars-received-unchecked", { project, car: label.slice(0, 40), reason: "unread" });
573
- return { unchecked: `the remote of the integrator's workspace checkout could not be read, so whether head ${head.slice(0, 12)} is on the base already was not checked` };
637
+ return { unchecked: `the remote of ${where.own ? `app ${app.slice(0, 64)}'s own repository in ` : ""}the integrator's workspace checkout could not be read, so whether head ${head.slice(0, 12)} is on the base already was not checked` };
574
638
  }
575
639
  if ("refused" in where) {
576
640
  const word = `sb: car ${label} is not received: ${where.refused}, so whether its head ${head.slice(0, 12)} is on the base already cannot be checked. A car that is on the base is never received again: the boss sets integration.base of app ${app}`;
@@ -580,7 +644,7 @@ export class CarBook {
580
644
  const { url, base } = where;
581
645
  let on: boolean;
582
646
  try {
583
- on = await this.withBase({ project, url, base, key: "receipt", state: "received" }, async (git, tip) => {
647
+ on = await this.withBase({ project, url, base, key: "receipt", state: "received", remote }, async (git, tip) => {
584
648
  if (tip === head) return true;
585
649
  try { await git("cat-file", "-e", `${head}^{commit}`); } catch { return false; }
586
650
  try { await git("merge-base", "--is-ancestor", head, tip); return true; } catch (error) {
@@ -593,35 +657,40 @@ export class CarBook {
593
657
  const reach = (error as { reach?: string }).reach;
594
658
  if (reach) {
595
659
  this.d.log?.("cars-received-unchecked", { project, car: label.slice(0, 40), reason: reach });
596
- return { unchecked: `the server could not reach the project's remote${hostOf(url) ? ` at ${hostOf(url)}` : ""} (${reach}: ${(error as Error).message.replace(/^sb: /, "").slice(0, 200)}), so whether head ${head.slice(0, 12)} is on ${base} already was not checked` };
660
+ return { unchecked: `the server could not reach ${remote}${hostOf(url) ? ` at ${hostOf(url)}` : ""} (${reach}: ${(error as Error).message.replace(/^sb: /, "").slice(0, 200)}), so whether head ${head.slice(0, 12)} is on ${base} already was not checked` };
597
661
  }
598
- const word = `sb: car ${label} is not received: whether its head ${head.slice(0, 12)} is on ${base} of the project's remote already could not be checked (${(error as Error).message.replace(/^sb: /, "").slice(0, 300)}). A car that is on the base is never received again, so the check has to run: try again`;
662
+ const word = `sb: car ${label} is not received: whether its head ${head.slice(0, 12)} is on ${base} of ${remote} already could not be checked (${(error as Error).message.replace(/^sb: /, "").slice(0, 300)}). A car that is on the base is never received again, so the check has to run: try again`;
599
663
  this.d.log?.("cars-received-refused", { project, car: label.slice(0, 40), reason: word.slice(0, 200) });
600
664
  throw refusal(word);
601
665
  }
602
- if (on) throw refusal(landedWord(label, head, `is on ${base} of the project's remote already`));
666
+ if (on) throw refusal(landedWord(label, head, `is on ${base} of ${remote} already`));
603
667
  return {};
604
668
  }
605
- /** Where a car of `app` lands, read now and from nothing the book holds: the remote of the checkout of the session's workspace (its own folder when the workspace has none) and the app's `integration.base` in that checkout's apps.json. `unread` when the remote cannot be read, `refused` (why) when the remote is read and the base is not there or not usable. */
606
- private async baseOf(look: Look, app: string): Promise<{ url: string; base: string } | { unread: true } | { refused: string }> {
669
+ /**
670
+ * Where a car of `app` lands, read now and from nothing the book holds: the remote of the checkout of the session's workspace (its own folder when the workspace has none) and the app's `integration.base` in that checkout's apps.json. `own` says the app is a repository of its
671
+ * own there (`appRepos`, or a submodule with no checkout: `gitlink`): the remote is then that of the app's checkout, and never the project's. `unread` when the remote cannot be read, `refused` (why) when the remote is read and the base is not there or not usable.
672
+ */
673
+ private async baseOf(look: Look, app: string): Promise<{ own: boolean } & ({ url: string; base: string } | { unread: true } | { refused: string })> {
607
674
  let checkout: string | undefined;
608
675
  try { checkout = await this.d.checkoutOf?.(look); } catch { checkout = undefined; }
609
676
  checkout ??= look.cwd;
610
- const url = await this.remoteOf(checkout);
611
- if (!checkout || !url) return { unread: true };
677
+ // A submodule with no checkout is still a repository of its own, with no remote to read (R0802-F002).
678
+ const repos = checkout && isAbsolute(checkout) ? appRepos(checkout, app) : [], own = repos.length > 0 || (!!checkout && isAbsolute(checkout) && (await this.gitlink(checkout, app)));
679
+ const url = own ? await this.ownRemote(repos) : await this.remoteOf(checkout);
680
+ if (!checkout || !url) return { own, unread: true };
612
681
  const apps = readApps(checkout), entry = apps.ok ? apps.apps.find((a) => a.name === app) : undefined;
613
- if (!apps.ok) return { refused: "the apps.json of the integrator's workspace checkout cannot be read" };
614
- if (!entry) return { refused: `the apps.json of the integrator's workspace checkout names no app ${app}` };
682
+ if (!apps.ok) return { own, refused: "the apps.json of the integrator's workspace checkout cannot be read" };
683
+ if (!entry) return { own, refused: `the apps.json of the integrator's workspace checkout names no app ${app}` };
615
684
  const base = isObject(entry.integration) ? entry.integration.base : undefined;
616
- if (typeof base !== "string" || !BASE_RE.test(base) || base.includes("..")) return { refused: `app ${app} names no usable integration.base in the apps.json of the integrator's workspace checkout` };
617
- return { url, base };
685
+ if (typeof base !== "string" || !BASE_RE.test(base) || base.includes("..")) return { own, refused: `app ${app} names no usable integration.base in the apps.json of the integrator's workspace checkout` };
686
+ return { own, url, base };
618
687
  }
619
688
  /**
620
689
  * The base's branch of a remote, fetched for one check and removed after it: the steps the comment of `landed` gives, which the check at `received` shares. `answer` gets git in the mirror and the tip `ls-remote` read; the mirror is inspected once more after it
621
690
  * answered. `key` names the mirror's one ref, and `state` the state the refusals speak of.
622
691
  */
623
- private async withBase<T>(o: { project: string; url: string; base: string; key: string; state: "landed" | "received" }, answer: (git: (...args: string[]) => Promise<string>, tip: string) => Promise<T>): Promise<T> {
624
- const { project, url, base, key: code, state } = o;
692
+ private async withBase<T>(o: { project: string; url: string; base: string; key: string; state: "landed" | "received"; /** The remote in the refusals' words (`remoteWord`). */ remote: string }, answer: (git: (...args: string[]) => Promise<string>, tip: string) => Promise<T>): Promise<T> {
693
+ const { project, url, base, key: code, state, remote } = o;
625
694
  let work: string | undefined, mirror = "", hosts = "";
626
695
  try {
627
696
  mkdirSync(this.d.dir, { recursive: true, mode: 0o700 });
@@ -640,9 +709,9 @@ export class CarBook {
640
709
  try {
641
710
  // The tip, from no repository: git reads no repository configuration there.
642
711
  let listed: string;
643
- try { listed = await this.d.git(parse(this.d.dir).root, [...REMOTE_FLAGS, "ls-remote", "--exit-code", "--", url, ref], env); } catch (error) { const line = firstLine(error); throw unreached(`sb: git ls-remote of ${base} from the project's remote failed: ${line}`, line); }
712
+ try { listed = await this.d.git(parse(this.d.dir).root, [...REMOTE_FLAGS, "ls-remote", "--exit-code", "--", url, ref], env); } catch (error) { const line = firstLine(error); throw unreached(`sb: git ls-remote of ${base} from ${remote} failed: ${line}`, line); }
644
713
  const tip = listed.split("\n").map((l) => l.split("\t")).find(([, name]) => name === ref)?.[0];
645
- if (!tip || !/^[0-9a-f]{40,64}$/.test(tip)) throw refusal(`sb: the project's remote lists no branch ${base}`);
714
+ if (!tip || !/^[0-9a-f]{40,64}$/.test(tip)) throw refusal(`sb: ${remote} lists no branch ${base}`);
646
715
  try { await this.d.git(mirror, ["init", "--bare", "-q", "--template=", "."]); } catch (error) { throw refusal(`sb: the server's mirror for project ${project} cannot be made: ${firstLine(error)}`); }
647
716
  const inMirror = (...args: string[]) => this.d.git(mirror, ["--git-dir", mirror, ...MIRROR_FLAGS, ...args], env);
648
717
  const fresh = inspectMirror(mirror, code, "init");
@@ -651,7 +720,7 @@ export class CarBook {
651
720
  const line = firstLine(error);
652
721
  // A fetch that failed as unreachable may have been made to fail by a rewritten mirror (an `insteadOf` in its config): that is a tampered mirror, refused, not a remote out of reach (R0772-F001).
653
722
  if (reachClass(line)) { const moved = mirrorMoved(mirror, fresh.look); if (moved.length) throw tampered(moved); }
654
- throw unreached(`sb: git fetch of ${base} from the project's remote failed: ${line}`, line);
723
+ throw unreached(`sb: git fetch of ${base} from ${remote} failed: ${line}`, line);
655
724
  }
656
725
  const fetched = inspectMirror(mirror, code, "fetch", fresh.look);
657
726
  if (fetched.problems.length) throw tampered(fetched.problems);
@@ -113,7 +113,7 @@ export interface TowersOptions {
113
113
  /** The asks the towers made for their mains. */
114
114
  asks?: Asks;
115
115
  /** The car book (carbook.ts): a forward the tower stamps and a train it opens are noted there, for the checks of the server to rest on. */
116
- cars?: Pick<CarBook, "noteForward" | "noteTrain" | "remoteOf">;
116
+ cars?: Pick<CarBook, "noteForward" | "noteTrain" | "remoteOf" | "appRemotesOf" | "appNamesOf">;
117
117
  /** Auto mode (automode.ts): the head's `boss_auto` acts through it. Absent on a secondary server. */
118
118
  auto?: Pick<AutoMode, "view" | "decided" | "bossAuto" | "onSwitch">;
119
119
  /** Hands the service to a test as soon as it is built. */
@@ -1,9 +1,9 @@
1
1
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
2
- import { availableParallelism, loadavg, userInfo } from "node:os";
2
+ import { availableParallelism, devNull, loadavg, userInfo } from "node:os";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { execFileSyncExe } from "../exe.mjs";
5
5
  import { checkAcceptRef, checkCar, checkEvidence, parseAppAccept, parseSlip } from "../train/accept.ts";
6
- import { appsFile, projectAppsDir, readAppIntegration, repoRoot } from "../train/appsconfig.ts";
6
+ import { appsFile, carRepos, projectAppsDir, readAppIntegration, repoRoot } from "../train/appsconfig.ts";
7
7
  import { type Board, boardPath, boardState, MAX_TRAINS, trainboardDir, factsOf, MAX_CLEARS, readBoard, readTrainboards, type Writer, writeBoard } from "../train/board.ts";
8
8
  import { isName, isObject, validateStep } from "../train/spec.ts";
9
9
  import { noticeStatus, stateLine, type Attempt } from "../train/cars.ts";
@@ -26,7 +26,7 @@ export interface TrainIo {
26
26
  now?: () => number;
27
27
  alive?: (writer: Writer) => boolean;
28
28
  user?: string;
29
- /** `git merge-base --is-ancestor` in `cwd`, and whether a file is there: replaced by tests. */
29
+ /** `git merge-base --is-ancestor` in `cwd` (in the app's own repository when the app is a submodule of the project), and whether a file is there: replaced by tests. */
30
30
  isAncestor?: (older: string, newer: string) => boolean;
31
31
  exists?: (path: string) => boolean;
32
32
  load?: () => { now: number; cores: number } | undefined;
@@ -95,7 +95,8 @@ function check(flags: Record<string, string | true>, io: TrainIo): number {
95
95
  // What the app requires is the file's (TB-F001): the project's apps.json, for the app `--app` names, else the slip's `car:` (or `app:`), else the evidence's `car.app`. `--app-accept` can only add to it. The file is this folder's, else
96
96
  // that of the repository's main checkout (a coordinator's linked worktree may have none, and the tower reads the project's). When neither has one, a named app could not be checked, and the check says so instead of ok (0.77.3);
97
97
  // with no app named, the flag alone is checked.
98
- let required: string[] = setting.ok ? setting.accept : [];
98
+ // Where git answers about the car's commits: `cwd`, or the app's own repository when the app is one (a submodule of the project, `carRepos`; 0.80.1).
99
+ let required: string[] = setting.ok ? setting.accept : [], repos = [cwd];
99
100
  if (!accept.refusal && !slip?.refusal && setting.ok) {
100
101
  const app = typeof flags.app === "string" ? flags.app : slip ? parseSlip(slip.text!).fields.car : evidenceApp(accept.text);
101
102
  const dir = projectAppsDir(cwd);
@@ -103,20 +104,21 @@ function check(flags: Record<string, string | true>, io: TrainIo): number {
103
104
  if (app) refusals.push(`sb: app ${app} could not be checked: ${noAppsWhere(cwd)}; run train check in the project's checkout`);
104
105
  } else {
105
106
  const found = app ? readAppIntegration(dir, app) : { ok: false as const, refusal: "sb: the project has an apps.json, so name the app to check against: --app <name>" };
106
- if (found.ok) required = [...new Set([...required, ...found.accept])];
107
+ if (found.ok) (required = [...new Set([...required, ...found.accept])], repos = carRepos(dir, app, cwd));
107
108
  else refusals.push(found.refusal);
108
109
  }
109
110
  }
110
111
  if (!accept.refusal && !slip?.refusal && setting.ok && !refusals.length) {
111
112
  const exists = io.exists ?? ((path: string) => existsSync(resolve(cwd, path)));
112
- const isAncestor = io.isAncestor ?? ((older: string, newer: string) => {
113
+ const isAncestor = io.isAncestor ?? ((older: string, newer: string) => repos.some((at) => {
113
114
  try {
114
- execFileSyncExe("git", ["merge-base", "--is-ancestor", older, newer], { cwd, stdio: "ignore", timeout: 15_000, killSignal: "SIGKILL" });
115
+ // Replace refs off and no graft file, as the guard asks (RD0801-F002, R0802-F003).
116
+ execFileSyncExe("git", ["--no-replace-objects", "-c", "core.commitGraph=false", "merge-base", "--is-ancestor", older, newer], { cwd: at, stdio: "ignore", timeout: 15_000, killSignal: "SIGKILL", env: { ...process.env, GIT_GRAFT_FILE: devNull } });
115
117
  return true;
116
118
  } catch {
117
119
  return false;
118
120
  }
119
- });
121
+ }));
120
122
  const options = { appAccept: required, exists, isAncestor };
121
123
  refusals.push(...(slip ? checkCar(slip.text!, accept.text, options) : none ? checkAcceptRef("none", required) : checkEvidence(accept.text!, options)));
122
124
  }
@@ -1,28 +1,28 @@
1
1
  import type { Opened, OpenRequest } from "../opener.ts";
2
2
  import { type CarBook, openingFacts } from "./carbook.ts";
3
3
 
4
- // What the server reads when the tower opens a train (docs/specs/2026-11-07-train-workers.md §24): the base and the heads of the cars from the manifest the integrator sent, and the project's remote from the tower workspace's checkout. Both are read BEFORE
4
+ // What the server reads when the tower opens a train (docs/specs/2026-11-07-train-workers.md §24): the base and the heads of the cars from the manifest the integrator sent, and the project's remote from the tower workspace's checkout, with the remote of each app there that is a repository of its own (a submodule; 0.80.2). All are read BEFORE
5
5
  // the opener creates the train's tab, so no process of the train can have changed the checkout's configuration yet; they are the only source the `landed` check and a train's right to a car rest on. Nothing is read again later.
6
6
 
7
7
  type Open = (input: OpenRequest) => Promise<Opened>;
8
8
  export interface TrainNoteDeps {
9
- cars: Pick<CarBook, "noteTrain" | "remoteOf"> | undefined;
9
+ cars: Pick<CarBook, "noteTrain" | "remoteOf" | "appRemotesOf" | "appNamesOf"> | undefined;
10
10
  /** The tower workspace's checkout folder, or undefined when it has none. */
11
11
  checkout(): Promise<string | undefined>;
12
12
  error(what: string, message: string): void;
13
13
  }
14
14
 
15
- /** The opener, noting each train it opens in the car book. A repeated open (the opener's ledger answers it) is noted without a remote: the train may have changed the checkout since, and the book keeps the first note of a code. */
15
+ /** The opener, noting each train it opens in the car book. A repeated open (the opener's ledger answers it) is noted without a remote, the project's or an app's: the train may have changed the checkout since, and the book keeps the first note of a code. */
16
16
  export function noteTrains(open: Open, d: TrainNoteDeps): Open {
17
17
  return async (input) => {
18
- let before: { facts: ReturnType<typeof openingFacts>; url: string | undefined } | undefined;
18
+ let before: { facts: ReturnType<typeof openingFacts>; url: string | undefined; appUrls: Record<string, string | null>; apps: string[] } | undefined;
19
19
  if (input.role === "train" && d.cars) {
20
- try { before = { facts: openingFacts(input.request), url: await d.cars.remoteOf(await d.checkout()) }; } catch (cause) { d.error("cars", (cause as Error).message); }
20
+ try { const checkout = await d.checkout(); before = { facts: openingFacts(input.request), url: await d.cars.remoteOf(checkout), appUrls: await d.cars.appRemotesOf(checkout), apps: await d.cars.appNamesOf(checkout) }; } catch (cause) { d.error("cars", (cause as Error).message); }
21
21
  }
22
22
  const opened = await open(input);
23
23
  if (opened.train && before) {
24
- const { facts, url } = before;
25
- try { d.cars?.noteTrain({ project: opened.train.project, code: opened.train.code, session: opened.main, pane: opened.pane, integrator: opened.sender, ...(facts.base ? { base: facts.base } : {}), heads: facts.heads, ...(url && !opened.repeated ? { url } : {}) }); } catch (cause) { d.error("cars", (cause as Error).message); }
24
+ const { facts, url, appUrls, apps } = before;
25
+ try { d.cars?.noteTrain({ project: opened.train.project, code: opened.train.code, session: opened.main, pane: opened.pane, integrator: opened.sender, ...(facts.base ? { base: facts.base } : {}), heads: facts.heads, ...(url && !opened.repeated ? { url } : {}), ...(opened.repeated ? {} : { appUrls, apps }) }); } catch (cause) { d.error("cars", (cause as Error).message); }
26
26
  }
27
27
  return opened;
28
28
  };
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
2
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
3
3
  import { checkStages, parseAppAccept } from "./accept.ts";
4
4
  import { isName, isObject } from "./spec.ts";
5
5
 
@@ -106,6 +106,78 @@ export function repoRoot(dir: string): string {
106
106
  } catch { return real(root); }
107
107
  }
108
108
 
109
+ /** The git dir of the checkout at `root` and the common dir that one names, as real paths: its `.git` when that is a folder, else the git dir its `.git` file names (a linked worktree, a submodule of another repository, `--separate-git-dir`). None when it cannot be read. */
110
+ function gitDirs(root: string): string[] {
111
+ try {
112
+ const dot = join(root, ".git"), named = statSync(dot).isFile() ? /^gitdir:\s*(.+)$/m.exec(readFileSync(dot, "utf8"))![1]!.trim() : dot, gitdir = realpathSync(resolve(root, named));
113
+ return [gitdir, commonOf(gitdir)];
114
+ } catch { return []; }
115
+ }
116
+ /** The common dir of a git dir, as a real path: what its `commondir` file names, else the git dir itself. git reads the objects and refs there. */
117
+ function commonOf(gitdir: string): string {
118
+ const file = join(gitdir, "commondir");
119
+ return existsSync(file) ? realpathSync(resolve(gitdir, readFileSync(file, "utf8").trim())) : gitdir;
120
+ }
121
+
122
+ /**
123
+ * The folders of the repository of `app` when the app is a repository of its own (a git submodule of the project, or a clone inside it), none when its commits are the project's (0.80.1, 0.80.2). They are the nearest folder holding a `.git`, from the app's `dir` of the
124
+ * apps.json of `dir` up to below the root (R0801-F002: an app may be a folder inside a submodule), under the git root of `dir` and under the main checkout of that repository: in a linked worktree of the project the submodule may not be checked out, or keeps objects of
125
+ * its own. No folder outside the project answers (R0801-F001, RD0801-F001, RD0801-F002): the folder is inside the root after realpath; the git dir its `.git` is or names (a folder, a `gitdir:` file, or a symlink to one), and the common dir that one names, are after realpath inside the checkout,
126
+ * the main checkout, or the project's own git dir or common dir (a project that is itself a submodule, or was cloned with `--separate-git-dir`, keeps its submodules' git dirs there and not in its folder). A `.git` that is no git dir (it holds no `HEAD`: git walks past it
127
+ * to the project's) and a git dir whose common dir is the project's own (a linked worktree of the project inside it: its commits and its remote are the project's) answer none (R0802-F004).
128
+ */
129
+ export function appRepos(dir: string, app: string | undefined): string[] {
130
+ const read = readApps(dir), at = read.ok ? read.apps.find((a) => a.name === app)?.dir : undefined;
131
+ if (typeof at !== "string") return [];
132
+ const top = resolve(gitRoot(dir)), home = repoRoot(dir);
133
+ const inside = (path: string, root: string) => path.startsWith(root + sep);
134
+ const own = (root: string): string[] => {
135
+ const folder = resolve(root, at);
136
+ if (!inside(folder, root)) return [];
137
+ try {
138
+ const real = realpathSync(root), mine = gitDirs(top), allowed = [real, home, ...mine], within = (path: string) => allowed.some((a) => path === a || inside(path, a));
139
+ for (let d = realpathSync(folder); inside(d, real); d = dirname(d)) {
140
+ const dot = join(d, ".git"), stat = statSync(dot, { throwIfNoEntry: false });
141
+ if (!stat) continue;
142
+ const named = stat.isDirectory() ? dot : stat.isFile() ? /^gitdir:\s*(.+)$/m.exec(readFileSync(dot, "utf8"))?.[1]?.trim() : undefined;
143
+ if (named === undefined) return [];
144
+ const gitdir = realpathSync(resolve(d, named)), common = commonOf(gitdir);
145
+ if (common === mine[1] || !existsSync(join(gitdir, "HEAD"))) return [];
146
+ return within(gitdir) && within(common) ? [d] : [];
147
+ }
148
+ } catch { /* a folder or a git dir that is not there answers nothing */ }
149
+ return [];
150
+ };
151
+ return [...new Set([...own(top), ...own(home)])];
152
+ }
153
+
154
+ /**
155
+ * Where the project's own git would hold a gitlink for `app` (R0802-F002): the git root of `dir`, and the app's `dir` of its apps.json with every folder above it below that root, as the index names them (relative, with `/`). None when the app names no folder inside the root, or the root itself.
156
+ * A submodule that is not checked out has no `.git` for `appRepos` to find, and the index (mode 160000) and `.gitmodules` still say that the app's commits are not the project's.
157
+ */
158
+ export function appLinkPaths(dir: string, app: string | undefined): { root: string; paths: string[] } {
159
+ const read = readApps(dir), at = read.ok ? read.apps.find((a) => a.name === app)?.dir : undefined, root = resolve(gitRoot(dir)), paths: string[] = [];
160
+ if (typeof at !== "string") return { root, paths };
161
+ for (let d = resolve(root, at); d.startsWith(root + sep); d = dirname(d)) paths.push(relative(root, d).split(sep).join("/"));
162
+ return { root, paths };
163
+ }
164
+ /** The `path` of each submodule the `.gitmodules` of the checkout at `root` names; none when the file is not there or cannot be read. */
165
+ export function gitmodulesPaths(root: string): string[] {
166
+ let text: string;
167
+ try { text = readFileSync(join(root, ".gitmodules"), "utf8"); } catch { return []; }
168
+ return [...text.matchAll(/^[ \t]*path[ \t]*=[ \t]*(.*?)[ \t]*$/gm)].map((m) => m[1]!.replace(/^"(.*)"$/, "$1").replace(/\/+$/, "")).filter(Boolean);
169
+ }
170
+
171
+ /**
172
+ * The folders git is asked in about the commits of a car of `app` (0.80.1): the app's own repository when it is one (`appRepos`), else `fallback`, where git was asked before, because the app's commits are then the project's (its folder holds no `.git` of its own, is the
173
+ * root, or leaves it; no app is named). Whether a delta's `on.head` is an ancestor of the car's head was asked in the project's root, where a submodule's commits do not exist. Which folder answers decides only whether git knows the two commits: a commit's ancestors are
174
+ * fixed by its hash, and the callers ask with replace refs off (`--no-replace-objects`), no graft file (`GIT_GRAFT_FILE` is the null device; R0802-F003) and no commit-graph (`core.commitGraph=false`; R0802D-F002), the three ways a repository can give a commit other parents.
175
+ */
176
+ export function carRepos(dir: string, app: string | undefined, fallback = dir): string[] {
177
+ const found = appRepos(dir, app);
178
+ return found.length ? found : [fallback];
179
+ }
180
+
109
181
  export type CheckoutProject = { ok: true; project: string; /** Where the name is from, in words. */ from: string; file: string } | { ok: false; refusal: string };
110
182
 
111
183
  /**
package/src/trainguard.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
3
- import { availableParallelism, homedir, loadavg } from "node:os";
3
+ import { availableParallelism, devNull, homedir, loadavg } from "node:os";
4
4
  import { isAbsolute, join, resolve } from "node:path";
5
5
  import { execFileSyncExe } from "./exe.mjs";
6
6
  import { startMs, writerAlive } from "./server/traingate.ts";
@@ -9,7 +9,7 @@ import { startOf } from "./startof.ts";
9
9
  import { snapshotOfBranch } from "./todo.ts";
10
10
  import { type Acceptance, acceptanceOf, checkAcceptRef, checkCar, checkEvidence, type EvidenceOptions, parseSlip, slipBlocks } from "./train/accept.ts";
11
11
  import { checkContract, type Contract, type SkillCommand } from "./train/contract.ts";
12
- import { type AppIntegration, readAppIntegration } from "./train/appsconfig.ts";
12
+ import { type AppIntegration, carRepos, readAppIntegration } from "./train/appsconfig.ts";
13
13
  import { type BoardRead, type BoardStep, boardPath, capBoard, type CarRow, factsOf, readBoard, readTrainboards, validateTrainTodo, type Writer, writeBoard, writeYard } from "./train/board.ts";
14
14
  import { type CarView, coordinatorWord, forwardsFor, forwardsOf, noticeSatisfied, receivedTold, type TerminalState } from "./train/cars.ts";
15
15
  import { fieldsOf } from "./headerfields.ts";
@@ -71,7 +71,7 @@ export function manifestText(entries: readonly unknown[]): string | undefined {
71
71
  export { slipBlocks };
72
72
 
73
73
  /** What the manifest check needs besides the text: the app's `integration` from apps.json, and the files and git of the train's own folder. */
74
- export interface ManifestCheck { config(app: string | undefined): AppIntegration; exists(path: string): boolean; isAncestor(older: string, newer: string): boolean }
74
+ export interface ManifestCheck { config(app: string | undefined): AppIntegration; exists(path: string): boolean; /** `app` is the manifest's: git is asked in that app's own repository when it is one (a submodule). */ isAncestor(older: string, newer: string, app?: string): boolean }
75
75
  /** The refusals of a slip against what its app requires (TB-F001): the kinds the evidence lacks, `accept: none` where something is required, and an evidence file that did not read. */
76
76
  const OWED = /^sb: (acceptance evidence lacks |accept: none is allowed only |accept: .* names an evidence file, but it was not read)/;
77
77
 
@@ -87,7 +87,7 @@ export function parseManifest(text: string, read: (path: string) => string | und
87
87
  const owed = config.ok ? (appAccept.length ? refusals.find((r) => OWED.test(r)) : undefined) : config.refusal;
88
88
  const word = asked ?? (owed ? `sb: car ${ticket}: ${owed.replace(/^sb: /, "")}` : undefined);
89
89
  const head = /^[0-9a-f]{40}$/.test(parsed.fields.head ?? "") ? parsed.fields.head! : undefined;
90
- const shown: Acceptance = config.ok ? acceptanceOf(accept ?? "none", evidence, { appAccept, ...(head ? { head } : {}), exists: check.exists, isAncestor: check.isAncestor }) : { unverified: true };
90
+ const shown: Acceptance = config.ok ? acceptanceOf(accept ?? "none", evidence, { appAccept, ...(head ? { head } : {}), exists: check.exists, isAncestor: (older, newer) => check.isAncestor(older, newer, app) }) : { unverified: true };
91
91
  const f = parsed.fields, row: CarRow = { tickets: parsed.tickets, branch: f.branch ?? "", head: head ?? "", coordinator: f.coordinator ?? "", departs: f.departs ?? "next", accept: accept ?? "none", ...shown };
92
92
  cars.push({ ticket, slip, ...(head ? { head } : {}), ...(evidence ? { evidence } : {}), ...(row.tickets.length && row.branch && row.head && row.coordinator ? { row } : {}) });
93
93
  if (word) leftOut.push({ ticket, head: head ?? "", word });
@@ -191,7 +191,7 @@ export interface GuardEnv {
191
191
  node: string; cli: string; home: string;
192
192
  tell(text: string, level?: "info" | "warning" | "error"): void;
193
193
  /** Seams: git, the load, the age of a board's writer, this process's start (tests replace them). */
194
- git?(cwd: string, args: string[]): string;
194
+ git?(cwd: string, args: string[], env?: Record<string, string>): string;
195
195
  load?(): { now: number; cores: number } | undefined;
196
196
  alive?(writer: Writer): boolean;
197
197
  pid?: number;
@@ -204,10 +204,10 @@ export interface GuardEnv {
204
204
  export interface CarSource { read(project: string): Promise<CarView[]> }
205
205
  type Block = { block: true; reason: string } | undefined;
206
206
  const GIT_ENV = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_COMMON_DIR", "GIT_NAMESPACE", "GIT_CONFIG", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_EXEC_PATH"];
207
- const realGit = (cwd: string, args: string[]): string => {
207
+ const realGit = (cwd: string, args: string[], extra: Record<string, string> = {}): string => {
208
208
  const env = { ...process.env };
209
209
  for (const key of GIT_ENV) delete env[key];
210
- return String(execFileSyncExe("git", ["-c", "core.fsmonitor=false", "-C", cwd, ...args], { encoding: "utf8", timeout: 15_000, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"], env })).trim();
210
+ return String(execFileSyncExe("git", ["-c", "core.fsmonitor=false", "-C", cwd, ...args], { encoding: "utf8", timeout: 15_000, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "pipe"], env: { ...env, ...extra } })).trim();
211
211
  };
212
212
  const shortError = (error: unknown) => String((error as { stderr?: unknown }).stderr || (error as Error).message).trim().split("\n")[0]!.slice(0, 200);
213
213
  const STATUS = ["pending", "in_progress", "completed"];
@@ -248,8 +248,8 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
248
248
  return text === undefined ? undefined : (manifest = parseManifest(text, readText(ctx), manifestCheck(ctx)));
249
249
  };
250
250
  const appsDir = (ctx: Ctx) => ctx.cwd ?? process.cwd();
251
- const isAncestorIn = (ctx: Ctx) => (older: string, newer: string): boolean => { try { git(appsDir(ctx), ["merge-base", "--is-ancestor", older, newer]); return true; } catch { return false; } };
252
- const manifestCheck = (ctx: Ctx): ManifestCheck => ({ config: (app) => (app ? readAppIntegration(appsDir(ctx), app) : { ok: false, refusal: "sb: the manifest names no app, so integration.accept of the app is unknown" }), exists: (path) => existsSync(expand(path, ctx)), isAncestor: isAncestorIn(ctx) });
251
+ const isAncestorIn = (ctx: Ctx, app: string | undefined) => (older: string, newer: string): boolean => carRepos(appsDir(ctx), app).some((dir) => { try { git(dir, ["--no-replace-objects", "-c", "core.commitGraph=false", "merge-base", "--is-ancestor", older, newer], { GIT_GRAFT_FILE: devNull }); return true; } catch { return false; } }); // replace refs off (GIT_NO_REPLACE_OBJECTS; RD0801-F002) and no graft file (R0802-F003): neither makes a commit an ancestor in the repository asked
252
+ const manifestCheck = (ctx: Ctx): ManifestCheck => ({ config: (app) => (app ? readAppIntegration(appsDir(ctx), app) : { ok: false, refusal: "sb: the manifest names no app, so integration.accept of the app is unknown" }), exists: (path) => existsSync(expand(path, ctx)), isAncestor: (older, newer, app) => isAncestorIn(ctx, app)(older, newer) });
253
253
  const writer = (): Writer => {
254
254
  const pid = env.pid ?? process.pid, said = startOf(pid), at = said ? startMs(said) : Number.NaN;
255
255
  return { session: env.session().id, ...(env.session().pane ? { pane: env.session().pane } : {}), pid, started: Number.isNaN(at) ? created : new Date(at).toISOString() };
@@ -418,7 +418,7 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
418
418
  if (!refusals.length && isObject(sb) && isObject(sb.spec)) {
419
419
  // What the app requires is read from its apps.json here and in the train's manifest check, never from a flag a model passes (TB-F001); a file that cannot be read refuses (TB-F002 too: stages that list uat).
420
420
  const cars = (sb.spec.cars as CarRow[]) ?? [], config = readAppIntegration(appsDir(ctx), String(sb.app));
421
- refusals.push(...(config.ok ? [...claimedRefusals(cars), ...evidenceRefusals(cars, ctx, config.accept)] : [config.refusal]));
421
+ refusals.push(...(config.ok ? [...claimedRefusals(cars), ...evidenceRefusals(cars, ctx, String(sb.app), config.accept)] : [config.refusal]));
422
422
  }
423
423
  // The manifest goes to the tower only when every car is received, its slip came from the coordinator the tower's forward names, and sb has told that coordinator (§5.5, §7.4).
424
424
  if (!refusals.length && effect.status === "in_progress" && rows.find((r) => r.id === effect.id)?.status !== "in_progress" && isObject(sb) && isObject(sb.spec)) {
@@ -445,13 +445,13 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
445
445
  /** A car's acceptance is what the checked evidence shows; the yard states it from there (TB-F003), so a todo that carries a word of its own about it is refused. */
446
446
  const claimedRefusals = (cars: readonly CarRow[]): string[] => cars.flatMap((car) => (car.accepted !== undefined || car.unverified !== undefined ? [`sb: car ${car.tickets[0]}: accepted is set by Straw Boss from the checked evidence; leave accepted and unverified out of the car`] : []));
447
447
  /** `train check --accept` on each car's evidence, with the kinds the app requires: the evidence is complete for what the file says and for what the app asks, names the car's head, and asks the train for nothing (§5.2, §5.4). */
448
- function evidenceRefusals(cars: readonly CarRow[], ctx: Ctx, appAccept: readonly string[]): string[] {
448
+ function evidenceRefusals(cars: readonly CarRow[], ctx: Ctx, app: string, appAccept: readonly string[]): string[] {
449
449
  const out: string[] = [], read = readText(ctx);
450
450
  for (const car of cars) {
451
451
  if (car.accept.trim().toLowerCase() === "none") { out.push(...checkAcceptRef("none", appAccept).map((r) => `sb: car ${car.tickets[0]}: ${r.replace(/^sb: /, "")}`)); continue; }
452
452
  const text = read(car.accept);
453
453
  if (text === undefined) { out.push(`sb: car ${car.tickets[0]}: cannot read the evidence file ${car.accept}`); continue; }
454
- const options: EvidenceOptions = { appAccept, head: car.head, exists: (path) => existsSync(expand(path, ctx)), isAncestor: isAncestorIn(ctx) };
454
+ const options: EvidenceOptions = { appAccept, head: car.head, exists: (path) => existsSync(expand(path, ctx)), isAncestor: isAncestorIn(ctx, app) };
455
455
  out.push(...checkEvidence(text, options));
456
456
  }
457
457
  return out;
@@ -463,7 +463,7 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
463
463
  if (!configs.has(app)) configs.set(app, readAppIntegration(appsDir(ctx), app));
464
464
  const config = configs.get(app)!;
465
465
  if (!config.ok) return { unverified: true };
466
- return acceptanceOf(car.accept, car.accept.trim().toLowerCase() === "none" ? undefined : read(car.accept), { appAccept: config.accept, head: car.head, exists: (path) => existsSync(expand(path, ctx)), isAncestor: isAncestorIn(ctx) });
466
+ return acceptanceOf(car.accept, car.accept.trim().toLowerCase() === "none" ? undefined : read(car.accept), { appAccept: config.accept, head: car.head, exists: (path) => existsSync(expand(path, ctx)), isAncestor: isAncestorIn(ctx, app) });
467
467
  };
468
468
  }
469
469