@bli-cockpit/cli 0.2.154 → 0.2.156

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.
@@ -1,7 +1,5 @@
1
1
  import { withDoctorLockWait } from "./doctor-lock-wait.js";
2
2
  import { doctorBackfillBudgetSeconds, doctorLockWaitSeconds } from "./doctor-budget.js";
3
- import fs from "node:fs/promises";
4
- import path from "node:path";
5
3
  import { inspectBackfillLock } from "../backfill-lock.js";
6
4
  import { readBackfillCompletionMarker, readBackfillCursor, } from "../cursors/backfill-cursor.js";
7
5
  import { savedDiscoveryLimitArgs } from "../discovery-limits.js";
@@ -12,7 +10,7 @@ import { runEvidenceRedelivery } from "../evidence-redelivery.js";
12
10
  import { DEFAULT_DASHBOARD_URL, getCollectorRuntimePaths } from "../local-state.js";
13
11
  import { runRawEvidenceLocalGc, rawEvidenceGcSummary } from "../raw-evidence-gc.js";
14
12
  import { runBackfillCommand } from "./backfill.js";
15
- import { diskRowMessage, mib, redeliveryLine } from "./doctor-disk-words.js";
13
+ import { FOOTPRINT_NEEDS_FIX_BYTES, diskRowMessage, footprintHolder, footprintTotalBytes, mib, redeliveryLine, } from "./doctor-disk-words.js";
16
14
  import { doctorRoots } from "./doctor-access.js";
17
15
  import { backfillCompletionStepState, backfillFixVerdict, jsonField, parseDoctorBackfillJson, parseDoctorSyncJson, syncFailureMessage, syncBacklogDrainingVerdict, syncStandAsideVerdict, } from "./doctor-pipeline-verdicts.js";
18
16
  import { asRecord, fail, needsFix, ok, skipped } from "./doctor-report.js";
@@ -32,7 +30,6 @@ import { asRecord, fail, needsFix, ok, skipped } from "./doctor-report.js";
32
30
  * `doctor-pipeline-verdicts.ts`, and every one of them is re-exported from
33
31
  * here so callers keep one address.
34
32
  */
35
- const GC_MIN_INTERVAL_MS = 24 * 60 * 60 * 1000;
36
33
  export async function checkBackfillState(context) {
37
34
  const paths = getCollectorRuntimePaths(context.command.homeDir);
38
35
  const roots = await doctorRoots(context);
@@ -137,18 +134,14 @@ export async function checkGcState(context) {
137
134
  if (context.io.env["COCKPIT_DISABLE_GC"] === "1") {
138
135
  return skipped("gc-checked", "skipped_disabled", "cleanup is switched off");
139
136
  }
140
- const paths = getCollectorRuntimePaths(context.command.homeDir);
141
- const marker = path.join(paths.state_dir, ".last-raw-evidence-gc");
142
- const info = await fs.stat(marker).catch(() => null);
143
- if (info && Date.now() - info.mtimeMs < GC_MIN_INTERVAL_MS) {
144
- return skipped("gc-checked", "skipped_throttled", "cleanup already ran today");
145
- }
146
- return needsFix("gc-checked", "due", "cleanup is due");
137
+ // BLI-11106: the GC runs on every sync tick and costs one manifest read per
138
+ // old pack, so there is no "already ran today" to report; doctor runs it too.
139
+ return needsFix("gc-checked", "due", "cleanup runs on every sync; running it now");
147
140
  }
148
141
  export async function fixGcState(context) {
149
142
  const result = await runRawEvidenceLocalGc(getCollectorRuntimePaths(context.command.homeDir), context.io.env);
150
143
  if (result.skipped) {
151
- return skipped("gc-checked", "skipped_throttled", "cleanup already ran today");
144
+ return skipped("gc-checked", "skipped_disabled", "cleanup is switched off");
152
145
  }
153
146
  if (result.removed_dirs === 0) {
154
147
  return ok("gc-checked", "nothing_eligible", rawEvidenceGcSummary(result));
@@ -156,21 +149,47 @@ export async function fixGcState(context) {
156
149
  return ok("gc-checked", `removed_${result.removed_dirs}`, rawEvidenceGcSummary(result));
157
150
  }
158
151
  /**
159
- * BLI-3619: what Cockpit is holding on this machine, in one line.
152
+ * BLI-3619 / BLI-11106: what Tower is holding on this machine, in one line.
160
153
  *
161
- * Green means the staging tree fits under the cap. Over the cap is `needs_fix`
162
- * and the fix is the same prune the tick runs, forced past its daily throttle;
163
- * if it is still over afterwards, the message names the one command that goes
164
- * further. Every number here is metadata — byte counts and file counts, never
165
- * a path.
154
+ * Green means the staging tree fits under the cap AND the whole collector
155
+ * footprint (staging, logs, state, spool) is under 512 MB. Either one crossed
156
+ * is `needs_fix`, and the message names the bucket holding the bytes. The fix
157
+ * is the same prune the tick runs; if it is still over afterwards, the message
158
+ * names the one command that goes further. Every number here is metadata —
159
+ * byte counts and file counts, never a path.
166
160
  */
167
161
  export async function checkDiskState(context) {
168
162
  const footprint = await readDiskFootprint(getCollectorRuntimePaths(context.command.homeDir));
169
163
  const { capBytes } = retentionOptionsFromEnv(context.io.env);
170
164
  const message = diskRowMessage(footprint, capBytes);
171
- return footprint.staging.total_bytes - (footprint.staging.terminal_bytes ?? 0) > capBytes
172
- ? needsFix("disk-bounded", "over_staging_cap", message)
173
- : ok("disk-bounded", "within_staging_cap", message);
165
+ if (footprint.staging.total_bytes - (footprint.staging.terminal_bytes ?? 0) > capBytes) {
166
+ return needsFix("disk-bounded", "over_staging_cap", message);
167
+ }
168
+ const over = footprintOverSentence(footprint);
169
+ if (over)
170
+ return needsFix("disk-bounded", "footprint_over_512mb", `${over}; ${message}`);
171
+ return ok("disk-bounded", "within_staging_cap", message);
172
+ }
173
+ /**
174
+ * "812.0 MB held, over the 512 MB line; most of it is sync logs (600.0 MB)",
175
+ * or null when the footprint is under the line. Logged either way, because a
176
+ * row that only speaks when it is red cannot say the check ran.
177
+ */
178
+ export function footprintOverSentence(footprint) {
179
+ const total = footprintTotalBytes(footprint);
180
+ const holder = footprintHolder(footprint);
181
+ const over = total > FOOTPRINT_NEEDS_FIX_BYTES;
182
+ console.error("[cockpit-doctor] collector footprint", JSON.stringify({
183
+ reason: over ? "footprint_over_512mb" : "footprint_within_512mb",
184
+ total_bytes: total,
185
+ limit_bytes: FOOTPRINT_NEEDS_FIX_BYTES,
186
+ holder: holder?.label ?? null,
187
+ holder_bytes: holder?.bytes ?? 0,
188
+ study_entries_not_counted: footprint.state.study_entries,
189
+ }));
190
+ if (!over)
191
+ return null;
192
+ return `${mib(total)} MB held, over the ${mib(FOOTPRINT_NEEDS_FIX_BYTES)} MB line; most of it is ${holder?.label ?? "unknown"} (${mib(holder?.bytes ?? 0)} MB)`;
174
193
  }
175
194
  export async function fixDiskState(context) {
176
195
  const paths = getCollectorRuntimePaths(context.command.homeDir);
@@ -188,7 +207,6 @@ export async function fixDiskState(context) {
188
207
  const redelivered = redeliveryLine(redelivery);
189
208
  const pruned = await runStagingPrune(paths, {
190
209
  env: context.io.env,
191
- force: true,
192
210
  });
193
211
  if (pruned.status === "fail") {
194
212
  return fail("disk-bounded", pruned.reason, "the prune could not run; nothing was deleted");
@@ -198,6 +216,10 @@ export async function fixDiskState(context) {
198
216
  }
199
217
  const footprint = await readDiskFootprint(paths);
200
218
  const message = diskRowMessage(footprint, pruned.cap_bytes);
219
+ const over = pruned.cap_blocked_by_uncommitted ? null : footprintOverSentence(footprint);
220
+ if (over) {
221
+ return needsFix("disk-bounded", "footprint_over_512mb", `freed ${mib(pruned.deleted_bytes)} MB; ${over}; ${message}`);
222
+ }
201
223
  if (!pruned.cap_blocked_by_uncommitted) {
202
224
  return ok("disk-bounded", `freed_${pruned.deleted_files}`, `freed ${mib(pruned.deleted_bytes)} MB; ${message}`);
203
225
  }
@@ -133,7 +133,7 @@ export function buildCollectorHeartbeat(options) {
133
133
  * that a green, syncing, up-to-date laptop was sitting on 1.8 GB of evidence the
134
134
  * server had never received, and a fleet-wide failure nobody can see is the
135
135
  * BLI-2528 shape exactly. The walk is bounded by the pack tree the prune keeps
136
- * under a 2 GB cap, and it is best-effort: a read that fails returns nulls and
136
+ * under a 256 MiB cap, and it is best-effort: a read that fails returns nulls and
137
137
  * says so, so the heartbeat omits both fields rather than claiming zero.
138
138
  */
139
139
  export async function readHeartbeatStagingFacts(options) {
@@ -348,11 +348,11 @@ export function localSubcommandHelp(command) {
348
348
  "Usage: cockpit clean [--dry-run] [--all-committed] [--reconcile] [--dashboard-url <url>] [--json]",
349
349
  "",
350
350
  "Reclaims this machine's disk. Prints what it would delete and why, per bucket,",
351
- "then deletes: staged evidence Tower has already accepted goes after a 48-hour",
352
- "retry window, and anything the upload ledger has NOT vouched for is kept,",
351
+ "then deletes: a staged copy Tower has already accepted goes (a retry re-reads",
352
+ "the source file), and anything the upload ledger has NOT vouched for is kept,",
353
353
  "counted and named — retention never deletes undelivered evidence.",
354
- "--dry-run stops after the printing. --all-committed drops the retry window,",
355
- "so every already-accepted copy goes now, and is the only thing that removes a",
354
+ "--dry-run stops after the printing. --all-committed drops any retry window set",
355
+ "with COCKPIT_STAGING_RETENTION_HOURS, so every already-accepted copy goes now, and is the only thing that removes a",
356
356
  "manual-study-evidence-vault folder (and only when every file in it is accepted).",
357
357
  "--reconcile asks Tower's own upload ledger about every object this machine's",
358
358
  "local memory can no longer classify (\"unknown\") before the buckets print — a",
@@ -361,9 +361,9 @@ export function localSubcommandHelp(command) {
361
361
  "object instead of \"unknown\". A server failure never blocks the rest of clean",
362
362
  "and is printed on its own line. Combine with --dry-run to ask and print",
363
363
  "without deleting.",
364
- "The scheduled sync does the same prune once a day (reconciling one batch first",
365
- "when there is anything unknown); this is the door for a laptop that is full",
366
- "right now.",
364
+ "The scheduled sync does the same prune on every tick (reconciling one batch first",
365
+ "when there is anything unknown); this is the door for \"show me\" and for a",
366
+ "laptop that has been off.",
367
367
  ],
368
368
  ],
369
369
  [
@@ -21,7 +21,7 @@ export async function runCockpitCli(argv, io) {
21
21
  }
22
22
 
23
23
  if (command === "--version" || command === "-V" || command === "version") {
24
- writeLine(io?.stdout ?? process.stdout, "0.2.154");
24
+ writeLine(io?.stdout ?? process.stdout, "0.2.156");
25
25
  return 0;
26
26
  }
27
27
 
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `cockpit status`'s `Disk:` line (BLI-11106): the same footprint line
3
+ * `cockpit doctor`'s disk row opens with, so a person who pastes `status` into
4
+ * Slack also pastes what the collector holds on disk and when it last cleaned
5
+ * up. Human output only; `status --json` is unchanged. Split out of
6
+ * `status.ts` to keep that file under the readability ratchet.
7
+ */
8
+ import { footprintLine } from "./doctor-disk-words.js";
9
+ import { readDiskFootprint } from "../disk-usage.js";
10
+ import { describeError } from "../health-detail.js";
11
+ import { getCollectorRuntimePaths } from "../local-state.js";
12
+ /** Never throws: an unreadable footprint is a named line, not a failed status. */
13
+ export async function statusDiskLine(homeDir) {
14
+ try {
15
+ const footprint = await readDiskFootprint(getCollectorRuntimePaths(homeDir));
16
+ return `Disk: ${footprintLine(footprint)}`;
17
+ }
18
+ catch (error) {
19
+ console.error("[cockpit-status] could not read the disk footprint", JSON.stringify({ reason: "footprint_read_failed", ...describeError(error) }));
20
+ return "Disk: could not be read (footprint_read_failed)";
21
+ }
22
+ }
@@ -22,6 +22,7 @@ import { displayTicketId, displayWorkLabel, shortSha, stuckEvidenceLine, } from
22
22
  import { discoverCommandWorktrees } from "./local-discovery.js";
23
23
  import { refreshSetupReceipt } from "./setup-receipt.js";
24
24
  import { setupReceiptBlock } from "./setup-receipt-lines.js";
25
+ import { statusDiskLine } from "./status-disk-line.js";
25
26
  import { defaultCodexSessionDirs } from "../adapters/codex-attribution.js";
26
27
  import { describeError } from "../health-detail.js";
27
28
  import { backfillCompletionCovers, emptyBackfillCursorState, prepareBackfillCursorForScope, readBackfillCompletionMarker, readBackfillCursor, } from "../cursors/backfill-cursor.js";
@@ -77,6 +78,7 @@ async function writeMultiRepoStatus(command, io, backfillCursor, setupReceipt, w
77
78
  return writeMultiRepoJson(io, backfillCursor, setupReceipt, statuses);
78
79
  writeLine(io.stdout, "Tower status — every repo below this folder");
79
80
  writeLine(io.stdout, `Old sessions: ${backfillCursorLine(backfillCursor)}`);
81
+ writeLine(io.stdout, await statusDiskLine(command.homeDir));
80
82
  for (const status of statuses) {
81
83
  writeLine(io.stdout, `- ${status.repo_label ?? status.repo}/${status.worktree_label ?? "worktree"} · ${status.branch} · head:${shortSha(status.head_sha)} · ${status.upload_state}`);
82
84
  }
@@ -108,14 +110,14 @@ async function writeSingleRepoStatus(command, io, backfillCursor, setupReceipt)
108
110
  });
109
111
  if (command.json)
110
112
  return writeSingleRepoJson(io, status, backfillCursor, setupReceipt);
111
- writeSingleRepoLines(io, status, backfillCursor, setupReceipt);
113
+ writeSingleRepoLines(io, status, backfillCursor, setupReceipt, await statusDiskLine(command.homeDir));
112
114
  return 0;
113
115
  }
114
116
  function writeSingleRepoJson(io, status, backfillCursor, setupReceipt) {
115
117
  writeLine(io.stdout, JSON.stringify({ ...status, backfill_cursor: backfillCursor, setup_receipt: setupReceipt?.receipt ?? null }, null, 2));
116
118
  return 0;
117
119
  }
118
- function writeSingleRepoLines(io, status, backfillCursor, setupReceipt) {
120
+ function writeSingleRepoLines(io, status, backfillCursor, setupReceipt, disk) {
119
121
  writeLine(io.stdout, "Tower status");
120
122
  writeLine(io.stdout, `Installed: ${status.installed ? "yes" : "no"}`);
121
123
  writeLine(io.stdout, `Signed in: ${signedInLine(status.session_state)}`);
@@ -142,6 +144,7 @@ function writeSingleRepoLines(io, status, backfillCursor, setupReceipt) {
142
144
  writeLine(io.stdout, `Last health note problem: ${status.last_health_receipt_failure_reason ?? "none"}`);
143
145
  writeLine(io.stdout, `Old sessions: ${backfillCursorLine(backfillCursor)}`);
144
146
  writeLine(io.stdout, `Stuck files: ${stuckEvidenceLine(status)}`);
147
+ writeLine(io.stdout, disk);
145
148
  for (const detail of status.details)
146
149
  writeLine(io.stdout, `- ${detail}`);
147
150
  writeConnectedBlock(io, setupReceipt);
@@ -10,9 +10,11 @@ const RECONCILE_BATCHES_PER_TICK = 1;
10
10
  * laptop forever.
11
11
  *
12
12
  * Same shape as the memory install beside it and for the same reasons: it runs
13
- * only once collection's own outcome is decided and reported, at most once a
14
- * day, it cannot throw, and its outcome is its own named receipt rather than a
15
- * sync failure. A machine that cannot prune is a machine short of disk, and
13
+ * only once collection's own outcome is decided and reported, it cannot throw,
14
+ * and its outcome is its own named receipt rather than a sync failure. Unlike
15
+ * the memory install it runs on EVERY tick (BLI-11106): the upload above has
16
+ * just recorded which objects the server committed, and their staged copies
17
+ * go in this same tick rather than a day or two later. A machine that cannot prune is a machine short of disk, and
16
18
  * that must never also be a machine that stops collecting.
17
19
  *
18
20
  * The rule itself is `disk-retention.ts`: only objects the upload ledger
@@ -24,7 +26,7 @@ const RECONCILE_BATCHES_PER_TICK = 1;
24
26
  * ledger's own memory is capped, so a laptop that keeps accumulating
25
27
  * `unknown` state needs SOMETHING asking the server on a schedule, not only
26
28
  * when a person happens to type `cockpit clean --reconcile`. One batch a tick
27
- * is not throttled to once a day like the prune below — an `unknown` backlog
29
+ * is bounded to one batch rather than drained whole — an `unknown` backlog
28
30
  * drains at up to 500 hashes/15 min, and the ordinary case (nothing unknown)
29
31
  * costs one cheap local read and no network call at all, so it never competes
30
32
  * with collection for the tick's time. A reconcile failure never blocks the
@@ -59,9 +61,10 @@ export async function runStagingPruneAfterSync(command, io, dashboardUrl, option
59
61
  detail: redactedSyncErrorDetail(error),
60
62
  }));
61
63
  }
62
- // The daily throttle is the steady state — reporting it would post a receipt
63
- // on 95 of every 96 ticks for no new information.
64
- if (result.reason !== "throttled_recent_run") {
64
+ // A tick with nothing to prune is the steady state: `[collector prune]`
65
+ // already logged it locally with the bytes scanned, and posting a receipt on
66
+ // 95 of every 96 ticks would say nothing new.
67
+ if (result.reason !== "nothing_to_prune") {
65
68
  events.push(stagingPruneEvent(result));
66
69
  }
67
70
  if (events.length === 0)
@@ -78,8 +81,8 @@ export async function runStagingPruneAfterSync(command, io, dashboardUrl, option
78
81
  /**
79
82
  * Never throws (`runEvidenceReconcile` already never does); returns `null`
80
83
  * for the boring, common case — nothing this tick was `unknown` — so that
81
- * case costs no receipt either, the same rule the prune's own daily throttle
82
- * follows above.
84
+ * case costs no receipt either, the same rule the prune's own
85
+ * `nothing_to_prune` follows above.
83
86
  */
84
87
  async function runReconcileFollowUp(command, io, dashboardUrl, options) {
85
88
  const result = await runEvidenceReconcile({
@@ -102,7 +105,7 @@ async function runReconcileFollowUp(command, io, dashboardUrl, options) {
102
105
  * Never throws (`runEvidenceRedelivery` already never does); returns `null` for
103
106
  * the boring, common case — nothing on this disk is undelivered — so the steady
104
107
  * state costs no receipt, the same rule the reconcile follow-up above and the
105
- * prune's daily throttle below both follow.
108
+ * prune's `nothing_to_prune` below both follow.
106
109
  */
107
110
  async function runRedeliveryFollowUp(command, io, dashboardUrl, options) {
108
111
  const result = await runEvidenceRedelivery({
@@ -24,8 +24,10 @@
24
24
  *
25
25
  * Both arms below do the same things in the same order, because a tick that
26
26
  * THREW is still a tick a machine survived and the fleet has to be able to tell
27
- * that from silence (BLI-3551). The one difference is the staging prune, which
28
- * the throwing arm has never run.
27
+ * that from silence (BLI-3551). Both arms also run the staging prune: a tick
28
+ * that threw after uploading still leaves committed copies the prune may take,
29
+ * and waiting for the next clean tick is how a sick machine fills its disk
30
+ * (BLI-11106).
29
31
  *
30
32
  * Split out of commands/local.ts (BLI-3578), then into the siblings above
31
33
  * (BLI-3982). The scan and upload engine underneath is `./session-sync.ts`;
@@ -78,8 +80,8 @@ export async function runSync(command, io) {
78
80
  await sendSyncHeartbeat(command, io, dashboardUrl, result.heartbeat);
79
81
  await reportTickOutcome(command, io, dashboardUrl, result.completion);
80
82
  await convergeAfterTick(command, io, dashboardUrl);
81
- // BLI-3619: and the disk stops growing without bound — same daily cadence,
82
- // same rule that a follow-up never blocks or fails collection.
83
+ // BLI-3619 / BLI-11106: every tick, the staged copies of whatever the
84
+ // server just committed go; a follow-up never blocks or fails collection.
83
85
  await runStagingPruneAfterSync(command, io, dashboardUrl);
84
86
  return result.exitCode;
85
87
  }
@@ -94,6 +96,7 @@ export async function runSync(command, io) {
94
96
  });
95
97
  await reportTickThrew(command, io, dashboardUrl, error, errorCode);
96
98
  await convergeAfterTick(command, io, dashboardUrl);
99
+ await runStagingPruneAfterSync(command, io, dashboardUrl);
97
100
  throw error;
98
101
  }
99
102
  }
@@ -195,8 +195,21 @@ function parseSessionEntry(value) {
195
195
  uploaded_at: optionalString(record["uploaded_at"]),
196
196
  uploaded_byte_size: optionalNumberOrNull(record["uploaded_byte_size"]),
197
197
  last_seen_at: lastSeenAt,
198
+ ...parseStubReoffer(record["stub_reoffer"]),
198
199
  };
199
200
  }
201
+ function parseStubReoffer(value) {
202
+ if (!value || typeof value !== "object")
203
+ return {};
204
+ const record = value;
205
+ const markedAt = optionalString(record["marked_at"]);
206
+ const ids = Array.isArray(record["stub_pointer_ids"])
207
+ ? record["stub_pointer_ids"].filter((id) => typeof id === "string" && id.length > 0)
208
+ : [];
209
+ if (record["reason"] !== "stub_reoffered" || !markedAt || ids.length === 0)
210
+ return {};
211
+ return { stub_reoffer: { reason: "stub_reoffered", stub_pointer_ids: ids, marked_at: markedAt } };
212
+ }
200
213
  function parseCheckpoints(value) {
201
214
  if (!value || typeof value !== "object")
202
215
  return null;
@@ -15,19 +15,25 @@
15
15
  * evidence that the drain is still running at all (the BLI-2528 lesson: what
16
16
  * only speaks on failure cannot answer "did anything work today?").
17
17
  *
18
- * Throttled to once a day by a marker file, the same idiom the raw-evidence GC,
19
- * the scheduled self-update and the BLI Memory install use. Walking a pack tree
20
- * is cheap; doing it every fifteen minutes for a decision that changes on the
21
- * scale of hours is not.
18
+ * Runs on EVERY tick (BLI-11106). It used to sit behind a once-a-day marker
19
+ * file, and that is how 534 MB of committed, past-window copies were still on
20
+ * the reference Mac when it was measured: the drain existed and had not run
21
+ * yet. The inventory reads each pack's small `manifest.json` rather than its
22
+ * payload, so a tick with nothing to delete costs one directory walk and logs
23
+ * `nothing_to_prune` with the bytes it scanned. `COCKPIT_DISABLE_GC=1` is the
24
+ * only off switch.
25
+ *
26
+ * Every non-dry run leaves `last-prune.json` (one small object, overwritten)
27
+ * so `cockpit doctor` and `cockpit status` can say when it last ran and what
28
+ * it freed without re-running it.
22
29
  */
23
30
  import fs from "node:fs/promises";
24
31
  import path from "node:path";
25
32
  import { planStagingRetention, retentionOptionsFromEnv, } from "./disk-retention.js";
26
33
  import { RAW_EVIDENCE_DIR, readStagingInventory } from "./disk-usage.js";
27
34
  import { describeError } from "./health-detail.js";
35
+ import { writeLastPruneReceipt } from "./prune-receipt.js";
28
36
  import { readRawEvidenceStagingState, writeRawEvidenceStagingState, } from "./raw-evidence-staging.js";
29
- export const STAGING_PRUNE_THROTTLE_MARKER = ".last-staging-prune";
30
- export const STAGING_PRUNE_MIN_INTERVAL_MS = 24 * 60 * 60 * 1000;
31
37
  /**
32
38
  * The prune the sync tick runs and `cockpit clean` / `cockpit doctor` reuse.
33
39
  * Never throws.
@@ -38,17 +44,14 @@ export async function runStagingPrune(paths, options = {}) {
38
44
  if (env["COCKPIT_DISABLE_GC"] === "1") {
39
45
  return skippedResult("disabled");
40
46
  }
41
- if (!options.force && (await prunedRecently(paths, now))) {
42
- return skippedResult("throttled_recent_run");
43
- }
44
47
  try {
45
- if (!options.dryRun && !options.force)
46
- await markPruned(paths, now);
47
48
  const plan = await planFromDisk(paths, env, options, now);
48
49
  const result = options.dryRun
49
50
  ? dryRunResult(plan)
50
51
  : await applyPlan(paths, plan);
51
52
  reportPrune(result, { dryRun: Boolean(options.dryRun) });
53
+ if (!options.dryRun)
54
+ await writeLastPruneReceipt(paths, result, now);
52
55
  return result;
53
56
  }
54
57
  catch (error) {
@@ -75,7 +78,7 @@ async function applyPlan(paths, plan) {
75
78
  return {
76
79
  ...dryRunResult(plan),
77
80
  status: "ok",
78
- reason: tally.files > 0 ? "pruned" : "nothing_eligible",
81
+ reason: tally.files > 0 || tally.packs > 0 ? "pruned" : "nothing_to_prune",
79
82
  deleted_files: tally.files,
80
83
  deleted_bytes: tally.bytes,
81
84
  removed_packs: tally.packs,
@@ -166,7 +169,9 @@ async function forgetStagedObjects(paths, hashes) {
166
169
  function dryRunResult(plan) {
167
170
  return {
168
171
  status: "ok",
169
- reason: plan.delete.length > 0 ? "would_prune" : "nothing_eligible",
172
+ reason: plan.delete.length > 0 || plan.empty_packs.length > 0
173
+ ? "would_prune"
174
+ : "nothing_to_prune",
170
175
  deleted_files: plan.delete.length,
171
176
  deleted_bytes: plan.deleted_bytes + plan.empty_pack_manifest_bytes,
172
177
  removed_packs: plan.empty_packs.length,
@@ -221,6 +226,7 @@ export function reportPrune(result, options = { dryRun: false }) {
221
226
  kept_unknown: result.kept_unknown,
222
227
  kept_in_window: result.kept_in_window,
223
228
  cap_bytes: result.cap_bytes,
229
+ bytes_scanned: result.bytes_before,
224
230
  bytes_after: result.bytes_after,
225
231
  failed_deletions: result.failed_deletions,
226
232
  }));
@@ -234,14 +240,4 @@ export function reportPrune(result, options = { dryRun: false }) {
234
240
  cap_bytes: result.cap_bytes,
235
241
  bytes_after: result.bytes_after,
236
242
  }));
237
- }
238
- async function prunedRecently(paths, now) {
239
- const marker = path.join(paths.state_dir, STAGING_PRUNE_THROTTLE_MARKER);
240
- const info = await fs.stat(marker).catch(() => null);
241
- return Boolean(info && now.getTime() - info.mtimeMs < STAGING_PRUNE_MIN_INTERVAL_MS);
242
- }
243
- async function markPruned(paths, now) {
244
- const marker = path.join(paths.state_dir, STAGING_PRUNE_THROTTLE_MARKER);
245
- await fs.mkdir(paths.state_dir, { recursive: true }).catch(() => undefined);
246
- await fs.writeFile(marker, now.toISOString()).catch(() => undefined);
247
243
  }
@@ -1,7 +1,10 @@
1
- /** How long a committed spare is kept so a retry still has local bytes. */
2
- export const DEFAULT_STAGING_RETENTION_MS = 48 * 60 * 60 * 1000;
1
+ /**
2
+ * How long a committed spare is kept: zero (BLI-11106). A retry re-reads the
3
+ * source file, so the staged copy of a committed object is pure duplication.
4
+ */
5
+ export const DEFAULT_STAGING_RETENTION_MS = 0;
3
6
  /** Ceiling on everything under `raw-evidence`, manifests included. */
4
- export const DEFAULT_STAGING_CAP_BYTES = 2 * 1024 * 1024 * 1024;
7
+ export const DEFAULT_STAGING_CAP_BYTES = 256 * 1024 * 1024;
5
8
  /** Local knobs, read from the environment like `COCKPIT_DISABLE_GC`. */
6
9
  export const STAGING_CAP_ENV = "COCKPIT_STAGING_CAP_BYTES";
7
10
  export const STAGING_RETENTION_ENV = "COCKPIT_STAGING_RETENTION_HOURS";
@@ -33,7 +36,7 @@ export function planStagingRetention(inventory, options = {}) {
33
36
  continue;
34
37
  }
35
38
  if (options.allCommitted || object.age_ms >= retentionMs) {
36
- pushDeletion(plan, object, "committed_past_retry_window");
39
+ pushDeletion(plan, object, "committed_on_server");
37
40
  continue;
38
41
  }
39
42
  committedInWindow.push(object);
@@ -61,11 +64,11 @@ export function planStagingRetention(inventory, options = {}) {
61
64
  * safe elsewhere.
62
65
  *
63
66
  * It does not run at all when the floor is already above the cap. That branch
64
- * is not theoretical: on the reference Mac (2026-09-05) 8.0 GB of staging is
65
- * evidence no ledger vouches for, against a 2 GB cap, so spending the retry
66
- * window on 1,027 committed spares would have deleted a day of local retry
67
- * copies and still ended over the cap. The cap takes a spare only when taking
68
- * it can actually get this machine under the cap.
67
+ * is not theoretical: on the reference Mac (2026-09-05) 8.0 GB of staging was
68
+ * evidence no ledger vouched for, against the cap of the day. With the default
69
+ * zero window it rarely matters (committed spares are already gone); it keeps
70
+ * an opted-in window honest by taking a spare only when that can actually get
71
+ * this machine under the cap.
69
72
  */
70
73
  function applyByteCap(plan, committedInWindow, capBytes, inventory) {
71
74
  let projected = plan.bytes_before - plan.deleted_bytes;
@@ -1,9 +1,11 @@
1
1
  /**
2
- * The whole-machine read: staging, rotated logs, the spool, and the vaults a
3
- * person made by hand — the four places Cockpit ever writes bytes on a laptop.
2
+ * The whole-machine read: staging, rotated logs, the spool, the vaults a
3
+ * person made by hand, and (BLI-11106) the rest of the state directory plus
4
+ * the last prune's receipt.
4
5
  *
5
- * The staging half is the rest of this family; what lives here is the other
6
- * three and the one function that puts all four together.
6
+ * The staging half is the rest of this family; the state-dir audit is
7
+ * `state-dir-audit.ts` and the receipt `prune-receipt.ts`. What lives here is
8
+ * the one function that puts them together.
7
9
  */
8
10
  import fs from "node:fs/promises";
9
11
  import path from "node:path";
@@ -11,6 +13,8 @@ import { MANUAL_VAULT_PREFIX, } from "./disk-usage-facts.js";
11
13
  import { directoryBytes, listPackFiles } from "./disk-usage-files.js";
12
14
  import { readStagingInventory } from "./disk-usage-scan.js";
13
15
  import { rotatedLogFootprint } from "./log-rotation.js";
16
+ import { readLastPruneReceipt } from "./prune-receipt.js";
17
+ import { readStateDirFootprint } from "./state-dir-audit.js";
14
18
  /**
15
19
  * Everything on this machine Cockpit put there, in one read. Used by the sync
16
20
  * tick's prune, by `cockpit clean` and by `cockpit doctor`'s disk row, so all
@@ -22,6 +26,8 @@ export async function readDiskFootprint(paths, now = new Date()) {
22
26
  logs: await rotatedLogFootprint(paths),
23
27
  spool_bytes: await directoryBytes(paths.spool_dir),
24
28
  vaults: await readManualVaults(paths),
29
+ state: await readStateDirFootprint(paths),
30
+ last_prune: await readLastPruneReceipt(paths),
25
31
  };
26
32
  }
27
33
  /** The hand-made vaults: counted and named so nothing deletes them silently. */
@@ -35,8 +35,8 @@ export async function runEvidenceReconcile(options) {
35
35
  if (hashes.length === 0) {
36
36
  // No stderr line here on purpose: the sync tick calls this every 15
37
37
  // minutes and the steady state is "nothing unknown" — logging that
38
- // every tick forever is exactly the receipt-on-95-of-96-ticks spam the
39
- // daily prune throttle exists to avoid. `cockpit clean --reconcile`
38
+ // every tick forever is exactly the receipt-on-95-of-96-ticks spam that
39
+ // the follow-ups skip on their `nothing_*` reasons. `cockpit clean --reconcile`
40
40
  // still tells a person this on stdout (`reconcileLines` in clean.ts).
41
41
  return emptyResult("nothing_unknown");
42
42
  }