@osdlc/repo-cleaner 0.24.1 → 0.25.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,19 @@
1
1
  # @osdlc/repo-cleaner
2
2
 
3
+ ## 0.25.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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.
8
+ - 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.
9
+
10
+ ### Patch Changes
11
+
12
+ - 28799e2: `holders` works out a process's working folders once per process, not once per root it is checked against.
13
+ - 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.
14
+ - Updated dependencies [0b3fbfa]
15
+ - @osdlc/cli-tool@0.22.0
16
+
3
17
  ## 0.24.1
4
18
 
5
19
  ### Patch Changes
package/README.md CHANGED
@@ -913,6 +913,9 @@ process table once per probe and reuses it for every worktree: `sweep` makes
913
913
  one probe per repository, and `run` uses one probe for its re-sweep and
914
914
  reads the table afresh for each pre-unlock and pre-remove check. Where the
915
915
  table cannot be read the worktree is held back as `process-probe-failed`. A
916
+ process whose working directory was removed, which Linux's `lsof` lists as
917
+ `<path> (deleted)`, still counts as working in `<path>` while nothing is at
918
+ `<path>` again; a gone path is matched through the links above it. A
916
919
  host or test supplies its own probe.
917
920
  Nothing is ever killed.
918
921
 
@@ -1239,12 +1242,17 @@ const receipt = run(preview)
1239
1242
  | `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
1243
  | `inspectWorktree(path, opts?)` | One worktree judged as a sweep judges it, submodules included |
1241
1244
  | `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 |
1245
+ | `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 |
1246
+ | `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 |
1247
+ | `archiveProblem(candidate, archived)` | Why a candidate may not be deleted on that archive, or null when it may |
1248
+ | `mayContribute(candidate)` | True when a candidate holds work an archive could hold; never a worktree whose directory is gone |
1249
+ | `noRemote(repo)` | The refusal of an archive for a repository with no remote |
1243
1250
  | `readPlan`, `writePlan`, `PlanSchema` | Plans on disk |
1244
1251
  | `fingerprint`, `sameFingerprint` | The evidence a row rests on and the rule that compares two of them |
1245
1252
  | `writeJsonAtomic`, `busyHolders` | The atomic JSON write the receipt uses; the holders of a worktree that are not idle shells |
1246
1253
  | `render` | The command line's formats: `text`, `json`, `summary`, `commands`, `preview`, `receipt` |
1247
1254
  | `defaultProcessProbe`, `providers` | The defaults a host can wrap or replace |
1255
+ | `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
1256
  | `RepoCleanerError` | Every refusal, with a `code`: `conflict`, `bad-input`, `not-found`, `ambiguous`, `spared-changed`, `bad-plan` |
1249
1257
 
1250
1258
  A row is a `WorktreeRow`, `BranchRow` or `RemoteRow`, told apart by `kind`:
@@ -1303,7 +1311,9 @@ host re-checks a candidate by sweeping again and comparing `fingerprint` with
1303
1311
  `sameFingerprint`, and turns `blockers` and `risks` into its own objections. It
1304
1312
  deletes what a branch `requires` (its worktree) first. `removeCandidate` keeps the safety model of
1305
1313
  `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.
1314
+ and verified before the delete, one archive per candidate. To push one archive
1315
+ per repository, before the host deletes anything, pass its candidates to
1316
+ `archiveCandidates`, then its answer to each `removeCandidate` as `archived`.
1307
1317
 
1308
1318
  ## Providers (prototype)
1309
1319
 
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()}`,
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
  };
@@ -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.25.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.25.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdlc/repo-cleaner",
3
- "version": "0.24.1",
3
+ "version": "0.25.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,13 +49,13 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "zod": "^4.6.6",
52
- "@osdlc/cli-tool": "^0.21.0",
53
52
  "@osdlc/command-seam": "^0.15.1",
53
+ "@osdlc/cli-tool": "^0.22.0",
54
54
  "@osdlc/file-lock": "^0.4.0",
55
55
  "@osdlc/path-guard": "^0.3.1",
56
- "@osdlc/typed-gh": "^0.20.0",
57
56
  "@osdlc/typed-git": "^0.22.0",
58
- "@osdlc/ux": "^0.1.1"
57
+ "@osdlc/ux": "^0.1.1",
58
+ "@osdlc/typed-gh": "^0.20.0"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/node": "^26.1.0",