clavarium 0.2.409-next.1 → 0.2.411-next.1

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.
@@ -1700,9 +1700,21 @@ OOMScoreAdjust=-900'
1700
1700
  # unreadable; 78 refused before anything ran; 79 the unit did not
1701
1701
  # start or its state is unknown; 80 time limit; 81 memory limit;
1702
1702
  # 82 killed by a signal.
1703
- [ $# -eq 1 ] || usage; is_name "$1" || refuse "not a folder name: $1"
1703
+ #
1704
+ # <name> --tips: the list of branches alone, no pack (deploy/git-read).
1705
+ # <name> --have <id>...: the pack leaves out what those commits reach
1706
+ # (at most 256, each a full object id): the server has it already.
1707
+ [ $# -ge 1 ] || usage; is_name "$1" || refuse "not a folder name: $1"
1704
1708
  case "$1" in *-origin) refuse "the reference of a repository is never read this way: $1" ;; esac
1705
- name="$1"
1709
+ name="$1"; shift
1710
+ how=()
1711
+ if [ $# -eq 1 ] && [ "$1" = "--tips" ]; then how=(--tips)
1712
+ elif [ $# -ge 2 ] && [ $# -le 257 ] && [ "$1" = "--have" ]; then
1713
+ shift
1714
+ for id in "$@"; do [[ "$id" =~ ^[0-9a-f]{40}$ ]] || refuse "not an object id: $id"; done
1715
+ how=(--have "$@")
1716
+ elif [ $# -ne 0 ]; then usage
1717
+ fi
1706
1718
  rand="RANDOM16"
1707
1719
  [ "$SAY" = "yes" ] || rand="$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')"
1708
1720
  unit="clvread-${name}_${rand}"
@@ -1722,7 +1734,7 @@ OOMScoreAdjust=-900'
1722
1734
  -E PATH=/usr/bin -E HOME=/nonexistent -E XDG_CONFIG_HOME=/nonexistent -E LC_ALL=C -E GIT_CONFIG_NOSYSTEM=1
1723
1735
  -E GIT_CONFIG_GLOBAL=/dev/null -E GIT_CEILING_DIRECTORIES=/resources -E GIT_NO_LAZY_FETCH=1
1724
1736
  -E GIT_TERMINAL_PROMPT=0 -E GIT_OPTIONAL_LOCKS=0 -E GIT_NO_REPLACE_OBJECTS=1
1725
- "$GIT_READ" "$name")
1737
+ "$GIT_READ" "$name" "${how[@]}")
1726
1738
  if [ "$SAY" = "yes" ]; then printf '%s\n' "${vector[@]}"; exit 0; fi
1727
1739
  folder_of "$name"
1728
1740
  [ -d "$RUNNER_ROOT" ] && [ ! -L "$RUNNER_ROOT" ] && [ -x "$GIT_READ" ] || refuse "the git reader is not installed (run install.sh again)"
package/deploy/git-read CHANGED
@@ -27,12 +27,37 @@
27
27
  # Every setting the repository could use to run something is overridden on
28
28
  # every git command.
29
29
  #
30
+ # Two more ways, after the same checks (the same refusals, the same list):
31
+ # --tips the header alone: the list of branches, no pack. What
32
+ # To send needs to see which branches moved, at the cost of
33
+ # one for-each-ref.
34
+ # --have <id>... the pack leaves out what those commits reach, for the
35
+ # server has it already (the remote's history, the last
36
+ # read): only what is new travels. A commit the repository
37
+ # does not have is left out of that list, never an error.
38
+ # The header is the same whole list of branches: a branch
39
+ # whose commits did not travel is still listed, and the
40
+ # server checks that it has every object each one needs.
41
+ #
30
42
  # Exit codes: 0; 3 (refs unreadable); 128 only with the 17 bytes of an
31
43
  # empty bundle (no branches); 66 for anything else, with one line on stderr
32
44
  # saying what. git's own codes become 66, so that a code systemd uses for
33
45
  # itself (200-243) can only come from systemd. A git killed by a signal is
34
46
  # killed again here by the same signal, so that the host still sees a signal.
35
47
  NAME="$1"
48
+ MODE="${2:-}"
49
+ case "$MODE" in
50
+ "") [ $# -eq 1 ] || { echo "BAD ARGUMENTS" >&2; exit 66; } ;;
51
+ --tips) [ $# -eq 2 ] || { echo "BAD ARGUMENTS" >&2; exit 66; } ;;
52
+ --have)
53
+ shift 2
54
+ [ $# -ge 1 ] && [ $# -le 256 ] || { echo "BAD ARGUMENTS" >&2; exit 66; }
55
+ for id in "$@"; do
56
+ case "$id" in *[!0-9a-f]*) echo "BAD ARGUMENTS" >&2; exit 66 ;; esac
57
+ [ "${#id}" -eq 40 ] || { echo "BAD ARGUMENTS" >&2; exit 66; }
58
+ done ;;
59
+ *) echo "BAD ARGUMENTS" >&2; exit 66 ;;
60
+ esac
36
61
  [ -d .git ] && [ ! -L .git ] && [ ! -e .git/commondir ] && [ ! -L .git/commondir ] \
37
62
  || { echo "NOT A PLAIN .git DIRECTORY" >&2; exit 66; }
38
63
  for p in .git/refs .git/packed-refs; do
@@ -86,7 +111,15 @@ if [ -z "$refs" ]; then
86
111
  exit 128
87
112
  fi
88
113
  printf '# v2 git bundle\n%s\n\n' "$refs"
89
- printf '%s\n' "$refs" | cut -c1-40 | g pack-objects --stdout --revs --delta-base-offset -q
114
+ [ "$MODE" = "--tips" ] && exit 0
115
+ # The commits to leave out: only those this repository has (a name of
116
+ # another kind, or none, would stop pack-objects). Should this look fail,
117
+ # nothing is left out: the whole pack goes, larger, never wrong.
118
+ have=""
119
+ if [ "$MODE" = "--have" ]; then
120
+ have=$(printf '%s\n' "$@" | g cat-file --batch-check='%(objectname) %(objecttype)' | sed -n 's/^\([0-9a-f]\{40\}\) commit$/^\1/p')
121
+ fi
122
+ { printf '%s\n' "$refs" | cut -c1-40; [ -z "$have" ] || printf '%s\n' "$have"; } | g pack-objects --stdout --revs --delta-base-offset -q
90
123
  rc=$?
91
124
  [ "$rc" -eq 0 ] && exit 0
92
125
  failed "$rc" "GIT COULD NOT PACK THE BRANCHES"
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.409-next.1",
3
+ "version": "0.2.411-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.409-next.1",
9
+ "version": "0.2.411-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.409-next.1",
3
+ "version": "0.2.411-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -420,7 +420,8 @@ export class GitKeeper {
420
420
  const message = failure.message ?? 'The repository could not be read.';
421
421
  const kind = failure.kind ?? 'error';
422
422
  const record = this.#record(name);
423
- const count = (record.readFailures ?? 0) + 1;
423
+ /* A read refused because another one runs ("busy") is no failure of the repository: it counts for nothing. */
424
+ const count = kind === 'busy' ? (record.readFailures ?? 0) : (record.readFailures ?? 0) + 1;
424
425
  /* The same failure as the last read's: the same kind, and the same
425
426
  words unless the words carry a number that moves at every read. */
426
427
  const same = record.lastRead?.ok === false && record.lastRead.kind === kind && (VARYING.has(kind) || record.lastRead.what === message);
@@ -434,7 +435,8 @@ export class GitKeeper {
434
435
  else if (count === 2) this.#tell(`${name}: could not be read`, message);
435
436
  /* The agent is told where it can act; a git failure, or refs that may
436
437
  only have been changing during the read, only after two in a row. */
437
- if (failure.ai && (!['git', 'refs'].includes(kind) || count >= 2)) this.#toAgent(name, failure.ai);
438
+ /* Two in a row OF THAT KIND: refs caught changing once, after a failure of another kind, are not "broken". */
439
+ if (failure.ai && (!['git', 'refs'].includes(kind) || (count >= 2 && record.lastRead?.ok === false && record.lastRead.kind === kind))) this.#toAgent(name, failure.ai);
438
440
  }
439
441
 
440
442
  #refreshOutcome(name, result) {
@@ -78,6 +78,8 @@ export class GitReview {
78
78
  #store; #vault; #resources; #local; #access; #runner; #now; #listeners = []; #waivers = () => ({});
79
79
  /* The refresh of each repository on its way: { run, waitMs }, by name. */
80
80
  #refreshing = new Map();
81
+ /* The last review of each branch, by repository: see #verdict. */
82
+ #verdicts = new Map();
81
83
 
82
84
  /* `localRemotes`: lets a remote be a directory of this machine. For tests only.
83
85
  `runner`: the git runner (gitrunner.mjs); its reads go through the host program. */
@@ -140,7 +142,7 @@ export class GitReview {
140
142
  }
141
143
 
142
144
  /* The repository is gone: its key goes with it. */
143
- forget(name) { this.#store.remove(name); this.#access.forget(name); }
145
+ forget(name) { this.#store.remove(name); this.#access.forget(name); this.#verdicts.delete(name); this.#runner.forget?.(name); }
144
146
 
145
147
  /* ---------- the tips of the agent's branches, as the server last saw them ---------- */
146
148
 
@@ -401,38 +403,90 @@ export class GitReview {
401
403
  return { fresh, ...read };
402
404
  }
403
405
 
404
- /* TO SEND, A WHOLE REPOSITORY AT ONCE: one fetch (shared with any on
405
- its way), ONE read of the agent's repository, then each of its
406
- branches that moved last (up to 1 + `more`) compared in that same
407
- workspace. The page asked one review per branch before, and each
408
- read the whole repository again through the host program: the read
409
- of the whole history, checked object by object, is what takes time,
410
- not the comparison. { state: 'read' | 'empty' | 'unreachable',
411
- message, remote, agentBranches, dropped, rows: [as outgoing()], more,
412
- asOf }; `more`: how many branches were not looked at. A branch whose
413
- comparison failed is a row { state: 'error', branch, message }. */
414
- async outgoingAll(name, { more = BRANCHES_MORE } = {}) {
406
+ /* TO SEND, A WHOLE REPOSITORY, LIGHTLY: NOTHING ASKED OF THE REMOTE
407
+ (the keeper's clock keeps the reference up to date; `fetch: true`, or
408
+ a reference never made, fetches first) and the agent's branches first
409
+ LISTED ONLY (`git read --tips`: no pack). A branch whose tip and whose
410
+ remote tip are both those of its last review here gets that review
411
+ again at once. Only when one moved (or was never looked at) is the
412
+ repository read -- partially: only what is new travels (gitrunner.mjs)
413
+ -- and those branches compared again. Up to 1 + `more` branches, the
414
+ one that moved last first. { state: 'read' | 'empty' | 'unreachable',
415
+ message, remote, fetchedAt, agentBranches, dropped, rows: [as
416
+ outgoing()], more, asOf, checked }; `more`: how many branches were
417
+ not looked at; `checked`: how many were compared again; `fetchedAt`:
418
+ when the reference was last brought up to date (the page says "as
419
+ of"). A branch whose comparison failed is a row { state: 'error',
420
+ branch, message }. */
421
+ async outgoingAll(name, { more = BRANCHES_MORE, fetch = false } = {}) {
415
422
  const r = this.#repository(name);
416
423
  const remote = this.#remoteOf(r) ?? null;
417
- const base = { remote, agentBranches: [], dropped: [], rows: [], more: 0, asOf: this.#now().toISOString() };
418
- const { fresh, got, error } = await this.#refreshAndRead(r, remote);
419
- if (fresh && !fresh.ok) return { ...base, state: 'unreachable', message: `The remote did not answer as expected: ${fresh.message}` };
420
- if (error) {
421
- if (error instanceof GitFailure && error.kind === 'empty') return { ...base, state: 'empty', message: 'Nothing has been committed on a branch in this repository yet.' };
424
+ const base = { remote, agentBranches: [], dropped: [], rows: [], more: 0, checked: 0, asOf: this.#now().toISOString() };
425
+ if (remote && (fetch || !this.#resources.hasOrigin(r.name))) {
426
+ const fresh = await this.refresh(r.name, { waitMs: REVIEW_WAIT_MS });
427
+ if (!fresh.ok) return { ...base, fetchedAt: this.#record(r.name).fetchedAt ?? null, state: 'unreachable', message: `The remote did not answer as expected: ${fresh.message}` };
428
+ }
429
+ base.fetchedAt = this.#record(r.name).fetchedAt ?? null;
430
+ const empty = { ...base, state: 'empty', message: 'Nothing has been committed on a branch in this repository yet.' };
431
+ let listed;
432
+ try { listed = this.#listed(r, await this.#tipsRead(r)); } catch (error) {
433
+ if (error instanceof GitFailure && error.kind === 'empty') return empty;
422
434
  throw error;
423
435
  }
436
+ const count = 1 + Math.max(0, Math.floor(Number(more) || 0));
437
+ const remoteTips = remote && this.#resources.hasOrigin(r.name) ? await this.#tipsIn(this.#reference(r.name)) : new Map();
438
+ const kept = this.#verdicts.get(r.name);
439
+ /* Its last review still holds: the same agent tip, the same remote, the same remote tip. */
440
+ const still = (b) => {
441
+ const v = kept?.get(b.name);
442
+ return v && v.head === b.id && v.remote === remote && (v.remoteTip ?? null) === (remoteTips.get(v.target) ?? null) ? v : null;
443
+ };
444
+ let chosen = listed.agentBranches.slice(0, count);
445
+ let got = null;
424
446
  try {
425
- const listed = this.#listed(r, got);
447
+ if (chosen.some((b) => !still(b))) {
448
+ try { got = await this.#read(r); } catch (error) {
449
+ if (error instanceof GitFailure && error.kind === 'empty') return empty;
450
+ throw error;
451
+ }
452
+ /* What the read found is what counts: a branch may have moved again since the list. */
453
+ listed = this.#listed(r, got);
454
+ chosen = listed.agentBranches.slice(0, count);
455
+ }
426
456
  if (listed.agentBranches.length === 0) return { ...base, ...listed, state: 'empty', message: 'No branch of this repository can be sent: see the names that were not taken.' };
427
- const chosen = listed.agentBranches.slice(0, 1 + Math.max(0, Math.floor(Number(more) || 0)));
428
- const rows = [];
457
+ const rows = []; let checked = 0;
429
458
  for (const b of chosen) {
459
+ const v = still(b);
460
+ if (v) { rows.push(this.#again(r.name, v, listed, remoteTips)); continue; }
461
+ checked += 1;
430
462
  try { rows.push(await this.#look(r, got, listed, b, undefined)); } catch (error) {
431
463
  rows.push({ ...nothingOut(remote), state: 'error', branch: b.name, target: b.name, kind: error?.kind ?? null, message: error instanceof Refusal ? error.message : 'It could not be read.' });
432
464
  }
433
465
  }
434
- return { ...base, ...listed, state: 'read', message: '', rows, more: listed.agentBranches.length - chosen.length, asOf: this.#now().toISOString() };
435
- } finally { got.remove(); }
466
+ return { ...base, ...listed, state: 'read', message: '', rows, checked, more: listed.agentBranches.length - chosen.length, asOf: this.#now().toISOString() };
467
+ } finally { got?.remove(); }
468
+ }
469
+
470
+ /* The agent's branches LISTED ONLY, through the host program's sandbox
471
+ (gitrunner.mjs tips()): told and recorded like any read. */
472
+ async #tipsRead(r) {
473
+ try {
474
+ const got = await this.#runner.tips(r.name);
475
+ this.#saw(r.name, got.branches);
476
+ this.#tell('read', r.name, null, got);
477
+ return got;
478
+ } catch (error) {
479
+ this.#tell('read', r.name, error);
480
+ if (error instanceof GitFailure && error.kind === 'empty') this.#saw(r.name, []);
481
+ throw error;
482
+ }
483
+ }
484
+
485
+ /* A review given again (its tips unchanged): the lists around it as they
486
+ are now, and its review kept again for Send, as when it was made. */
487
+ #again(name, v, { agentBranches, dropped }, remoteTips) {
488
+ if (v.state === 'ahead') this.#keep(name, { branch: v.branch, head: v.head, target: v.target, remoteTip: v.remoteTip, count: v.count ?? undefined, confirm: v.guards?.confirm, at: v.asOf });
489
+ return { ...v, agentBranches, dropped, branches: v.remote ? [...remoteTips.keys()].sort().slice(0, BRANCHES_MAX) : v.branches };
436
490
  }
437
491
 
438
492
  /* WHAT IS KNOWN HERE, AT ONCE: no remote asked, no repository read. The
@@ -477,6 +531,15 @@ export class GitReview {
477
531
  return { agentBranches, dropped: got.dropped.map((d) => ({ name: escaped(d.name), why: d.why })) };
478
532
  }
479
533
 
534
+ /* EVERY REVIEW MADE, by repository and branch, in memory: what To send
535
+ gives again while neither tip moved (outgoingAll). Only the last one
536
+ of a branch (one per branch, a few branches per repository). */
537
+ #verdict(name, out) {
538
+ if (!this.#verdicts.has(name)) this.#verdicts.set(name, new Map());
539
+ this.#verdicts.get(name).set(out.branch, out);
540
+ return out;
541
+ }
542
+
480
543
  /* The outcome of a review, kept by branch for the list shown at once (known()). */
481
544
  #remember(name, out, agentBranches) {
482
545
  const record = this.#record(name);
@@ -497,7 +560,7 @@ export class GitReview {
497
560
  const base0 = { agentBranches, dropped, branch: chosen.name, target: to, head, remote, asOf };
498
561
  if (!remote) {
499
562
  const shown = await this.#compare(ws, { head, base: EMPTY_TREE, range: [head], negatives: [] });
500
- return { ...nothing, ...base0, ...shown, state: 'no-remote', message: 'No address is set to send these commits to.' };
563
+ return this.#verdict(r.name, { ...nothing, ...base0, ...shown, state: 'no-remote', message: 'No address is set to send these commits to.' });
501
564
  }
502
565
  const reference = this.#reference(r.name);
503
566
  const release = await this.#runner.lock(reference, REVIEW_WAIT_MS);
@@ -539,7 +602,7 @@ export class GitReview {
539
602
  if (state === 'ahead') this.#keep(r.name, { branch: chosen.name, head, target: to, remoteTip, count: n ?? undefined, confirm: shown.guards.confirm, at: asOf });
540
603
  const out = { ...nothing, ...base0, ...shown, branches, targetExists: Boolean(remoteTip), remoteTip, state, message };
541
604
  this.#remember(r.name, out, agentBranches);
542
- return out;
605
+ return this.#verdict(r.name, out);
543
606
  } finally { release(); }
544
607
  }
545
608
 
@@ -8,8 +8,10 @@
8
8
  * server would obey all of it. So:
9
9
  *
10
10
  * 1. the host program reads the folder in a throw-away sandbox (`git read`,
11
- * see deploy/clavarium-host and deploy/git-read) and writes ONE FULL
12
- * BUNDLE of its branches to stdout;
11
+ * see deploy/clavarium-host and deploy/git-read) and writes ONE BUNDLE
12
+ * of its branches to stdout -- whole, or without what this server
13
+ * already has and checked (a partial read, see read()), or the list of
14
+ * branches alone (tips());
13
15
  * 2. this file treats those bytes as hostile: every byte counted against a
14
16
  * cap, the header parsed here on Buffers before any git sees it, the
15
17
  * pack checked object by object (`index-pack --strict`) into an EMPTY,
@@ -26,7 +28,7 @@
26
28
  * agent (or the owner) go after `--end-of-options`, or on stdin.
27
29
  */
28
30
  import { spawn } from 'node:child_process';
29
- import { mkdirSync, rmSync, statfsSync, writeFileSync, existsSync, readdirSync, lstatSync, unlinkSync } from 'node:fs';
31
+ import { mkdirSync, rmSync, statfsSync, writeFileSync, existsSync, readdirSync, lstatSync, unlinkSync, readFileSync, renameSync, linkSync, copyFileSync } from 'node:fs';
30
32
  import { randomBytes } from 'node:crypto';
31
33
  import { join } from 'node:path';
32
34
  import { Refusal } from './conversations.mjs';
@@ -45,6 +47,15 @@ export const READ_BRANCHES_MAX = 1000;
45
47
  export const READ_DEADLINE_MS = 360_000;
46
48
  export const HOST_READS = 2;
47
49
  export const BRANCH_MAX = 200;
50
+ /* A list-only read (`git read <name> --tips`): its time limit, and the most bytes it may print. */
51
+ export const TIPS_DEADLINE_MS = 60_000;
52
+ /* A partial read: at most so many commits said to be had already (the host
53
+ program takes no more), and so many packs kept before a whole read again. */
54
+ export const HAVES_MAX = 256;
55
+ export const KEPT_PACKS_MAX = 16;
56
+ /* A partial read that failed in its pack or its checks is made again whole:
57
+ what was had may be gone (the reference packed again, a history rewritten). */
58
+ const AGAIN_WHOLE = new Set(['incomplete', 'fsck', 'header', 'connect', 'workspace']);
48
59
  /* What `git bundle create` writes for a repository with no branch. */
49
60
  export const EMPTY_BUNDLE = '# v2 git bundle\n\n';
50
61
  /* The fsck messages an owner may waive, for old histories made by old
@@ -312,7 +323,7 @@ export class GitRunner {
312
323
  fixed byte cap, for tests. */
313
324
  constructor({ dataDir, host = [], reserveBytes = RESERVE, readDeadlineMs = READ_DEADLINE_MS, spawnRead, git = runGit, cap } = {}) {
314
325
  this.#dataDir = dataDir; this.#host = host; this.#reserve = reserveBytes; this.#deadline = readDeadlineMs; this.#git = git; this.#cap = cap;
315
- this.#spawnRead = spawnRead ?? ((name) => spawn(this.#host[0], [...this.#host.slice(1), 'git', 'read', name], { stdio: ['ignore', 'pipe', 'pipe'] }));
326
+ this.#spawnRead = spawnRead ?? ((name, how = []) => spawn(this.#host[0], [...this.#host.slice(1), 'git', 'read', name, ...how], { stdio: ['ignore', 'pipe', 'pipe'] }));
316
327
  /* What is left from before is nobody's now: a workspace outlives its
317
328
  use only if this server stopped in the middle of one. The copies an
318
329
  earlier version kept (git-review/) go too. */
@@ -323,6 +334,15 @@ export class GitRunner {
323
334
  }
324
335
 
325
336
  get workRoot() { return `${this.#dataDir}/git-work`; }
337
+ /* WHAT IS KEPT OF THE LAST READ of a repository: its packs (each one
338
+ checked object by object when it came, by index-pack --strict) and the
339
+ tips it held, so that the next read asks only for what is new. Ours
340
+ alone, like a workspace: never the agent's, never the reference. A
341
+ workspace gets its own links to these files, so that a newer read
342
+ replacing them never takes objects from under a review going on. */
343
+ keptDir(name) { return `${this.#dataDir}/git-kept/${name}`; }
344
+ /* The repository is gone: what was kept of it goes too. */
345
+ forget(name) { rmSync(this.keptDir(name), { recursive: true, force: true }); }
326
346
  /* An empty place for HOME: git and ssh find nothing there. */
327
347
  get home() { return `${this.#dataDir}/git-home`; }
328
348
 
@@ -398,24 +418,42 @@ export class GitRunner {
398
418
  `reference`: the remote's history, for the cap only (never borrowed
399
419
  here). `waivers`: the owner's fsck waivers. One read per repository
400
420
  at a time, two on the host. */
401
- read(name, { reference, waivers } = {}) {
421
+ /* `partial` (the default): only what is new since the last read, and
422
+ what the reference does not have, travels -- see #haves. `got.partial`
423
+ says whether it did. */
424
+ read(name, { reference, waivers, partial = true } = {}) {
425
+ return this.#queued(name, () => this.#read(name, reference, waivers, partial));
426
+ }
427
+ /* One host read of a repository at a time, whatever kind: the host program refuses a second one as busy. */
428
+ #queued(name, work) {
402
429
  const before = this.#queues.get(name) ?? Promise.resolve();
403
- const run = before.then(() => this.#read(name, reference, waivers), () => this.#read(name, reference, waivers));
430
+ const run = before.then(work, work);
404
431
  const tail = run.catch(() => {});
405
432
  this.#queues.set(name, tail);
406
433
  void tail.then(() => { if (this.#queues.get(name) === tail) this.#queues.delete(name); });
407
434
  return run;
408
435
  }
409
436
 
410
- async #read(name, reference, waivers) {
437
+ async #read(name, reference, waivers, partial) {
411
438
  const release = await this.#slots.take();
412
439
  let ws;
413
440
  try {
414
441
  const cap = this.#cap ?? capFor(await this.sizeOf(reference));
415
442
  const free = this.freeBytes();
416
443
  if (free < 2 * cap + this.#reserve) throw new GitFailure(507, 'space', `Not read: ${Math.floor(free / MiB)} MB free on the server, ${Math.ceil((2 * cap + this.#reserve) / MiB)} MB needed.`, { alert: true });
444
+ const checks = strictOption(waivers);
445
+ const haves = partial ? await this.#haves(name, reference, checks) : { ids: [], packs: [] };
417
446
  ws = await this.workspace();
418
- const got = await this.#receive(name, ws.path, cap, waivers);
447
+ let got = null;
448
+ if (haves.ids.length > 0) {
449
+ try { got = { ...await this.#partial(name, ws.path, reference, haves, cap, waivers), partial: true }; } catch (error) {
450
+ if (!(error instanceof GitFailure) || !AGAIN_WHOLE.has(error.kind)) throw error;
451
+ ws.remove();
452
+ ws = await this.workspace();
453
+ }
454
+ }
455
+ if (!got) got = { ...await this.#receive(name, ws.path, cap, waivers), partial: false };
456
+ this.#keep(name, ws.path, got.branches, checks);
419
457
  return { ...got, path: ws.path, remove: ws.remove };
420
458
  } catch (error) {
421
459
  ws?.remove();
@@ -423,14 +461,110 @@ export class GitRunner {
423
461
  } finally { release(); }
424
462
  }
425
463
 
426
- #receive(name, ws, cap, waivers) {
464
+ /* What the next read may leave out: the tips of the last read (kept,
465
+ read under the same fsck waivers, not too many packs), then the
466
+ reference's tips. { ids, packs }: `packs` the kept files to link. */
467
+ async #haves(name, reference, checks) {
468
+ const ids = []; let packs = [];
469
+ try {
470
+ const dir = this.keptDir(name);
471
+ const kept = JSON.parse(readFileSync(join(dir, 'tips.json'), 'utf8'));
472
+ const files = readdirSync(dir).filter((f) => /^pack-[0-9a-f]{40,64}\.(pack|idx|rev)$/.test(f));
473
+ if (kept?.checks === checks && Array.isArray(kept.ids) && files.filter((f) => f.endsWith('.pack')).length <= KEPT_PACKS_MAX) {
474
+ packs = files.map((f) => join(dir, f));
475
+ for (const id of kept.ids) if (isId(id)) ids.push(id);
476
+ }
477
+ } catch { /* nothing kept: the reference alone */ }
478
+ if (reference && existsSync(join(reference, 'objects'))) {
479
+ const r = await this.in(reference, ['for-each-ref', '--format=%(objectname)', 'refs/heads/'], { deadlineMs: 60_000 });
480
+ if (r.code === 0) for (const id of r.stdout.toString('latin1').split('\n')) if (isId(id)) ids.push(id);
481
+ }
482
+ return { ids: [...new Set(ids)].slice(0, HAVES_MAX), packs };
483
+ }
484
+
485
+ /* A PARTIAL READ: the kept packs linked into the workspace and the
486
+ reference lent to it BEFORE the pack comes, for index-pack --strict to
487
+ find every object the new ones point to -- it refuses a pack whose
488
+ links lead nowhere. Then every branch, moved or not, is walked to its
489
+ roots: a tip that did not travel must be whole here too, or the read
490
+ is made again whole. */
491
+ async #partial(name, ws, reference, haves, cap, waivers) {
492
+ for (const file of haves.packs) {
493
+ const to = join(ws, 'objects', 'pack', file.slice(file.lastIndexOf('/') + 1));
494
+ try { linkSync(file, to); } catch { copyFileSync(file, to); }
495
+ }
496
+ if (reference) this.borrow(ws, reference);
497
+ const got = await this.#receive(name, ws, cap, waivers, ['--have', ...haves.ids]);
498
+ if (got.branches.length > 0) {
499
+ const walked = await this.in(ws, ['rev-list', '--objects', '--quiet', '--stdin', '--end-of-options'], { input: got.branches.map((b) => `${b.id}\n`).join(''), deadlineMs: 120_000 });
500
+ if (walked.code !== 0 || walked.killed || walked.signal) throw new GitFailure(422, 'connect', 'The repository could not be read safely: a branch lacks objects here.');
501
+ }
502
+ return got;
503
+ }
504
+
505
+ /* After a read: its packs, and its tips, are what the next one may leave
506
+ out. Put in place whole or not at all; a failure here only makes the
507
+ next read whole. */
508
+ #keep(name, ws, branches, checks) {
509
+ const dir = this.keptDir(name);
510
+ try {
511
+ const fresh = `${dir}.new`; const old = `${dir}.old`;
512
+ rmSync(fresh, { recursive: true, force: true }); rmSync(old, { recursive: true, force: true });
513
+ mkdirSync(fresh, { recursive: true, mode: 0o700 });
514
+ const packDir = join(ws, 'objects', 'pack');
515
+ for (const f of readdirSync(packDir).filter((x) => /^pack-[0-9a-f]{40,64}\.(pack|idx|rev)$/.test(x))) {
516
+ try { linkSync(join(packDir, f), join(fresh, f)); } catch { copyFileSync(join(packDir, f), join(fresh, f)); }
517
+ }
518
+ writeFileSync(join(fresh, 'tips.json'), JSON.stringify({ ids: [...new Set(branches.map((b) => b.id))], checks }));
519
+ if (existsSync(dir)) renameSync(dir, old);
520
+ renameSync(fresh, dir);
521
+ rmSync(old, { recursive: true, force: true });
522
+ } catch { rmSync(dir, { recursive: true, force: true }); }
523
+ }
524
+
525
+ /* THE BRANCHES ALONE (`git read <name> --tips`): the same sandbox, the
526
+ same checks and refusals as a read, and only its header -- no pack, no
527
+ workspace. Resolves { branches: [{name, id}], dropped }. */
528
+ tips(name) {
529
+ return this.#queued(name, () => new Promise((resolve, reject) => {
530
+ const header = new HeaderReader();
531
+ let parsed = null; let failure = null; let bytes = 0; let errText = ''; let after = false;
532
+ const reader = this.#spawnRead(name, ['--tips']);
533
+ const fail = (f) => {
534
+ if (failure) return;
535
+ failure = f;
536
+ reader.stdout.destroy();
537
+ try { reader.kill('SIGTERM'); } catch { /* the host stops it */ }
538
+ void this.stopReads(name);
539
+ };
540
+ const timer = setTimeout(() => fail(new GitFailure(504, 'deadline', `Reading stopped: the server's time limit (${Math.round(TIPS_DEADLINE_MS / 1000)} s).`)), TIPS_DEADLINE_MS);
541
+ reader.stdout.on('data', (chunk) => {
542
+ if (failure) return;
543
+ bytes += chunk.length;
544
+ if (parsed) { after = true; return; }
545
+ try { parsed = header.push(chunk) ?? null; if (parsed?.rest.length) after = true; } catch (error) { fail(error instanceof GitFailure ? error : refused('it could not be parsed')); }
546
+ });
547
+ reader.stderr.on('data', (d) => { errText = (errText + d.toString('latin1')).slice(-4096); });
548
+ reader.on('error', () => fail(new GitFailure(502, 'host', 'The host program could not be started.', { alert: true })));
549
+ reader.on('close', (code) => {
550
+ clearTimeout(timer);
551
+ if (failure) return reject(failure);
552
+ if (code !== 0) return reject(hostFailure(code, errText, bytes));
553
+ /* Nothing after the list: a list-only read that sends a pack is not the reader. */
554
+ if (!parsed || after) return reject(refused('the list of branches is not as expected'));
555
+ resolve({ branches: parsed.refs, dropped: parsed.dropped });
556
+ });
557
+ }));
558
+ }
559
+
560
+ #receive(name, ws, cap, waivers, how = []) {
427
561
  return new Promise((resolve, reject) => {
428
562
  const deadline = Date.now() + this.#deadline;
429
563
  const header = new HeaderReader();
430
564
  let parsed; let bytes = 0; let failure = null; let packStarted = false; let first = Buffer.alloc(0);
431
565
  let indexer; let indexed; let readerClosed = false;
432
566
  let errText = '';
433
- const reader = this.#spawnRead(name);
567
+ const reader = this.#spawnRead(name, how);
434
568
  let settled = false;
435
569
  const settle = (error, value) => { if (settled) return; settled = true; clearTimeout(timer); if (error) reject(error); else resolve(value); };
436
570
  /* Given up: the bytes stop being taken (the git in the sandbox
package/web/app.js CHANGED
@@ -4527,7 +4527,7 @@
4527
4527
  /* By repositories: how many there are is known from the start, how many branches each has is not. */
4528
4528
  meter.hidden = !reading; meterFill.style.width = `${names.length ? Math.round((reposDone / names.length) * 100) : 100}%`;
4529
4529
  progress.toggleAttribute('data-busy', reading);
4530
- if (reading) { progress.dataset.tone = 'warn'; progress.textContent = `Checking with the remotes: ${reposDone} of ${names.length}`; }
4530
+ if (reading) { progress.dataset.tone = 'warn'; progress.textContent = `Checking: ${reposDone} of ${names.length}`; }
4531
4531
  else {
4532
4532
  const failed = rows.filter((r) => unread(r.out)).length;
4533
4533
  const notLooked = [...notLookedBy.values()].reduce((n, x) => n + x, 0);
@@ -4575,7 +4575,8 @@
4575
4575
  row.classList.toggle('off', !ahead);
4576
4576
  const tick = el('input'); tick.type = 'checkbox'; tick.checked = r.picked; tick.disabled = !ahead || r.known || sending || checking; tick.setAttribute('aria-label', `Send ${label(r)}`);
4577
4577
  tick.addEventListener('change', () => { r.picked = tick.checked; sure = ''; paint(); if (!review.hidden) paintReview(); });
4578
- const who = el('div', 'ts-who'); who.append(el('b', '', r.name), el('small', 'hint', `${out?.remote ? hostOf(out.remote) : out ? 'no remote' : ''}${r.known ? ` · ${asOfText(r.asOf)}` : ''}`));
4578
+ /* The remote is not asked when the page opens (the server's clock keeps it): how old what is known of it is, said. */
4579
+ const who = el('div', 'ts-who'); who.append(el('b', '', r.name), el('small', 'hint', `${out?.remote ? hostOf(out.remote) : out ? 'no remote' : ''}${r.known ? ` · ${asOfText(r.asOf)}` : out?.remote && r.fetchedAt ? ` · remote ${asOfText(r.fetchedAt)}` : ''}`));
4579
4580
  const way = el('div', 'ts-way');
4580
4581
  /* Its own name even when it could not be read: which branch is missing is said. */
4581
4582
  const named = out?.branch ?? (unread(out) ? r.branch : '');
@@ -4785,7 +4786,7 @@
4785
4786
  paint();
4786
4787
  said.scrollIntoView({ block: 'nearest' });
4787
4788
  });
4788
- /* ONE REPOSITORY READ AFRESH (one fetch, one read, its branches that moved last reviewed): its rows replaced
4789
+ /* ONE REPOSITORY READ AFRESH (its branches listed; only those that moved read and reviewed again, no fetch): its rows replaced
4789
4790
  where they were, each keeping what was said or ticked of the same commit. A branch with nothing to send is
4790
4791
  listed only when it is the one that moved last (or what became of its sending is said); one that could not be
4791
4792
  read always, with why. */
@@ -4797,7 +4798,7 @@
4797
4798
  if (Array.isArray(all.rows) && all.rows.length) {
4798
4799
  fresh = all.rows.filter((out, i) => i === 0 || out.state === 'ahead' || unread(out) || before.some((x) => x.branch === out.branch && x.sent)).map((out) => {
4799
4800
  const was = before.find((x) => x.branch === out.branch);
4800
- const r = { name, out: null, keep, branch: out.branch, target: '', picked: false, check: null, sent: was?.sent ?? null, movedAt: (all.agentBranches ?? []).find((b) => b.name === out.branch)?.movedAt ?? null };
4801
+ const r = { name, out: null, keep, branch: out.branch, target: '', picked: false, check: null, sent: was?.sent ?? null, movedAt: (all.agentBranches ?? []).find((b) => b.name === out.branch)?.movedAt ?? null, fetchedAt: all.fetchedAt ?? null };
4801
4802
  apply(r, out, keep);
4802
4803
  /* Ticked by one rule for every row: a branch of the remote to update is ticked; a new one is not. */
4803
4804
  r.picked = was && !was.known && was.out?.head === out.head ? was.picked && out.state === 'ahead' : kindOfRow(out) === 'update';
@@ -4829,7 +4830,7 @@
4829
4830
  }
4830
4831
  }
4831
4832
  paint();
4832
- /* THEN, IN THE BACKGROUND: each repository brought up to date with its remote and read, a few at a time; its rows replaced as it comes. */
4833
+ /* THEN, IN THE BACKGROUND: each repository's branches listed, those that moved read again, a few at a time; its rows replaced as it comes. */
4833
4834
  await inTurns(names, TS_PARALLEL, async (name) => {
4834
4835
  try { await readRepo(name); } catch { /* said by its rows */ }
4835
4836
  reposDone++; paint();