@osdlc/repo-cleaner 0.24.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # @osdlc/repo-cleaner
2
2
 
3
+ ## 0.26.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f75dee2: A worktree whose commits ahead could not be counted, because the base does not resolve (a remote never fetched, say) or its HEAD does not (its branch deleted), is no longer read as having none. `evidence.aheadUnknown` is set, the row carries `abandon-unmerged` and is held for review, and its reason names what did not resolve, such as `commits ahead of origin/main not known: origin/main does not resolve`.
8
+ - b120464: A worktree whose directory is gone, and whose HEAD no local branch, tag or remote-tracking branch holds (a detached worktree with its own commits, or one whose branch was deleted), is no longer pruned by default. Its prune would leave those commits unreachable, so the row is `review` with `abandon-unmerged`, and `evidence.headOnRef` says what was found; a HEAD git cannot place is held the same way. A gone worktree on a branch that still exists, or at a commit a ref holds, is pruned as before.
9
+
10
+ ### Patch Changes
11
+
12
+ - 93e864e: The reason of a worktree that holds work leaves out counts of zero and says one and many properly: `1 commit ahead of origin/main` instead of `0 dirty file(s), 1 commit(s) ahead of origin/main`. Submodules with unpushed work read the same way: `submodule sub (1 stash) holds work no remote has`, `unpushed work in submodules a (…), b (…)`.
13
+ - Updated dependencies [3b7fc6b]
14
+ - @osdlc/typed-git@0.22.1
15
+
16
+ ## 0.25.0
17
+
18
+ ### Minor Changes
19
+
20
+ - 3f34046: Export `startMs`, which reads a process start time as `ps -o lstart` prints it, and `PS_LSTART_ENV`, the environment to run that `ps` under.
21
+ - 8be1132: `archiveCandidates` pushes one archive of a repository's candidates, and `removeCandidate` takes its answer as `archived` in place of pushing an archive per candidate. A worktree that changes after an archive that had nothing to hold is no longer removed. `mayContribute` no longer counts a worktree whose directory is gone, so `run --archive` does not refuse one for a repository with no remote.
22
+
23
+ ### Patch Changes
24
+
25
+ - 28799e2: `holders` works out a process's working folders once per process, not once per root it is checked against.
26
+ - ac231ce: `defaultProcessProbe().holders(path)` now counts a process whose working directory was removed, which Linux's `lsof` lists as `<path> (deleted)`, as working in `path` while nothing is at `path` again.
27
+ - Updated dependencies [0b3fbfa]
28
+ - @osdlc/cli-tool@0.22.0
29
+
3
30
  ## 0.24.1
4
31
 
5
32
  ### Patch Changes
package/README.md CHANGED
@@ -576,7 +576,13 @@ A **verdict** is what the sweep concluded about a row:
576
576
  | `keep` | Structural (the default branch, the current checkout, the primary worktree), or in use (an open pull request) | Never deletes a structural row; deletes one in use only when picked and `confirm-open-pr` is allowed |
577
577
 
578
578
  The report shows `prune` for a `delete` row whose worktree directory is
579
- already gone: only the stale record goes.
579
+ already gone: only the stale record goes. The record holds the worktree's
580
+ HEAD, so one on a branch that still exists, or at a commit a local branch, a
581
+ tag or a remote-tracking branch holds, is a `delete`. A detached one with its
582
+ own commits, or one whose branch was deleted, would leave its HEAD on no ref:
583
+ its prune is a `review` that carries `abandon-unmerged`, and
584
+ `evidence.headOnRef` is `false`. One whose HEAD git cannot place (`null`) is
585
+ held the same way.
580
586
 
581
587
  A **risk** is what deleting a row would lose. Each row lists its risks, and
582
588
  you approve them by name with `--allow`:
@@ -705,7 +711,12 @@ Everything else is held back. A branch that is neither merged nor an ancestor
705
711
  is `review` with the reasons spelled out, not a guess. A worktree
706
712
  holding uncommitted or unpushed work is never proposed for removal whatever
707
713
  else is true of it — losing an hour of someone's work costs more than any
708
- amount of clutter.
714
+ amount of clutter. A worktree's commits are counted against its upstream, else
715
+ `<remote>/<default>`; when that does not resolve (a remote never fetched), or
716
+ the worktree's HEAD does not (its branch deleted), the count is not known,
717
+ which is not none: `evidence.aheadUnknown` is set, the reason names what did
718
+ not resolve, and the row carries `abandon-unmerged`. Untracked files count whatever
719
+ `status.showUntrackedFiles` says, since `git worktree remove` deletes them.
709
720
 
710
721
  A clean worktree whose HEAD is merged by ancestry alone, with no merged PR
711
722
  or patch match, needs one more sign, because a worktree that `git worktree
@@ -913,6 +924,9 @@ process table once per probe and reuses it for every worktree: `sweep` makes
913
924
  one probe per repository, and `run` uses one probe for its re-sweep and
914
925
  reads the table afresh for each pre-unlock and pre-remove check. Where the
915
926
  table cannot be read the worktree is held back as `process-probe-failed`. A
927
+ process whose working directory was removed, which Linux's `lsof` lists as
928
+ `<path> (deleted)`, still counts as working in `<path>` while nothing is at
929
+ `<path>` again; a gone path is matched through the links above it. A
916
930
  host or test supplies its own probe.
917
931
  Nothing is ever killed.
918
932
 
@@ -1239,12 +1253,17 @@ const receipt = run(preview)
1239
1253
  | `run(preview, opts?)` | Sweep once more and take the preview's steps, writing a `Receipt` (to `receiptPath` after every step, when given). `onNotes` hears what its own re-check judged without. Each worktree it removes is measured with `du` first, into the step's `freedBytes` |
1240
1254
  | `inspectWorktree(path, opts?)` | One worktree judged as a sweep judges it, submodules included |
1241
1255
  | `candidatesOf(sweep)` | The sweep's deletable or objecting rows as plain data (`CleanCandidate`): id, kind, path, evidence, fingerprint, `requires`, blockers, risks |
1242
- | `removeCandidate(candidate, opts?)` | Delete one candidate as `run` takes one row: archive first with `archive`, the live-process and unsafe-force checks, the removal, its verification. Returns a `CandidateRemoval` (`ok`, `steps`, `error`, and `archiveFailed` for a failed archive push, which a host should treat as fatal). Never throws for a refused or failed delete |
1256
+ | `removeCandidate(candidate, opts?)` | Delete one candidate as `run` takes one row: archive first with `archive`, the live-process and unsafe-force checks, the removal, its verification. Returns a `CandidateRemoval` (`ok`, `steps`, `error`, and `archiveFailed` for a failed archive push, which a host should treat as fatal). With `archived`, an `archiveCandidates` answer, nothing is pushed, and a candidate whose unlanded work it does not hold as it is now is refused. Never throws for a refused or failed delete |
1257
+ | `archiveCandidates(candidates, opts)` | Push one archive of the unlanded work of one repository's candidates, as `run` does, and check the remote has it. Returns a `CandidateArchive`; throws when it cannot be made. Deletes nothing |
1258
+ | `archiveProblem(candidate, archived)` | Why a candidate may not be deleted on that archive, or null when it may |
1259
+ | `mayContribute(candidate)` | True when a candidate holds work an archive could hold; never a worktree whose directory is gone |
1260
+ | `noRemote(repo)` | The refusal of an archive for a repository with no remote |
1243
1261
  | `readPlan`, `writePlan`, `PlanSchema` | Plans on disk |
1244
1262
  | `fingerprint`, `sameFingerprint` | The evidence a row rests on and the rule that compares two of them |
1245
1263
  | `writeJsonAtomic`, `busyHolders` | The atomic JSON write the receipt uses; the holders of a worktree that are not idle shells |
1246
1264
  | `render` | The command line's formats: `text`, `json`, `summary`, `commands`, `preview`, `receipt` |
1247
1265
  | `defaultProcessProbe`, `providers` | The defaults a host can wrap or replace |
1266
+ | `startMs`, `PS_LSTART_ENV` | A process start time as `ps -o lstart` prints it, in epoch milliseconds (NaN for other text), and the environment to run that `ps` under so it prints UTC in English |
1248
1267
  | `RepoCleanerError` | Every refusal, with a `code`: `conflict`, `bad-input`, `not-found`, `ambiguous`, `spared-changed`, `bad-plan` |
1249
1268
 
1250
1269
  A row is a `WorktreeRow`, `BranchRow` or `RemoteRow`, told apart by `kind`:
@@ -1303,7 +1322,9 @@ host re-checks a candidate by sweeping again and comparing `fingerprint` with
1303
1322
  `sameFingerprint`, and turns `blockers` and `risks` into its own objections. It
1304
1323
  deletes what a branch `requires` (its worktree) first. `removeCandidate` keeps the safety model of
1305
1324
  `run`: a risk not in `allow` is refused, and with `archive` the push is made
1306
- and verified before the delete, one archive per candidate.
1325
+ and verified before the delete, one archive per candidate. To push one archive
1326
+ per repository, before the host deletes anything, pass its candidates to
1327
+ `archiveCandidates`, then its answer to each `removeCandidate` as `archived`.
1307
1328
 
1308
1329
  ## Providers (prototype)
1309
1330
 
package/dist/archive.d.ts CHANGED
@@ -56,8 +56,16 @@ export interface Coverage {
56
56
  * @param git The client for reading a worktree's files; unused for a branch.
57
57
  */
58
58
  export declare function coverageOf(row: Row, opts: ArchiveOptions, git: (path: string) => Git): Coverage;
59
- /** True when a row could put something in an archive. */
60
- export declare function mayContribute(row: Row): boolean;
59
+ /**
60
+ * True when a row, or the candidate of one, could put something in an archive:
61
+ * it risks `abandon-unmerged` or `discard-changes`, and is not a worktree whose
62
+ * directory is gone, of which {@link pushArchive} holds nothing.
63
+ */
64
+ export declare function mayContribute(row: {
65
+ kind: string;
66
+ risks: readonly string[];
67
+ evidence: object;
68
+ }): boolean;
61
69
  /** One row's work in an archive. */
62
70
  export interface ArchiveRowJob {
63
71
  id: RowId;
@@ -73,7 +81,7 @@ export interface ArchiveRowJob {
73
81
  export declare function worktreeStamp(git: Git, opts: ArchiveOptions, files: boolean): string;
74
82
  /**
75
83
  * Build the archive of `jobs` and push it, then confirm the remote has it.
76
- * Returns null when there was nothing to hold, else the receipt record and each archived worktree's {@link worktreeStamp}.
84
+ * Returns the receipt record, null when there was nothing to hold, and the {@link worktreeStamp} of each worktree on disk.
77
85
  *
78
86
  * @param git The client at the repository's root.
79
87
  * @param defaultRef The remote default branch, `<remote>/<branch>`.
@@ -82,6 +90,6 @@ export declare function worktreeStamp(git: Git, opts: ArchiveOptions, files: boo
82
90
  * list the archive afterwards. Nothing has been deleted.
83
91
  */
84
92
  export declare function pushArchive(git: Git, remote: string, defaultRef: string, jobs: readonly ArchiveRowJob[], opts: ArchiveOptions, now: Date): {
85
- record: ArchiveRecord;
93
+ record: ArchiveRecord | null;
86
94
  stamps: Map<RowId, string>;
87
- } | null;
95
+ };
package/dist/archive.js CHANGED
@@ -89,8 +89,15 @@ export function coverageOf(row, opts, git) {
89
89
  }
90
90
  return { covers, leftOut };
91
91
  }
92
- /** True when a row could put something in an archive. */
92
+ /**
93
+ * True when a row, or the candidate of one, could put something in an archive:
94
+ * it risks `abandon-unmerged` or `discard-changes`, and is not a worktree whose
95
+ * directory is gone, of which {@link pushArchive} holds nothing.
96
+ */
93
97
  export function mayContribute(row) {
98
+ if (row.kind === 'worktree' && row.evidence.onDisk === false) {
99
+ return false;
100
+ }
94
101
  return row.risks.includes('abandon-unmerged') || row.risks.includes('discard-changes');
95
102
  }
96
103
  /** The tree of the worktree's files as a snapshot holds them, built in a temporary index. */
@@ -113,26 +120,29 @@ function snapshotTree(git, leftOut) {
113
120
  * archive is not deleted on the strength of an archive that lacks it.
114
121
  */
115
122
  export function worktreeStamp(git, opts, files) {
116
- const tree = files ? snapshotTree(git, snapshotLeftOut(git, opts)) : '';
117
- return `${git.resolveRef('HEAD') ?? ''}:${tree}`;
123
+ const head = git.resolveRef('HEAD');
124
+ return stampOf(head, files && head !== null ? snapshotTree(git, snapshotLeftOut(git, opts)) : null);
118
125
  }
126
+ const stampOf = (head, tree) => `${head ?? ''}:${tree ?? ''}`;
119
127
  /**
120
128
  * Commit the worktree `git` is at, uncommitted files included, without
121
129
  * touching its index or files. `sha` is null when nothing differs from HEAD;
122
130
  * `unheld` is true when something is dirty that a snapshot cannot hold, such
123
- * as a staged change the working file has since been reverted from.
131
+ * as a staged change the working file has since been reverted from; `stamp` is
132
+ * the {@link worktreeStamp} of what was committed.
124
133
  */
125
134
  function snapshot(git, opts) {
126
135
  const head = git.resolveRef('HEAD');
127
136
  if (head === null)
128
- return { sha: null, leftOut: [], unheld: false };
137
+ return { sha: null, leftOut: [], unheld: false, stamp: stampOf(null, null) };
129
138
  const leftOut = snapshotLeftOut(git, opts);
130
139
  const tree = snapshotTree(git, leftOut);
140
+ const stamp = stampOf(head, tree);
131
141
  if (tree === git.resolveRef('HEAD^{tree}')) {
132
- return { sha: null, leftOut, unheld: git.statusEntries().length > leftOut.length };
142
+ return { sha: null, leftOut, unheld: git.statusEntries().length > leftOut.length, stamp };
133
143
  }
134
144
  const sha = git.commitTree(tree, { parents: [head], message: `snapshot of ${git.cwd}\n\nuncommitted files on top of ${head}` }, { env: identityEnv(git) });
135
- return { sha, leftOut, unheld: false };
145
+ return { sha, leftOut, unheld: false, stamp };
136
146
  }
137
147
  /** `<repo>-local-<YYYY-MM-DD>`, the branch name after `archive/`. */
138
148
  function branchBase(root, now) {
@@ -152,7 +162,7 @@ function identityEnv(git) {
152
162
  }
153
163
  /**
154
164
  * Build the archive of `jobs` and push it, then confirm the remote has it.
155
- * Returns null when there was nothing to hold, else the receipt record and each archived worktree's {@link worktreeStamp}.
165
+ * Returns the receipt record, null when there was nothing to hold, and the {@link worktreeStamp} of each worktree on disk.
156
166
  *
157
167
  * @param git The client at the repository's root.
158
168
  * @param defaultRef The remote default branch, `<remote>/<branch>`.
@@ -177,6 +187,7 @@ export function pushArchive(git, remote, defaultRef, jobs, opts, now) {
177
187
  was.source += `, ${source}`;
178
188
  }
179
189
  };
190
+ const stamps = new Map();
180
191
  for (const { row, discardAllowed } of jobs) {
181
192
  if (row.kind !== 'worktree') {
182
193
  if (row.risks.includes('abandon-unmerged'))
@@ -191,25 +202,21 @@ export function pushArchive(git, remote, defaultRef, jobs, opts, now) {
191
202
  if ((snap.leftOut.length > 0 || snap.unheld) && !discardAllowed) {
192
203
  throw new Error(`refused: ${row.name} has changes the archive cannot hold (${snap.leftOut.map((f) => f.path).join(', ') || 'staged changes the files no longer show'}); allow discard-changes for it`);
193
204
  }
205
+ // The stamp of the very tree that was committed, so a file written since is a change.
206
+ stamps.set(row.id, snap.stamp);
194
207
  if (snap.sha !== null) {
195
208
  hold(snap.sha, row.id, row.id, snap.leftOut);
196
209
  continue;
197
210
  }
198
211
  }
212
+ else
213
+ stamps.set(row.id, worktreeStamp(at, opts, false));
199
214
  const head = row.risks.includes('abandon-unmerged') ? at.resolveRef('HEAD') : null;
200
215
  if (head !== null)
201
216
  hold(head, row.id, row.id);
202
217
  }
203
218
  if (held.size === 0)
204
- return null;
205
- const stamps = new Map(jobs.flatMap(({ row }) => row.kind === 'worktree' && row.evidence.onDisk !== false
206
- ? [
207
- [
208
- row.id,
209
- worktreeStamp(git.at(row.name), opts, row.risks.includes('discard-changes')),
210
- ],
211
- ]
212
- : []));
219
+ return { record: null, stamps };
213
220
  const parents = [...held.values()];
214
221
  const lines = [
215
222
  `repo-cleaner archive of local work, ${now.toISOString()}`,
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A sweep's rows as plain data for a host that runs its own phases (a
3
- * `git` plugin of host-cleaner): what could be deleted, what would object,
3
+ * `git` plugin of workstation-cleaner): what could be deleted, what would object,
4
4
  * and what it depends on. `removeCandidate` (in `clean.ts`) takes one back.
5
5
  */
6
6
  import { type Action, type Blocker, type Kind, type Risk, type Row, type RowId, type Sweep, type Verdict } from './types.ts';
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A sweep's rows as plain data for a host that runs its own phases (a
3
- * `git` plugin of host-cleaner): what could be deleted, what would object,
3
+ * `git` plugin of workstation-cleaner): what could be deleted, what would object,
4
4
  * and what it depends on. `removeCandidate` (in `clean.ts`) takes one back.
5
5
  */
6
6
  import { fingerprint } from "./plan.js";
package/dist/clean.d.ts CHANGED
@@ -31,7 +31,7 @@ import { type Approval, type ResolvedApproval } from './approval.ts';
31
31
  import type { Annotate } from './hooks.ts';
32
32
  import type { CleanCandidate } from './candidates.ts';
33
33
  import { type Plan } from './plan.ts';
34
- import { type Dropped, type Receipt, type Step } from './receipt.ts';
34
+ import { type ArchiveRecord, type Dropped, type Receipt, type Step } from './receipt.ts';
35
35
  import { type Runners } from './sweep.ts';
36
36
  import { type Risk, type RowId, type Sweep, type SweepProgress, type RepoNote } from './types.ts';
37
37
  interface Shared extends Runners {
@@ -144,6 +144,12 @@ export interface RemoveCandidateOptions extends Runners {
144
144
  allow?: readonly Risk[] | undefined;
145
145
  /** Archive unlanded work to the remote first, as `check` is given it. */
146
146
  archive?: ArchiveOptions | undefined;
147
+ /**
148
+ * The archive {@link archiveCandidates} made that holds this candidate, in
149
+ * place of `archive`: nothing is pushed, and a candidate with unlanded work
150
+ * that the archive does not hold as it is now is refused.
151
+ */
152
+ archived?: CandidateArchive | undefined;
147
153
  now?: (() => Date) | undefined;
148
154
  /** Told after each step, with its `result` set. */
149
155
  onStepDone?: ((step: Step) => void) | undefined;
@@ -158,12 +164,46 @@ export interface CandidateRemoval {
158
164
  /** Why it did not complete: the failed step's error, or the refusal. Null when `ok`. */
159
165
  error: string | null;
160
166
  }
167
+ /** The refusal of an archive for `repo`, which has no remote to push it to. */
168
+ export declare function noRemote(repo: string): string;
169
+ /** The archive of one repository's candidates, as {@link archiveCandidates} pushed it. */
170
+ export interface CandidateArchive {
171
+ repo: string;
172
+ /** The options it was made with. */
173
+ options: ArchiveOptions;
174
+ /** What was pushed; null when the candidates held nothing the remote lacks. */
175
+ record: ArchiveRecord | null;
176
+ /** What each archived candidate held: a branch's commit, a worktree's HEAD and files. */
177
+ stamps: ReadonlyMap<RowId, string>;
178
+ /** Why a candidate was left out of it. */
179
+ refused: ReadonlyMap<RowId, string>;
180
+ }
181
+ /**
182
+ * Archive the unlanded work of one repository's `candidates` to its remote, as
183
+ * `run` does: one commit, one push, checked with `ls-remote`. Pass the answer
184
+ * to {@link removeCandidate} as `archived`. A candidate with nothing unlanded
185
+ * is ignored, and one `removeCandidate` would refuse is left out (`refused`),
186
+ * so nothing is pushed that was not granted. Deletes nothing.
187
+ *
188
+ * @throws when the candidates are of several repositories, the repository has
189
+ * no remote, a worktree cannot be read or held, or the push fails or cannot
190
+ * be confirmed.
191
+ */
192
+ export declare function archiveCandidates(candidates: readonly CleanCandidate[], opts: Omit<RemoveCandidateOptions, 'archive' | 'archived' | 'onStepDone'> & {
193
+ archive: ArchiveOptions;
194
+ }): CandidateArchive;
195
+ /**
196
+ * Why `candidate` may not be deleted on the strength of `archived`, or null
197
+ * when it may: it holds nothing unlanded, or the archive holds it. A branch is
198
+ * compared by the commit its candidate names; a worktree as it is now.
199
+ */
200
+ export declare function archiveProblem(candidate: CleanCandidate, archived: CandidateArchive, opts?: Pick<Runners, 'git'>): string | null;
161
201
  /**
162
202
  * Delete one candidate as `run` takes one row: the archive first when
163
- * `archive` is given and the row holds unlanded work, then the live-process
164
- * and unsafe-force checks, the removal and its verification, stopping at the
165
- * first failure. The caller has already re-checked the candidate; this
166
- * refuses only what is unsafe now.
203
+ * `archive` is given and the row holds unlanded work (or the check that
204
+ * `archived` holds it), then the live-process and unsafe-force checks, the
205
+ * removal and its verification, stopping at the first failure. The caller has
206
+ * already re-checked the candidate; this refuses only what is unsafe now.
167
207
  *
168
208
  * A worktree whose removal needs `git worktree prune` is refused when the
169
209
  * prune would also drop another worktree of its repository, since this sees
package/dist/clean.js CHANGED
@@ -36,7 +36,7 @@ import { allowed, keyOf, resolveApproval, same, uniq, } from "./approval.js";
36
36
  import { localDeleteCommand, remoteDeleteCommand } from "./branches.js";
37
37
  import { fingerprint, runnable, sameFingerprint } from "./plan.js";
38
38
  import { busyHolders, defaultProcessProbe, parseLockOwner } from "./processes.js";
39
- import { RECEIPT_VERSION } from "./receipt.js";
39
+ import { RECEIPT_VERSION, } from "./receipt.js";
40
40
  import { defaultCacheDir, mirrorProblem } from "./remote-mirror.js";
41
41
  import { sizeOf } from "./size.js";
42
42
  import { inspectSubmodules, submoduleHazards } from "./submodules.js";
@@ -441,7 +441,7 @@ function planSteps(plan, approval, opts) {
441
441
  continue;
442
442
  const info = rechecked.infos.get(root);
443
443
  if (info.remote === null) {
444
- throw new RepoCleanerError('conflict', `archive: ${root} has no remote to push the archive to`);
444
+ throw new RepoCleanerError('conflict', noRemote(root));
445
445
  }
446
446
  const step = pending(root, members[0].row.id, 'archive', shellJoin(['git', 'push', info.remote, 'refs/heads/archive/<repo>-local-<date>']));
447
447
  archives.set(step, {
@@ -625,12 +625,11 @@ measure, archive) {
625
625
  throw new Error('archive without its rows');
626
626
  }
627
627
  const { remote, defaultRef, jobs } = archive.job;
628
- const pushed = pushArchive(at, remote, defaultRef, jobs, archive.options, archive.now);
629
- if (pushed === null)
630
- return 'nothing to archive';
631
- const { record } = pushed;
632
- for (const [id, stamp] of pushed.stamps)
628
+ const { record, stamps } = pushArchive(at, remote, defaultRef, jobs, archive.options, archive.now);
629
+ for (const [id, stamp] of stamps)
633
630
  archive.stamps.set(`${step.repo}\0${id}`, stamp);
631
+ if (record === null)
632
+ return 'nothing to archive';
634
633
  step.archive = record;
635
634
  step.command = shellJoin(['git', 'push', remote, `${record.sha}:${record.ref}`]);
636
635
  return `${record.ref} lists ${record.sha}`;
@@ -899,48 +898,29 @@ function rowOfCandidate(c) {
899
898
  evidence: c.evidence,
900
899
  });
901
900
  }
902
- /**
903
- * Delete one candidate as `run` takes one row: the archive first when
904
- * `archive` is given and the row holds unlanded work, then the live-process
905
- * and unsafe-force checks, the removal and its verification, stopping at the
906
- * first failure. The caller has already re-checked the candidate; this
907
- * refuses only what is unsafe now.
908
- *
909
- * A worktree whose removal needs `git worktree prune` is refused when the
910
- * prune would also drop another worktree of its repository, since this sees
911
- * only the one row.
912
- *
913
- * Does not throw for a refused or failed delete: see `CandidateRemoval`.
914
- */
915
- export function removeCandidate(candidate, opts = {}) {
916
- const now = opts.now ?? (() => new Date());
917
- const refused = (error) => ({
918
- steps: [],
919
- ok: false,
920
- archiveFailed: false,
921
- error,
922
- });
901
+ /** Judge `candidate` as `removeCandidate` takes it: accepted, or the refusal. */
902
+ function acceptCandidate(candidate, opts, archive) {
923
903
  const row = rowOfCandidate(candidate);
924
904
  if (!runnable(row))
925
- return refused(`refused: ${candidate.id} ${candidate.why}`);
905
+ return `refused: ${candidate.id} ${candidate.why}`;
926
906
  const cwd = opts.cwd ?? process.cwd();
927
907
  // Anchored without folding `..`, as the sweep does, so a `..` after a symlink is judged where it really is.
928
908
  const absCwd = isAbsolute(cwd) ? cwd : `${process.cwd()}${sep}${cwd}`;
929
909
  if (row.kind === 'worktree' && nodeGuard.contains(row.name, absCwd)) {
930
- return refused(`refused: ${candidate.id} is the worktree the caller stands in`);
910
+ return `refused: ${candidate.id} is the worktree the caller stands in`;
931
911
  }
932
912
  const allow = new Set(opts.allow ?? []);
933
913
  let judged;
934
914
  try {
935
- judged = judgeRisks(row, (risk) => allow.has(risk), opts.archive, (path) => new Git(path, { runner: opts.git }));
915
+ judged = judgeRisks(row, (risk) => allow.has(risk), archive, (path) => new Git(path, { runner: opts.git }));
936
916
  }
937
917
  catch (err) {
938
- return refused(`refused: ${candidate.id}: ${errorText(err)}`);
918
+ return `refused: ${candidate.id}: ${errorText(err)}`;
939
919
  }
940
920
  if (judged.missing.length > 0) {
941
- return refused(`refused: ${candidate.id} needs ${judged.missing.join(', ')}`);
921
+ return `refused: ${candidate.id} needs ${judged.missing.join(', ')}`;
942
922
  }
943
- const a = {
923
+ return {
944
924
  repo: candidate.repo,
945
925
  row,
946
926
  discard: judged.discard,
@@ -948,12 +928,134 @@ export function removeCandidate(candidate, opts = {}) {
948
928
  discardNamed: allow.has('discard-changes'),
949
929
  needs: judged.needs,
950
930
  };
931
+ }
932
+ /** The refusal of an archive for `repo`, which has no remote to push it to. */
933
+ export function noRemote(repo) {
934
+ return `archive: ${repo} has no remote to push the archive to`;
935
+ }
936
+ /**
937
+ * Archive the unlanded work of one repository's `candidates` to its remote, as
938
+ * `run` does: one commit, one push, checked with `ls-remote`. Pass the answer
939
+ * to {@link removeCandidate} as `archived`. A candidate with nothing unlanded
940
+ * is ignored, and one `removeCandidate` would refuse is left out (`refused`),
941
+ * so nothing is pushed that was not granted. Deletes nothing.
942
+ *
943
+ * @throws when the candidates are of several repositories, the repository has
944
+ * no remote, a worktree cannot be read or held, or the push fails or cannot
945
+ * be confirmed.
946
+ */
947
+ export function archiveCandidates(candidates, opts) {
948
+ const first = candidates[0];
949
+ if (first === undefined || candidates.some((c) => c.repo !== first.repo)) {
950
+ throw new Error("archive: takes one repository's candidates");
951
+ }
952
+ const refused = new Map();
953
+ const jobs = [];
954
+ for (const c of candidates) {
955
+ if (!mayContribute(c))
956
+ continue;
957
+ const a = acceptCandidate(c, opts, opts.archive);
958
+ if (typeof a === 'string')
959
+ refused.set(c.id, a);
960
+ else
961
+ jobs.push({ id: c.id, row: a.row, discardAllowed: a.discardNamed });
962
+ }
963
+ const made = { repo: first.repo, options: opts.archive, refused };
964
+ if (jobs.length === 0)
965
+ return { ...made, record: null, stamps: new Map() };
966
+ if (first.remote === null)
967
+ throw new Error(noRemote(first.repo));
968
+ const pushed = pushArchive(new Git(opts.cwd ?? process.cwd(), { runner: opts.git }).at(first.repo), first.remote, first.landedRef, jobs, opts.archive, (opts.now ?? (() => new Date()))());
969
+ // A branch's stamp is the commit it stood at when the archive was made.
970
+ const stamps = new Map(jobs.map(({ id, row }) => [id, pushed.stamps.get(id) ?? tipOf(row)]));
971
+ return { ...made, record: pushed.record, stamps };
972
+ }
973
+ /** The commit a branch row stands for; empty for a worktree. */
974
+ const tipOf = (row) => (row.kind === 'worktree' ? '' : row.evidence.sha);
975
+ /**
976
+ * Why `archived` does not hold `candidate` as its evidence names it, or null
977
+ * when it does or the candidate holds nothing unlanded. A branch is compared
978
+ * by the commit its candidate names, which `delete-branch` deletes it at; a
979
+ * worktree's files are not read here.
980
+ */
981
+ function notArchived(candidate, archived) {
982
+ if (!mayContribute(candidate))
983
+ return null;
984
+ const left = archived.refused.get(candidate.id);
985
+ if (left !== undefined)
986
+ return left;
987
+ const stamp = archived.repo === candidate.repo ? archived.stamps.get(candidate.id) : undefined;
988
+ if (stamp === undefined)
989
+ return `refused: ${candidate.id} was not archived`;
990
+ const row = rowOfCandidate(candidate);
991
+ return row.kind === 'worktree' || stamp === tipOf(row)
992
+ ? null
993
+ : `refused: ${candidate.path} changed since it was archived`;
994
+ }
995
+ /**
996
+ * Why `candidate` may not be deleted on the strength of `archived`, or null
997
+ * when it may: it holds nothing unlanded, or the archive holds it. A branch is
998
+ * compared by the commit its candidate names; a worktree as it is now.
999
+ */
1000
+ export function archiveProblem(candidate, archived, opts = {}) {
1001
+ const missing = notArchived(candidate, archived);
1002
+ if (missing !== null || !mayContribute(candidate))
1003
+ return missing;
1004
+ const row = rowOfCandidate(candidate);
1005
+ if (row.kind !== 'worktree')
1006
+ return null;
1007
+ let now;
1008
+ try {
1009
+ now = worktreeStamp(new Git(row.name, { runner: opts.git }), archived.options, row.risks.includes('discard-changes'));
1010
+ }
1011
+ catch (err) {
1012
+ return `refused: ${candidate.id}: ${errorText(err)}`;
1013
+ }
1014
+ return archived.stamps.get(candidate.id) === now
1015
+ ? null
1016
+ : `refused: ${candidate.path} changed since it was archived`;
1017
+ }
1018
+ /**
1019
+ * Delete one candidate as `run` takes one row: the archive first when
1020
+ * `archive` is given and the row holds unlanded work (or the check that
1021
+ * `archived` holds it), then the live-process and unsafe-force checks, the
1022
+ * removal and its verification, stopping at the first failure. The caller has
1023
+ * already re-checked the candidate; this refuses only what is unsafe now.
1024
+ *
1025
+ * A worktree whose removal needs `git worktree prune` is refused when the
1026
+ * prune would also drop another worktree of its repository, since this sees
1027
+ * only the one row.
1028
+ *
1029
+ * Does not throw for a refused or failed delete: see `CandidateRemoval`.
1030
+ */
1031
+ export function removeCandidate(candidate, opts = {}) {
1032
+ const now = opts.now ?? (() => new Date());
1033
+ const refused = (error) => ({
1034
+ steps: [],
1035
+ ok: false,
1036
+ archiveFailed: false,
1037
+ error,
1038
+ });
1039
+ const archive = opts.archived?.options ?? opts.archive;
1040
+ const a = acceptCandidate(candidate, opts, archive);
1041
+ if (typeof a === 'string')
1042
+ return refused(a);
1043
+ const { row } = a;
951
1044
  const steps = stepsFor(a).map((step) => [step, a]);
1045
+ const stamps = new Map();
952
1046
  let job;
953
- if (opts.archive !== undefined && mayContribute(row)) {
954
- if (candidate.remote === null) {
955
- return refused(`archive: ${candidate.repo} has no remote to push the archive to`);
956
- }
1047
+ if (opts.archived !== undefined) {
1048
+ // A worktree's files are compared with the archive by its `remove-worktree` step.
1049
+ const problem = notArchived(candidate, opts.archived);
1050
+ if (problem !== null)
1051
+ return refused(problem);
1052
+ const stamp = opts.archived.stamps.get(row.id);
1053
+ if (stamp !== undefined)
1054
+ stamps.set(`${a.repo}\0${row.id}`, stamp);
1055
+ }
1056
+ else if (archive !== undefined && mayContribute(row)) {
1057
+ if (candidate.remote === null)
1058
+ return refused(noRemote(candidate.repo));
957
1059
  const step = pending(candidate.repo, row.id, 'archive', shellJoin(['git', 'push', candidate.remote, 'refs/heads/archive/<repo>-local-<date>']));
958
1060
  job = {
959
1061
  remote: candidate.remote,
@@ -963,19 +1065,19 @@ export function removeCandidate(candidate, opts = {}) {
963
1065
  steps.unshift([step, null]);
964
1066
  }
965
1067
  const ctx = {
966
- git: new Git(cwd, { runner: opts.git }),
1068
+ git: new Git(opts.cwd ?? process.cwd(), { runner: opts.git }),
967
1069
  probe: opts.probe ?? defaultProcessProbe(),
968
1070
  removedHere: new Set(row.kind === 'worktree' ? [resolve(row.name)] : []),
969
1071
  measure: (path) => sizeOf(path, { du: opts.du }),
970
1072
  unlocked: new Set(),
971
- stamps: new Map(),
1073
+ stamps,
972
1074
  };
973
1075
  const taken = [];
974
1076
  for (const [step, accepted] of steps) {
975
1077
  taken.push(step);
976
1078
  runStep(step, accepted, ctx, {
977
1079
  job: step.action === 'archive' ? job : undefined,
978
- options: opts.archive,
1080
+ options: archive,
979
1081
  now: now(),
980
1082
  });
981
1083
  opts.onStepDone?.(step);
package/dist/index.d.ts CHANGED
@@ -15,17 +15,17 @@
15
15
  */
16
16
  export { sweep, inspectWorktree, type Runners, type SweepOptions } from './sweep.ts';
17
17
  export { PLAN_VERSION, PlanSchema, fingerprint, plan, readPlan, sameFingerprint, writePlan, type Plan, type PlanRepo, type PlanRow, } from './plan.ts';
18
- export { DEFAULT_MAX_FILE_BYTES, type ArchiveOptions, type LeftOut } from './archive.ts';
18
+ export { DEFAULT_MAX_FILE_BYTES, mayContribute, type ArchiveOptions, type LeftOut, } from './archive.ts';
19
19
  export { DEFAULT_MAX_DEPTH } from './resolve.ts';
20
20
  export { isGlob, type Allow, type Approval, type ResolvedApproval, type Resolved, } from './approval.ts';
21
21
  export { globRegExp } from './util.ts';
22
- export { check, removeCandidate, run, type CandidateRemoval, type CheckOptions, type Preview, type RemoveCandidateOptions, type RunOptions, } from './clean.ts';
22
+ export { archiveCandidates, archiveProblem, check, noRemote, removeCandidate, run, type CandidateArchive, type CandidateRemoval, type CheckOptions, type Preview, type RemoveCandidateOptions, type RunOptions, } from './clean.ts';
23
23
  export { candidatesOf, type CleanCandidate } from './candidates.ts';
24
24
  export { writeJsonAtomic } from './write-json.ts';
25
25
  export { RECEIPT_VERSION, ReceiptSchema, type DropReason, type Dropped, type ArchiveRecord, type Receipt, type Step, } from './receipt.ts';
26
26
  export { render, type RunSummary, type Style } from './render.ts';
27
27
  export { formatBytes, sizeOf, type SizeOfOptions } from './size.ts';
28
- export { busyHolders, defaultProcessProbe, type ProcessHolder, type ProcessProbe, } from './processes.ts';
28
+ export { busyHolders, defaultProcessProbe, PS_ENV as PS_LSTART_ENV, startMs, type ProcessHolder, type ProcessProbe, } from './processes.ts';
29
29
  export { providers, type PrProvider, type ProviderChoice } from './providers/index.ts';
30
30
  export type { Annotate } from './hooks.ts';
31
31
  export { KINDS, RISKS, RepoCleanerError, judgedRemotes, landedFor, refOf, type Action, type Blocker, type BranchEvidence, type BranchRow, type Bucket, type Counts, type ErrorCode, type Kind, type LandedAgainst, type LandingEvidence, type PrEvidence, type RemoteEvidence, type RemoteInfo, type RemoteRow, type RepoInfo, type RepoNote, type RepoSweep, type Reclaimable, type Risk, type Row, type RowId, type SubmoduleEvidence, type Sweep, type SweepProgress, type SweptWith, type Verdict, type WorktreeEvidence, type WorktreeRow, } from './types.ts';
package/dist/index.js CHANGED
@@ -15,16 +15,16 @@
15
15
  */
16
16
  export { sweep, inspectWorktree } from "./sweep.js";
17
17
  export { PLAN_VERSION, PlanSchema, fingerprint, plan, readPlan, sameFingerprint, writePlan, } from "./plan.js";
18
- export { DEFAULT_MAX_FILE_BYTES } from "./archive.js";
18
+ export { DEFAULT_MAX_FILE_BYTES, mayContribute, } from "./archive.js";
19
19
  export { DEFAULT_MAX_DEPTH } from "./resolve.js";
20
20
  export { isGlob, } from "./approval.js";
21
21
  export { globRegExp } from "./util.js";
22
- export { check, removeCandidate, run, } from "./clean.js";
22
+ export { archiveCandidates, archiveProblem, check, noRemote, removeCandidate, run, } from "./clean.js";
23
23
  export { candidatesOf } from "./candidates.js";
24
24
  export { writeJsonAtomic } from "./write-json.js";
25
25
  export { RECEIPT_VERSION, ReceiptSchema, } from "./receipt.js";
26
26
  export { render } from "./render.js";
27
27
  export { formatBytes, sizeOf } from "./size.js";
28
- export { busyHolders, defaultProcessProbe, } from "./processes.js";
28
+ export { busyHolders, defaultProcessProbe, PS_ENV as PS_LSTART_ENV, startMs, } from "./processes.js";
29
29
  export { providers } from "./providers/index.js";
30
30
  export { KINDS, RISKS, RepoCleanerError, judgedRemotes, landedFor, refOf, } from "./types.js";
@@ -100,6 +100,15 @@ export interface DefaultProbeOptions {
100
100
  */
101
101
  platform?: NodeJS.Platform | undefined;
102
102
  }
103
+ /**
104
+ * `ps` reads its own zone and locale. `TZ=UTC` makes the zoneless `lstart` one
105
+ * instant, so the repeated hour of a DST fall-back cannot read as two; `LC_ALL=C`
106
+ * keeps the month and day names English.
107
+ */
108
+ export declare const PS_ENV: {
109
+ readonly TZ: "UTC";
110
+ readonly LC_ALL: "C";
111
+ };
103
112
  /**
104
113
  * The default probe: `ps` for liveness, `lsof` for working directories, both
105
114
  * through the command seam.
package/dist/processes.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * answer them without a process table. The default probe runs `ps` and `lsof`
12
12
  * through the command seam.
13
13
  */
14
- import { realpathSync } from 'node:fs';
14
+ import { existsSync, realpathSync } from 'node:fs';
15
15
  import { spawnRunner } from '@osdlc/command-seam';
16
16
  import { sameProcess } from '@osdlc/file-lock';
17
17
  import { nodeGuard } from '@osdlc/path-guard/node';
@@ -116,7 +116,21 @@ function killProbe(pid) {
116
116
  * instant, so the repeated hour of a DST fall-back cannot read as two; `LC_ALL=C`
117
117
  * keeps the month and day names English.
118
118
  */
119
- const PS_ENV = { TZ: 'UTC', LC_ALL: 'C' };
119
+ export const PS_ENV = { TZ: 'UTC', LC_ALL: 'C' };
120
+ /** What Linux appends to the working directory of a process whose directory was removed. */
121
+ const DELETED = ' (deleted)';
122
+ /**
123
+ * The directories a working directory as lsof lists it may be: itself, and,
124
+ * when it ends in {@link DELETED}, the removed directory it names while no
125
+ * directory is there again, since a process may still sit in a directory that
126
+ * is gone, but not in one made later at its path.
127
+ */
128
+ const cwdsOf = (cwd) => {
129
+ if (!cwd.endsWith(DELETED))
130
+ return [cwd];
131
+ const removed = cwd.slice(0, -DELETED.length);
132
+ return existsSync(removed) ? [cwd] : [cwd, removed];
133
+ };
120
134
  /** True when the command ran and reported an exit status. */
121
135
  const answered = (r) => r.neverExited !== true;
122
136
  /**
@@ -189,10 +203,13 @@ export function defaultProcessProbe(opts = {}) {
189
203
  roots.add(realpathSync(path));
190
204
  }
191
205
  catch {
192
- // A directory that is gone has no holders.
206
+ // A directory that is gone has only the path as given: `contains` follows the links above it.
193
207
  }
194
208
  return table
195
- .filter((row) => [...roots].some((root) => nodeGuard.contains(root, row.cwd)))
209
+ .filter((row) => {
210
+ const cwds = cwdsOf(row.cwd);
211
+ return [...roots].some((root) => cwds.some((cwd) => nodeGuard.contains(root, cwd)));
212
+ })
196
213
  .map(({ pid, command, hasChildren }) => ({ pid, command, hasChildren }));
197
214
  },
198
215
  };
@@ -112,7 +112,7 @@ export declare function submoduleHazards(report: SubmoduleReport, opts?: {
112
112
  discard?: boolean;
113
113
  abandon?: boolean;
114
114
  }): string[];
115
- /** `submodule(s) sub (1 unpushed commit), deps/x (2 stashes)`. */
115
+ /** `submodule sub (1 unpushed commit)`, or `submodules sub (1 unpushed commit), deps/x (2 stashes)`. */
116
116
  export declare function unpushedPhrase(subs: readonly Submodule[]): string;
117
117
  /** `submodule(s) sub (<why it could not be read>)`. */
118
118
  export declare function unreadablePhrase(subs: readonly Submodule[]): string;
@@ -260,7 +260,8 @@ export function submoduleHazards(report, opts = {}) {
260
260
  if (report.unreadable.length > 0)
261
261
  out.push(`could not read ${unreadablePhrase(report.unreadable)}`);
262
262
  if (opts.abandon !== true && report.unpushed.length > 0) {
263
- out.push(`${unpushedPhrase(report.unpushed)} hold work no remote has`);
263
+ const hold = report.unpushed.length === 1 ? 'holds' : 'hold';
264
+ out.push(`${unpushedPhrase(report.unpushed)} ${hold} work no remote has`);
264
265
  }
265
266
  const hidden = report.submodules.filter((s) => s.hiddenIndexPaths.length > 0);
266
267
  if (hidden.length > 0)
@@ -273,9 +274,10 @@ export function submoduleHazards(report, opts = {}) {
273
274
  }
274
275
  return out;
275
276
  }
276
- /** `submodule(s) sub (1 unpushed commit), deps/x (2 stashes)`. */
277
+ /** `submodule sub (1 unpushed commit)`, or `submodules sub (1 unpushed commit), deps/x (2 stashes)`. */
277
278
  export function unpushedPhrase(subs) {
278
- return `submodule(s) ${subs.map((s) => `${s.path} (${unsharedPhrase(s)})`).join(', ')}`;
279
+ const which = subs.length === 1 ? 'submodule' : 'submodules';
280
+ return `${which} ${subs.map((s) => `${s.path} (${unsharedPhrase(s)})`).join(', ')}`;
279
281
  }
280
282
  /** `submodule(s) sub (<why it could not be read>)`. */
281
283
  export function unreadablePhrase(subs) {
package/dist/types.d.ts CHANGED
@@ -143,6 +143,11 @@ export interface WorktreeEvidence extends LandingEvidence {
143
143
  unpushedCommits?: number;
144
144
  /** What `unpushedCommits` was counted against: the upstream, or the default branch. */
145
145
  compareAgainst?: string;
146
+ /**
147
+ * True when `compareAgainst` did not resolve (a remote never fetched), so
148
+ * `unpushedCommits` is not known; the row then carries `abandon-unmerged`.
149
+ */
150
+ aheadUnknown?: boolean;
146
151
  branchExists?: boolean;
147
152
  /** Set for a worktree merged by ancestry alone; null when its branch looks freshly made. */
148
153
  branchUsed?: BranchUse | null;
@@ -171,6 +176,13 @@ export interface WorktreeEvidence extends LandingEvidence {
171
176
  recoverableFrom?: string[];
172
177
  /** Its submodules make plain `git worktree remove` refuse, so the remove is forced. */
173
178
  forcedForSubmodules?: boolean;
179
+ /**
180
+ * Set for a gone worktree whose branch does not hold its HEAD (detached, or
181
+ * the branch was deleted): whether a local branch, tag or remote-tracking
182
+ * branch does. Null when git could not say. Not true: the prune would leave
183
+ * the commit unreachable, so it needs `abandon-unmerged`.
184
+ */
185
+ headOnRef?: boolean | null;
174
186
  }
175
187
  export interface BranchEvidence extends LandingEvidence {
176
188
  branch: string;
@@ -1,2 +1,2 @@
1
1
  /** This package's version, from its package.json when it was built. */
2
- export declare const VERSION = "0.24.1";
2
+ export declare const VERSION = "0.26.0";
@@ -1,3 +1,3 @@
1
1
  // Generated by cli-tool-stamp-version from package.json. Do not edit.
2
2
  /** This package's version, from its package.json when it was built. */
3
- export const VERSION = '0.24.1';
3
+ export const VERSION = '0.26.0';
@@ -8,6 +8,27 @@
8
8
  import type { Git } from '@osdlc/typed-git';
9
9
  import { type ProcessProbe } from './processes.ts';
10
10
  import { type PRInfo, type RepoInfo, type WorktreeEvidence, type WorktreeRow } from './types.ts';
11
+ /** What {@link workPhrase} words. */
12
+ export interface HeldWork {
13
+ /** Modified, staged and untracked files in the worktree itself. */
14
+ dirtyFiles: number;
15
+ /** The same, summed over its submodules. */
16
+ submoduleDirtyFiles: number;
17
+ /** The submodules those are in. */
18
+ dirtySubmodules: readonly string[];
19
+ /** Commits ahead of `against`. */
20
+ ahead: number;
21
+ /** Set when `ahead` is not known: what did not resolve, `against` or `HEAD`. */
22
+ unresolved?: string | undefined;
23
+ against: string;
24
+ /** `unpushedPhrase` of the submodules with work no remote has, or `''`. */
25
+ submoduleWork: string;
26
+ }
27
+ /**
28
+ * The reason of a worktree that holds work: `1 dirty file, 2 commits ahead of
29
+ * origin/main`. A count of zero is left out.
30
+ */
31
+ export declare function workPhrase(w: HeldWork): string;
11
32
  /** The command line, not run, that removes the worktree at `path`. */
12
33
  export declare function worktreeRemoveCommand(root: string, path: string, opts?: {
13
34
  force?: boolean;
package/dist/worktrees.js CHANGED
@@ -14,7 +14,47 @@ import { confirmationNote, judgeLanding, landingConfirmed, recordLanding, unmatc
14
14
  import { busyHolders, isIdleHolder, parseLockOwner } from "./processes.js";
15
15
  import { inspectSubmodules, readIndexHazards, submoduleFacts, unpushedPhrase, unreadablePhrase, worktreeGitDirs, } from "./submodules.js";
16
16
  import { landedFor, refOf, makeRow, risksFor, } from "./types.js";
17
- import { isDir } from "./util.js";
17
+ import { isDir, plural } from "./util.js";
18
+ /**
19
+ * The reason of a worktree that holds work: `1 dirty file, 2 commits ahead of
20
+ * origin/main`. A count of zero is left out.
21
+ */
22
+ export function workPhrase(w) {
23
+ const files = (n) => plural(n, 'dirty file', 'dirty files');
24
+ const parts = [];
25
+ if (w.dirtyFiles > 0)
26
+ parts.push(files(w.dirtyFiles));
27
+ if (w.submoduleDirtyFiles > 0) {
28
+ const where = `${w.dirtySubmodules.length === 1 ? 'submodule' : 'submodules'} ${w.dirtySubmodules.join(', ')}`;
29
+ parts.push(w.dirtyFiles > 0
30
+ ? `${w.submoduleDirtyFiles} in ${where}`
31
+ : `${files(w.submoduleDirtyFiles)} in ${where}`);
32
+ }
33
+ if (w.unresolved !== undefined) {
34
+ parts.push(`commits ahead of ${w.against} not known: ${w.unresolved} does not resolve`);
35
+ }
36
+ else if (w.ahead > 0) {
37
+ parts.push(`${plural(w.ahead, 'commit', 'commits')} ahead of ${w.against}`);
38
+ }
39
+ const said = parts.join(', ');
40
+ if (w.submoduleWork === '')
41
+ return said;
42
+ const work = `unpushed work in ${w.submoduleWork}`;
43
+ return said === '' ? work : `${said}; ${work}`;
44
+ }
45
+ /**
46
+ * Whether a local branch, a tag or a remote-tracking branch holds `head`;
47
+ * null when there is no `head`, or git cannot say (its commit is missing, say).
48
+ */
49
+ function headOnRef(git, head) {
50
+ if (head === null)
51
+ return null;
52
+ const held = git.try.forEachRef(['refs/heads/', 'refs/tags/', 'refs/remotes/'], {
53
+ format: '%(refname)',
54
+ contains: head,
55
+ });
56
+ return held.ok ? held.value.length > 0 : null;
57
+ }
18
58
  /** The command line, not run, that removes the worktree at `path`. */
19
59
  export function worktreeRemoveCommand(root, path, opts = {}) {
20
60
  return shellJoin([
@@ -262,6 +302,8 @@ function classifyWorktree(opts) {
262
302
  evidence.forcedForSubmodules = true;
263
303
  let dirtyFiles = [];
264
304
  let unpushed = [];
305
+ /** What did not resolve when the commits ahead could not be counted. */
306
+ let unresolved;
265
307
  if (onDisk) {
266
308
  dirtyFiles = git.at(path).statusPorcelain();
267
309
  let compareAgainst = '';
@@ -276,10 +318,16 @@ function classifyWorktree(opts) {
276
318
  compareAgainst = landedOn;
277
319
  }
278
320
  // `try`: `compareAgainst` is a guess — the fallback `origin/main` need not
279
- // exist locally, and an unresolvable range renders as zero unpushed commits.
321
+ // exist locally (a remote never fetched). A range that does not resolve
322
+ // leaves the count unknown, which is not none.
280
323
  const range = git.at(path).try.logLines({ range: `${compareAgainst}..HEAD`, format: '%h %s' });
281
324
  if (range.ok)
282
325
  unpushed = range.value;
326
+ else {
327
+ evidence.aheadUnknown = true;
328
+ // A deleted branch leaves HEAD unborn while the base resolves.
329
+ unresolved = git.at(path).resolveRef(compareAgainst) === null ? compareAgainst : 'HEAD';
330
+ }
283
331
  evidence.compareAgainst = compareAgainst;
284
332
  }
285
333
  evidence.dirtyFiles = dirtyFiles.length;
@@ -301,7 +349,7 @@ function classifyWorktree(opts) {
301
349
  if (patch !== null)
302
350
  recordLanding(evidence, patch);
303
351
  const patchLanded = patch !== null && patch.check !== null;
304
- let unlanded = unpushed.length > 0 && !landed && !landingConfirmed(patch);
352
+ let unlanded = (unpushed.length > 0 || evidence.aheadUnknown === true) && !landed && !landingConfirmed(patch);
305
353
  if (onDisk && head !== null) {
306
354
  evidence.landedAgainst = landedOn;
307
355
  // `soft`: a missing default ref reads as not merged.
@@ -340,8 +388,16 @@ function classifyWorktree(opts) {
340
388
  }
341
389
  }
342
390
  }
391
+ // A gone worktree's HEAD is kept by its admin dir alone, which the prune
392
+ // deletes: on a branch that still exists the branch holds it, else only
393
+ // another ref can. One no ref holds, or one that cannot be read, is lost.
394
+ let headLost = false;
395
+ if (!onDisk && !(branch && branchExists)) {
396
+ evidence.headOnRef = headOnRef(git.at(repo.root), head);
397
+ headLost = evidence.headOnRef !== true;
398
+ }
343
399
  const risks = risksFor({
344
- 'abandon-unmerged': unlanded || submoduleWork,
400
+ 'abandon-unmerged': unlanded || submoduleWork || headLost,
345
401
  'discard-changes': dirty,
346
402
  'confirm-open-pr': pr?.state === 'OPEN',
347
403
  });
@@ -362,6 +418,29 @@ function classifyWorktree(opts) {
362
418
  notes: blockers.map(([, advice]) => advice),
363
419
  });
364
420
  }
421
+ if (!onDisk && headLost) {
422
+ const short = head === null ? null : head.slice(0, 12);
423
+ const held = evidence.headOnRef === false
424
+ ? `its HEAD ${short} is on no branch, tag or remote branch`
425
+ : `no ref could be shown to hold its HEAD${short === null ? '' : ` ${short}`}`;
426
+ const inSubmodules = submoduleWork
427
+ ? `; its git dir keeps work no remote has in ${submoduleWorkText}`
428
+ : '';
429
+ return row({
430
+ verdict: 'review',
431
+ action: 'prune',
432
+ why: `directory gone, but ${held}${inSubmodules}`,
433
+ commands: pruneOnly,
434
+ risks,
435
+ notes: [
436
+ `Worktree ${path} is gone, and ${held}: pruning it leaves ${head === null ? 'that HEAD' : head} unreachable.`,
437
+ ...(submoduleWork
438
+ ? [`Its git dir also keeps ${submoduleWorkText}; pruning it deletes them.`]
439
+ : []),
440
+ `Make a branch at it (\`git branch <name> ${head ?? '<sha>'}\`), or allow abandon-unmerged to prune it anyway.`,
441
+ ],
442
+ });
443
+ }
365
444
  if (!onDisk && submoduleWork) {
366
445
  return row({
367
446
  verdict: 'review',
@@ -386,14 +465,18 @@ function classifyWorktree(opts) {
386
465
  });
387
466
  }
388
467
  if (dirty || unlanded || submoduleWork) {
389
- const inSubmodules = submoduleDirty > 0
390
- ? `, ${submoduleDirty} in submodule(s) ${submodules.dirty.map((s) => s.path).join(', ')}`
391
- : '';
392
- const workInSubmodules = submoduleWork ? `; unpushed work in ${submoduleWorkText}` : '';
393
468
  return row({
394
469
  verdict: 'review',
395
470
  action: 'remove',
396
- why: `${dirtyFiles.length} dirty file(s)${inSubmodules}, ${unpushed.length} commit(s) ahead of ${evidence.compareAgainst}${workInSubmodules}`,
471
+ why: workPhrase({
472
+ dirtyFiles: dirtyFiles.length,
473
+ submoduleDirtyFiles: submoduleDirty,
474
+ dirtySubmodules: submodules.dirty.map((s) => s.path),
475
+ ahead: unpushed.length,
476
+ unresolved,
477
+ against: evidence.compareAgainst ?? landedOn,
478
+ submoduleWork: submoduleWorkText,
479
+ }),
397
480
  commands: removes,
398
481
  risks,
399
482
  notes: [
@@ -410,6 +493,13 @@ function classifyWorktree(opts) {
410
493
  ]
411
494
  : []),
412
495
  ...(remoteNote !== null ? [remoteNote] : []),
496
+ ...(unresolved === undefined
497
+ ? []
498
+ : [
499
+ unresolved === 'HEAD'
500
+ ? 'Its HEAD does not resolve, so its commits could not be counted.'
501
+ : `${unresolved} does not resolve, so its commits could not be counted; \`--fetch\` may make it resolve.`,
502
+ ]),
413
503
  'Decide whether to preserve, push, or discard.',
414
504
  ],
415
505
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdlc/repo-cleaner",
3
- "version": "0.24.1",
3
+ "version": "0.26.0",
4
4
  "description": "What has been merged into the default branch, and what can go away. Inventories local branches, worktrees and remote branches across one repository or many, classifying each with the evidence behind the verdict and the command that would act on it. Plans and applies approved deletes, compare-and-swap.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "sksizer",
@@ -49,12 +49,12 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "zod": "^4.6.6",
52
- "@osdlc/cli-tool": "^0.21.0",
52
+ "@osdlc/cli-tool": "^0.22.0",
53
53
  "@osdlc/command-seam": "^0.15.1",
54
54
  "@osdlc/file-lock": "^0.4.0",
55
55
  "@osdlc/path-guard": "^0.3.1",
56
56
  "@osdlc/typed-gh": "^0.20.0",
57
- "@osdlc/typed-git": "^0.22.0",
57
+ "@osdlc/typed-git": "^0.22.1",
58
58
  "@osdlc/ux": "^0.1.1"
59
59
  },
60
60
  "devDependencies": {