@aryasaatvik/scratchpad 0.6.2 → 0.7.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.
@@ -29725,6 +29725,7 @@ var DEFAULT_LAYOUT = {
29725
29725
  files: ["README.md", "STATE.md"]
29726
29726
  };
29727
29727
  var MaxAgeDays = Number6.check(isGreaterThan3(0));
29728
+ var Megabytes = Number6.check(isGreaterThan3(0));
29728
29729
  var LifecycleConfig = Struct({
29729
29730
  notes: optional2(Struct({
29730
29731
  autoTrashConfidence: optional2(Number6.check(isBetween2({ minimum: 0, maximum: 1 }))),
@@ -29735,9 +29736,15 @@ var LifecycleConfig = Struct({
29735
29736
  maxAgeDays: optional2(MaxAgeDays),
29736
29737
  overrides: optional2(ArraySchema(Struct({ path: String5, maxAgeDays: MaxAgeDays })))
29737
29738
  })),
29739
+ storage: optional2(Struct({
29740
+ budgetMB: optional2(Megabytes),
29741
+ bulkMB: optional2(Megabytes)
29742
+ })),
29738
29743
  protect: optional2(ArraySchema(String5))
29739
29744
  });
29740
29745
  var DEFAULT_ARTIFACT_MAX_AGE_DAYS = 14;
29746
+ var DEFAULT_STORAGE_BUDGET_MB = 1024;
29747
+ var DEFAULT_BULK_MB = 5;
29741
29748
  var Config = Struct({
29742
29749
  repo: String5,
29743
29750
  mounts: ArraySchema(ProviderMount),
@@ -46883,8 +46890,16 @@ var prepareMounts = fn2("Sync.prepareMounts")(function* (input, store, dryRun) {
46883
46890
  };
46884
46891
  return { config, store: scopeWrites(view) };
46885
46892
  });
46886
- var validateMountDirectories = fn2("Sync.validateMountDirectories")(function* (config, store) {
46893
+ var RESTORE_MOUNT_COMMAND = "scratchpad pull --full";
46894
+ var RESTORE_MARKER = ".scratchpad-restore-pending";
46895
+ var unfinishedRestoreMessage = (directory) => `Mount directory ${directory} has an unfinished restore; refusing to plan closes or archives. Run \`${RESTORE_MOUNT_COMMAND}\` to finish it.`;
46896
+ var missingMountMessage = (directory, count) => `Mount directory ${directory} is missing with ${count} stored mapping(s); refusing to plan closes or archives. Run \`${RESTORE_MOUNT_COMMAND}\` to recreate it from the provider (preview with \`${RESTORE_MOUNT_COMMAND} --dry-run\`).`;
46897
+ var validateMountDirectories = fn2("Sync.validateMountDirectories")(function* (config, store, options = {
46898
+ restore: false,
46899
+ dryRun: false
46900
+ }) {
46887
46901
  const fs = yield* FileSystem;
46902
+ const restored = [];
46888
46903
  for (const mount of config.mounts) {
46889
46904
  for (const [kind, directory] of [
46890
46905
  ["issue", mount.issues],
@@ -46894,19 +46909,37 @@ var validateMountDirectories = fn2("Sync.validateMountDirectories")(function* (c
46894
46909
  message: `Cannot inspect mount directory ${directory}. Restore access before syncing.`,
46895
46910
  cause
46896
46911
  }))));
46897
- if (info?.type === "Directory")
46912
+ if (info?.type === "Directory") {
46913
+ const marker = yield* fs.exists(join6(directory, RESTORE_MARKER)).pipe(mapError2((cause) => new MountError({
46914
+ message: `Cannot inspect mount directory ${directory}. Restore access before syncing.`,
46915
+ cause
46916
+ })));
46917
+ if (!marker)
46918
+ continue;
46919
+ if (!options.restore)
46920
+ return yield* new MountError({ message: unfinishedRestoreMessage(directory) });
46921
+ yield* logWarning(`pull: finishing an interrupted restore of ${directory}`);
46922
+ restored.push(directory);
46898
46923
  continue;
46924
+ }
46899
46925
  if (info !== undefined)
46900
46926
  return yield* new MountError({
46901
46927
  message: `Mount path ${directory} is not a directory. Restore the directory before syncing; refusing to plan closes or archives.`
46902
46928
  });
46903
46929
  const mappings = yield* store.listMappings(kind, directory);
46904
- if (mappings.length > 0)
46905
- return yield* new MountError({
46906
- message: `Mount directory ${directory} is missing with ${mappings.length} stored mapping(s). Restore the directory or run scratchpad repair before syncing; refusing to plan closes or archives.`
46907
- });
46930
+ if (mappings.length === 0)
46931
+ continue;
46932
+ if (!options.restore)
46933
+ return yield* new MountError({ message: missingMountMessage(directory, mappings.length) });
46934
+ yield* logWarning(`pull: ${options.dryRun ? "would restore" : "restoring"} missing mount directory ${directory} (${mappings.length} stored mapping(s)) from the provider`);
46935
+ restored.push(directory);
46908
46936
  }
46909
46937
  }
46938
+ return restored;
46939
+ });
46940
+ var missingMountError = (directory, count, cause) => new MountError({
46941
+ message: missingMountMessage(directory, count),
46942
+ ...cause === undefined ? {} : { cause }
46910
46943
  });
46911
46944
 
46912
46945
  // packages/core/src/sync/engine.ts
@@ -46932,15 +46965,16 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
46932
46965
  ...slugValue === undefined ? {} : { issueSlug: slugValue }
46933
46966
  });
46934
46967
  const renderMilestone = (doc) => renderMilestoneFile(doc, frontmatterOptions);
46935
- const listSlugs = (dir) => fs.readDirectory(dir, { recursive: true }).pipe(map6((names) => names.map((name) => name.replaceAll("\\", "/")).filter((name) => name.endsWith(".md")).map((name) => name.slice(0, -3))), catch_2((cause) => gen3(function* () {
46968
+ const listSlugs = (dir, restoring = false) => fs.readDirectory(dir, { recursive: true }).pipe(map6((names) => names.map((name) => name.replaceAll("\\", "/")).filter((name) => name.endsWith(".md")).map((name) => name.slice(0, -3))), catch_2((cause) => gen3(function* () {
46936
46969
  if (cause.reason._tag === "NotFound" && !(yield* fs.exists(dir))) {
46937
46970
  const mount = path.resolve(dir);
46938
46971
  const mappings = [
46939
46972
  ...yield* store.listMappings("issue", mount),
46940
46973
  ...yield* store.listMappings("milestone", mount)
46941
46974
  ];
46942
- if (mappings.length === 0)
46975
+ if (mappings.length === 0 || restoring)
46943
46976
  return [];
46977
+ return yield* missingMountError(dir, mappings.length, cause);
46944
46978
  }
46945
46979
  return yield* new MountError({
46946
46980
  message: `Cannot scan mount directory ${dir}. Restore the directory and read access before syncing; refusing to plan closes or archives.`,
@@ -47124,10 +47158,11 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
47124
47158
  const localized = opts.localize === undefined ? listed : listed.map((doc) => opts.localize(doc, ""));
47125
47159
  const remotes = localized.map(opts.prepare);
47126
47160
  const seen = new Set;
47127
- for (const existing of yield* listSlugs(opts.mountDir))
47161
+ for (const existing of yield* listSlugs(opts.mountDir, opts.full))
47128
47162
  seen.add(existing);
47129
47163
  const archiveKey = opts.archive === undefined ? undefined : path.resolve(opts.archive.dir);
47130
47164
  const archiveSeen = new Set;
47165
+ const archiveProjected = new Set;
47131
47166
  const archiveSlugByExternalId = new Map;
47132
47167
  if (opts.archive !== undefined && archiveKey !== undefined) {
47133
47168
  const archiveFiles = yield* fs.readDirectory(opts.archive.dir).pipe(orElseSucceed2(() => []));
@@ -47229,7 +47264,7 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
47229
47264
  const archiveAbs = path.resolve(path.join(opts.archive.dir, `${archiveSlug}.md`));
47230
47265
  const archiveHash = contentHash(remote.frontmatter, remote.body);
47231
47266
  const archiveMapping = yield* store.getObjectMapping(opts.kind, archiveKey, archiveSlug);
47232
- if (archiveMapping?.contentHash !== archiveHash) {
47267
+ if (archiveMapping?.contentHash !== archiveHash || opts.full && !(yield* fs.exists(archiveAbs))) {
47233
47268
  if (!opts.dryRun) {
47234
47269
  const local = opts.preserveLocal === undefined || !(yield* fs.exists(archiveAbs)) ? undefined : yield* readExisting(archiveAbs);
47235
47270
  yield* writeDoc(archiveAbs, renderRemote(remote, local, archiveSlug));
@@ -47247,6 +47282,7 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
47247
47282
  syncStatus: "archived"
47248
47283
  });
47249
47284
  }
47285
+ archiveProjected.add(archiveSlug);
47250
47286
  actions.push({
47251
47287
  kind: opts.kind,
47252
47288
  slug: archiveSlug,
@@ -47353,6 +47389,8 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
47353
47389
  if (opts.archive !== undefined && archiveKey !== undefined) {
47354
47390
  const archived = yield* store.listMappings(opts.kind, archiveKey);
47355
47391
  for (const mapping of archived) {
47392
+ if (archiveProjected.has(mapping.slug))
47393
+ continue;
47356
47394
  const fileAbs = path.resolve(path.join(opts.archive.dir, `${mapping.slug}.md`));
47357
47395
  const exists = yield* fs.exists(fileAbs);
47358
47396
  if (exists) {
@@ -47381,6 +47419,25 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
47381
47419
  });
47382
47420
  }
47383
47421
  }
47422
+ if (opts.full) {
47423
+ const listedIds = new Set(remotes.flatMap((remote) => {
47424
+ const id = remote.frontmatter.providerRef?.externalId;
47425
+ return id === undefined ? [] : [id];
47426
+ }));
47427
+ for (const mapping of backlogMappings) {
47428
+ if (mapping.externalId === null || mapping.syncStatus === "closed" || mapping.syncStatus === "conflict" || listedIds.has(mapping.externalId) || (yield* fs.exists(mappingPath(mapping))) || (yield* store.pendingOutboxExists(opts.kind, mountKey, mapping.slug)))
47429
+ continue;
47430
+ if (!opts.dryRun)
47431
+ yield* store.putObjectMapping({ ...mapping, syncStatus: "closed" });
47432
+ actions.push({
47433
+ kind: opts.kind,
47434
+ slug: mapping.slug,
47435
+ externalId: mapping.externalId,
47436
+ op: "retire",
47437
+ reason: "remote-missing"
47438
+ });
47439
+ }
47440
+ }
47384
47441
  if (!opts.dryRun && maxUpdated !== undefined) {
47385
47442
  yield* store.putSyncCursor({
47386
47443
  provider: "github",
@@ -47872,14 +47929,38 @@ class SyncEngine extends Service()("@scratchpad/SyncEngine") {
47872
47929
  const config = yield* ProjectConfig;
47873
47930
  const fs = yield* FileSystem;
47874
47931
  const path = yield* Path;
47875
- const build = (dryRun, validateDirectories = false) => prepareMounts(config, store, dryRun).pipe(provideService2(FileSystem, fs), flatMap3((prepared) => SyncEngine.make.pipe(tap2(() => validateDirectories ? validateMountDirectories(prepared.config, prepared.store).pipe(provideService2(FileSystem, fs)) : void_3), provideService2(Provider, provider), provideService2(ProjectionStore, prepared.store), provideService2(ProjectConfig, prepared.config), provideService2(FileSystem, fs), provideService2(Path, path))));
47932
+ const build = (dryRun, directories = "skip") => prepareMounts(config, store, dryRun).pipe(provideService2(FileSystem, fs), flatMap3((prepared) => gen3(function* () {
47933
+ const engine = yield* SyncEngine.make.pipe(provideService2(Provider, provider), provideService2(ProjectionStore, prepared.store), provideService2(ProjectConfig, prepared.config), provideService2(FileSystem, fs), provideService2(Path, path));
47934
+ const restoring = directories === "skip" ? [] : yield* validateMountDirectories(prepared.config, prepared.store, {
47935
+ restore: directories === "restore",
47936
+ dryRun
47937
+ }).pipe(provideService2(FileSystem, fs));
47938
+ return { engine, restoring };
47939
+ })));
47940
+ const mountFailure = (directory) => (cause) => new MountError({ message: `Could not restore mount directory ${directory}`, cause });
47941
+ const restoreNote = "A `scratchpad pull --full` restore of this directory has not finished. Re-run it; sync and push refuse until it succeeds.\n";
47942
+ const markRestoring = (directories) => forEach2(directories, (directory) => gen3(function* () {
47943
+ if (yield* fs.exists(directory)) {
47944
+ yield* fs.writeFileString(path.join(directory, RESTORE_MARKER), restoreNote);
47945
+ return;
47946
+ }
47947
+ const parent = path.dirname(directory);
47948
+ yield* fs.makeDirectory(parent, { recursive: true });
47949
+ const staging = yield* fs.makeTempDirectory({
47950
+ directory: parent,
47951
+ prefix: `.${path.basename(directory)}.restoring-`
47952
+ });
47953
+ yield* fs.writeFileString(path.join(staging, RESTORE_MARKER), restoreNote);
47954
+ yield* fs.rename(staging, directory);
47955
+ }).pipe(mapError2(mountFailure(directory))), { discard: true });
47956
+ const finishRestoring = (directories) => forEach2(directories, (directory) => fs.remove(path.join(directory, RESTORE_MARKER), { force: true }).pipe(mapError2(mountFailure(directory))), { discard: true });
47876
47957
  return SyncEngine.of({
47877
- pull: (opts) => build(opts?.dryRun ?? false, true).pipe(flatMap3((engine) => engine.pull(opts)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47878
- push: (opts) => build(opts?.dryRun ?? false, true).pipe(flatMap3((engine) => engine.push(opts)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47879
- sync: (opts) => build(opts?.dryRun ?? false, true).pipe(flatMap3((engine) => engine.sync(opts)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47880
- deleteRemote: (file, opts) => build(opts?.dryRun ?? false).pipe(mapError2((cause) => new RemoteDeleteError({ message: cause.message, cause })), flatMap3((engine) => engine.deleteRemote(file, opts))),
47881
- listConflicts: build(true).pipe(flatMap3((engine) => engine.listConflicts), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47882
- resolveConflict: (id, resolution) => build(false).pipe(flatMap3((engine) => engine.resolveConflict(id, resolution)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error)))
47958
+ pull: (opts) => build(opts?.dryRun ?? false, opts?.full === true ? "restore" : "refuse").pipe(flatMap3(({ engine, restoring }) => opts?.dryRun === true || restoring.length === 0 ? engine.pull(opts) : markRestoring(restoring).pipe(andThen2(engine.pull(opts)), tap2(() => finishRestoring(restoring)))), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47959
+ push: (opts) => build(opts?.dryRun ?? false, "refuse").pipe(flatMap3(({ engine }) => engine.push(opts)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47960
+ sync: (opts) => build(opts?.dryRun ?? false, "refuse").pipe(flatMap3(({ engine }) => engine.sync(opts)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47961
+ deleteRemote: (file, opts) => build(opts?.dryRun ?? false).pipe(mapError2((cause) => new RemoteDeleteError({ message: cause.message, cause })), flatMap3(({ engine }) => engine.deleteRemote(file, opts))),
47962
+ listConflicts: build(true).pipe(flatMap3(({ engine }) => engine.listConflicts), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error))),
47963
+ resolveConflict: (id, resolution) => build(false).pipe(flatMap3(({ engine }) => engine.resolveConflict(id, resolution)), catch_2((error) => error instanceof MountError ? fail6(error) : die3(error)))
47883
47964
  });
47884
47965
  }));
47885
47966
  }
@@ -50748,6 +50829,14 @@ var artifactCandidates = ({ files, now, config }) => succeed6(files.flatMap((fil
50748
50829
  }
50749
50830
  ] : [];
50750
50831
  }));
50832
+ var mountedPaths = (root, config, configRoot) => (config?.mounts ?? []).flatMap((mount) => [
50833
+ mount.issues,
50834
+ mount.milestones,
50835
+ ...mount.archive === undefined ? [] : [mount.archive.issues, mount.archive.milestones]
50836
+ ].flatMap((directory) => {
50837
+ const physical = physicalMountPath(resolve10(configRoot ?? root, directory));
50838
+ return within2(root, physical) ? [relative5(root, physical)] : [];
50839
+ }));
50751
50840
  var collectCandidates = fn2("maintenance.collectCandidates")(function* (sources = [artifactCandidates]) {
50752
50841
  const project = yield* Project;
50753
50842
  const root = yield* maintenanceIO(() => realpath6(project.notesRoot).catch((error) => {
@@ -50773,19 +50862,33 @@ var collectCandidates = fn2("maintenance.collectCandidates")(function* (sources
50773
50862
  if (filePaths.has(json))
50774
50863
  protectedPaths.add(json);
50775
50864
  }
50865
+ const links = new Map;
50776
50866
  yield* maintenanceIO(async () => {
50777
50867
  for (const file of files.filter((entry) => isNote(entry.path))) {
50778
50868
  const body = await readFile4(join11(root, file.path), "utf8");
50869
+ const targets = [];
50779
50870
  for (const target of await linkedTargets(join11(root, file.path), body)) {
50780
50871
  if (within2(root, target))
50781
- protectedPaths.add(relative5(root, target));
50872
+ targets.push(relative5(root, target));
50782
50873
  }
50874
+ for (const target of targets)
50875
+ protectedPaths.add(target);
50876
+ links.set(file.path, targets);
50783
50877
  }
50784
50878
  });
50785
- const candidates = (yield* forEach2(sources, (source) => source({ root, files, now, config, ...configRoot === undefined ? {} : { configRoot } }))).flat();
50879
+ const candidates = (yield* forEach2(sources, (source) => source({
50880
+ root,
50881
+ files,
50882
+ now,
50883
+ config,
50884
+ links,
50885
+ ...configRoot === undefined ? {} : { configRoot }
50886
+ }))).flat();
50786
50887
  const unique = [...new Map(candidates.map((entry) => [entry.path, entry])).values()].sort((left, right) => left.path.localeCompare(right.path));
50888
+ const mounted = yield* maintenanceIO(async () => mountedPaths(root, config, configRoot));
50889
+ const isMounted = (path) => mounted.some((mount) => mount === "" || path === mount || path.startsWith(`${mount}/`));
50787
50890
  const isProtected = (path, source) => {
50788
- const paths = source === "notes" ? new Set(["README.md", "STATE.md", "maintenance/trash-log.md"]) : protectedPaths;
50891
+ const paths = source === "notes" || source === "bulk" ? new Set(["README.md", "STATE.md", "maintenance/trash-log.md"]) : protectedPaths;
50789
50892
  if (paths.has(""))
50790
50893
  return true;
50791
50894
  for (let current = path;current !== "."; current = dirname7(current)) {
@@ -50797,7 +50900,7 @@ var collectCandidates = fn2("maintenance.collectCandidates")(function* (sources
50797
50900
  return {
50798
50901
  root,
50799
50902
  files,
50800
- candidates: unique.filter((entry) => filePaths.has(entry.path) && !isProtected(entry.path, entry.source) && !config?.lifecycle?.protect?.some((pattern) => matches(pattern, entry.path)))
50903
+ candidates: unique.filter((entry) => filePaths.has(entry.path) && !isMounted(entry.path) && !isProtected(entry.path, entry.source) && !config?.lifecycle?.protect?.some((pattern) => matches(pattern, entry.path)))
50801
50904
  };
50802
50905
  });
50803
50906
 
@@ -51974,7 +52077,7 @@ var bundleHtml = async (options) => {
51974
52077
  // package.json
51975
52078
  var package_default = {
51976
52079
  name: "@aryasaatvik/scratchpad",
51977
- version: "0.6.2",
52080
+ version: "0.7.0",
51978
52081
  description: "Working memory for coding agents: project notes shared across worktrees, instruction feedback, note search and lifecycle cleanup, plus GitHub backlog sync, hosted artifacts and codemaps.",
51979
52082
  keywords: [
51980
52083
  "bun",
@@ -53871,8 +53974,209 @@ var deleteCommand = make39("delete", {
53871
53974
  }).pipe(json ? provideService2(MinimumLogLevel2, "None") : identity)).pipe(withDescription4("Delete a remote object through the provider (requires --remote)"));
53872
53975
 
53873
53976
  // packages/cli/src/commands/doctor.ts
53874
- import { lstat as lstat11 } from "fs/promises";
53875
- import { join as join14 } from "path";
53977
+ import { lstat as lstat12 } from "fs/promises";
53978
+ import { join as join15 } from "path";
53979
+
53980
+ // packages/cli/src/maintenance/storage.ts
53981
+ import { open as open4, readFile as readFile12 } from "fs/promises";
53982
+ import { dirname as dirname12, join as join14 } from "path";
53983
+ var MB = 1024 * 1024;
53984
+ var BUNDLE_SEGMENT = /^(?:node_modules|\.git|test-results|playwright-report|blob-report|\.next|\.turbo|.+\.(?:app|framework|xcarchive))$/iu;
53985
+ var VIDEO = /\.(?:webm|mp4|mov|mkv|avi|m4v)$/iu;
53986
+ var ARCHIVE = /\.(?:zip|tar|tgz|gz|bz2|xz|zst|7z|rar|dmg|pkg|iso|jar|asar|deb|rpm|whl|vsix)$/iu;
53987
+ var EXECUTABLE = /\.(?:exe|dll|so|dylib|node|wasm)$/iu;
53988
+ var MAGIC = [
53989
+ [127, 69, 76, 70],
53990
+ [254, 237, 250, 206],
53991
+ [254, 237, 250, 207],
53992
+ [206, 250, 237, 254],
53993
+ [207, 250, 237, 254],
53994
+ [202, 254, 186, 190]
53995
+ ];
53996
+ var bundleRoot = (path) => {
53997
+ const segments = path.split("/");
53998
+ const index = segments.slice(0, -1).findIndex((segment) => BUNDLE_SEGMENT.test(segment));
53999
+ return index === -1 ? undefined : segments.slice(0, index + 1).join("/");
54000
+ };
54001
+ var bulkKind = (path, header) => {
54002
+ if (isNote(path))
54003
+ return;
54004
+ if (bundleRoot(path) !== undefined)
54005
+ return "bundle";
54006
+ if (VIDEO.test(path))
54007
+ return "video";
54008
+ if (/\.zip$/iu.test(path) && /trace/iu.test(path) || /\.(?:trace|network|stacks)$/iu.test(path))
54009
+ return "trace";
54010
+ if (ARCHIVE.test(path))
54011
+ return "archive";
54012
+ if (EXECUTABLE.test(path))
54013
+ return "executable";
54014
+ if (header !== undefined && (MAGIC.some((magic) => magic.every((byte, index) => header[index] === byte)) || header[0] === 77 && header[1] === 90))
54015
+ return "executable";
54016
+ return;
54017
+ };
54018
+ var storageLimits = (config) => ({
54019
+ budgetBytes: (config?.lifecycle?.storage?.budgetMB ?? DEFAULT_STORAGE_BUDGET_MB) * MB,
54020
+ bulkBytes: (config?.lifecycle?.storage?.bulkMB ?? DEFAULT_BULK_MB) * MB
54021
+ });
54022
+ var readHeader = (path) => maintenanceIO(async () => {
54023
+ const handle = await open4(path, "r").catch(() => {
54024
+ return;
54025
+ });
54026
+ if (handle === undefined)
54027
+ return;
54028
+ try {
54029
+ const buffer = new Uint8Array(4);
54030
+ await handle.read(buffer, 0, 4, 0);
54031
+ return buffer;
54032
+ } finally {
54033
+ await handle.close();
54034
+ }
54035
+ });
54036
+ var flagBulk = fn2("maintenance.flagBulk")(function* (root, files, bulkBytes) {
54037
+ const bundles = new Map;
54038
+ for (const file of files) {
54039
+ const bundle = bundleRoot(file.path);
54040
+ if (bundle !== undefined)
54041
+ bundles.set(bundle, (bundles.get(bundle) ?? 0) + file.bytes);
54042
+ }
54043
+ const flagged = [];
54044
+ for (const file of files) {
54045
+ if (isNote(file.path))
54046
+ continue;
54047
+ const bundle = bundleRoot(file.path);
54048
+ if (bundle !== undefined) {
54049
+ if ((bundles.get(bundle) ?? 0) >= bulkBytes)
54050
+ flagged.push({ path: file.path, bytes: file.bytes, kind: "bundle" });
54051
+ continue;
54052
+ }
54053
+ if (file.bytes < bulkBytes)
54054
+ continue;
54055
+ const kind = bulkKind(file.path) ?? bulkKind(file.path, yield* readHeader(join14(root, file.path)));
54056
+ if (kind !== undefined)
54057
+ flagged.push({ path: file.path, bytes: file.bytes, kind });
54058
+ }
54059
+ return flagged;
54060
+ });
54061
+ var bySize = (left, right) => right.bytes - left.bytes || left.path.localeCompare(right.path);
54062
+ var storageReport = fn2("maintenance.storageReport")(function* (options) {
54063
+ const { root, files, config } = options;
54064
+ const depth = Math.max(1, options.depth ?? 2);
54065
+ const top = Math.max(1, options.top ?? 10);
54066
+ const { budgetBytes, bulkBytes } = storageLimits(config);
54067
+ const totalBytes = files.reduce((total, file) => total + file.bytes, 0);
54068
+ const folders = new Map;
54069
+ for (const file of files) {
54070
+ const segments = file.path.split("/").slice(0, -1);
54071
+ for (let level = 1;level <= Math.min(depth, segments.length); level += 1) {
54072
+ const path = segments.slice(0, level).join("/");
54073
+ const entry = folders.get(path) ?? { bytes: 0, files: 0 };
54074
+ folders.set(path, { bytes: entry.bytes + file.bytes, files: entry.files + 1 });
54075
+ }
54076
+ }
54077
+ const flagged = yield* flagBulk(root, files, bulkBytes);
54078
+ const kinds = new Map(flagged.map((file) => [file.path, file.kind]));
54079
+ const bulkEntries = new Map;
54080
+ for (const file of flagged) {
54081
+ const path = file.kind === "bundle" ? bundleRoot(file.path) : file.path;
54082
+ const entry = bulkEntries.get(path) ?? { path, bytes: 0, files: 0, kind: file.kind };
54083
+ bulkEntries.set(path, { ...entry, bytes: entry.bytes + file.bytes, files: entry.files + 1 });
54084
+ }
54085
+ return {
54086
+ version: 1,
54087
+ root,
54088
+ totalBytes,
54089
+ fileCount: files.length,
54090
+ budgetBytes,
54091
+ overBudget: totalBytes > budgetBytes,
54092
+ bulkThresholdBytes: bulkBytes,
54093
+ folders: [...folders].map(([path, entry]) => ({ path, ...entry })).sort(bySize).slice(0, top),
54094
+ files: [...files].sort(bySize).slice(0, top).map((file) => {
54095
+ const kind = kinds.get(file.path);
54096
+ return { path: file.path, bytes: file.bytes, ...kind === undefined ? {} : { kind } };
54097
+ }),
54098
+ bulk: {
54099
+ bytes: flagged.reduce((total, file) => total + file.bytes, 0),
54100
+ count: flagged.length,
54101
+ entries: [...bulkEntries.values()].sort(bySize)
54102
+ }
54103
+ };
54104
+ });
54105
+ var noteClosed = (text, closedStatuses) => parseFrontmatterData(text).pipe(map6((data) => {
54106
+ const status = typeof data === "object" && data !== null && "status" in data ? data.status : undefined;
54107
+ return typeof status === "string" && classifyStatus(status, closedStatuses) === "closed";
54108
+ }), orElseSucceed2(() => false));
54109
+ var owningRecords = (links, notes) => {
54110
+ const byTarget = new Map;
54111
+ for (const [note, targets] of links) {
54112
+ if (bundleRoot(note) !== undefined)
54113
+ continue;
54114
+ for (const target of targets)
54115
+ byTarget.set(target, [...byTarget.get(target) ?? [], note]);
54116
+ }
54117
+ return (path) => {
54118
+ const owners = new Set;
54119
+ for (let current = path;current !== "."; current = dirname12(current))
54120
+ for (const note of byTarget.get(current) ?? [])
54121
+ owners.add(note);
54122
+ for (let current = dirname12(path);current !== "."; current = dirname12(current)) {
54123
+ const readme = join14(current, "README.md");
54124
+ if (notes.has(readme) && bundleRoot(readme) === undefined) {
54125
+ owners.add(readme);
54126
+ break;
54127
+ }
54128
+ }
54129
+ return [...owners].sort();
54130
+ };
54131
+ };
54132
+ var bulkCandidates = ({ root, files, config, links }) => gen3(function* () {
54133
+ if (links === undefined)
54134
+ return [];
54135
+ const flagged = yield* flagBulk(root, files, storageLimits(config).bulkBytes);
54136
+ if (flagged.length === 0)
54137
+ return [];
54138
+ const ownersOf = owningRecords(links, new Set(files.filter((file) => isNote(file.path)).map((file) => file.path)));
54139
+ const closed = new Map;
54140
+ const isClosed = (note) => gen3(function* () {
54141
+ const cached = closed.get(note);
54142
+ if (cached !== undefined)
54143
+ return cached;
54144
+ const text = yield* maintenanceIO(() => readFile12(join14(root, note), "utf8"));
54145
+ const result = yield* noteClosed(text, config?.backlog?.closedStatuses);
54146
+ closed.set(note, result);
54147
+ return result;
54148
+ });
54149
+ const candidates = [];
54150
+ for (const file of flagged) {
54151
+ const owning = ownersOf(file.path);
54152
+ if (owning.length === 0)
54153
+ continue;
54154
+ let allClosed = true;
54155
+ for (const note of owning)
54156
+ if (!(yield* isClosed(note)))
54157
+ allClosed = false;
54158
+ if (!allClosed)
54159
+ continue;
54160
+ candidates.push({
54161
+ path: file.path,
54162
+ bytes: file.bytes,
54163
+ source: "bulk",
54164
+ reason: `${file.kind} bulk owned by closed ${owning.join(", ")}`,
54165
+ owners: owning
54166
+ });
54167
+ }
54168
+ return candidates;
54169
+ });
54170
+ var formatBytes = (bytes) => {
54171
+ const units = ["B", "KB", "MB", "GB", "TB"];
54172
+ let value = bytes;
54173
+ let unit = 0;
54174
+ while (value >= 1024 && unit < units.length - 1) {
54175
+ value /= 1024;
54176
+ unit += 1;
54177
+ }
54178
+ return unit === 0 ? `${bytes} B` : `${value.toFixed(1)} ${units[unit]}`;
54179
+ };
53876
54180
 
53877
54181
  // packages/cli/src/runtime/classifier.ts
53878
54182
  var classifierStatus = gen3(function* () {
@@ -53911,6 +54215,61 @@ var withSelectedClassifier = (operation, experiment) => classifierStatus.pipe(fl
53911
54215
  return operation.pipe(provide4(Classifier.openrouter(model, apiKey, experiment)));
53912
54216
  }));
53913
54217
 
54218
+ // packages/cli/src/commands/du.ts
54219
+ import { lstat as lstat11, realpath as realpath10 } from "fs/promises";
54220
+ import { resolve as resolve18 } from "path";
54221
+ var runStorageReport = fn2("cli.runStorageReport")(function* (options = {}) {
54222
+ const project = yield* Project;
54223
+ const { config } = yield* lifecycleWorkspace;
54224
+ const root = yield* maintenanceIO(() => realpath10(project.notesRoot).catch((error2) => {
54225
+ if (error2.code !== "ENOENT")
54226
+ throw error2;
54227
+ return resolve18(project.notesRoot);
54228
+ }));
54229
+ const files = yield* maintenanceIO(async () => {
54230
+ const exists = await lstat11(root).catch((error2) => {
54231
+ if (error2.code !== "ENOENT")
54232
+ throw error2;
54233
+ return;
54234
+ });
54235
+ return exists?.isDirectory() === true ? readTree(root) : [];
54236
+ });
54237
+ return yield* storageReport({ root, files, config, ...options });
54238
+ });
54239
+ var budgetWarning = (report) => report.overBudget ? `Scratchpad is ${formatBytes(report.totalBytes)}, over its ${formatBytes(report.budgetBytes)} budget (lifecycle.storage.budgetMB). Run \`scratchpad du\` to find the bulk.` : undefined;
54240
+ var bulkWarning = (report) => report.bulk.count === 0 ? undefined : `${formatBytes(report.bulk.bytes)} of run artifacts (traces, videos, archives, executables, copied trees) in ${report.bulk.entries.length} place(s). Keep a receipt and a link to the original run instead; \`scratchpad sweep\` previews bulk owned by closed records.`;
54241
+ var formatDu = (report) => {
54242
+ const row = (bytes, path, note = "") => `${formatBytes(bytes).padStart(10)} ${path}${note === "" ? "" : ` ${dim(note)}`}`;
54243
+ return [
54244
+ `${formatBytes(report.totalBytes)} in ${report.fileCount} files under ${report.root} (budget ${formatBytes(report.budgetBytes)})`,
54245
+ "",
54246
+ "Largest folders:",
54247
+ ...report.folders.map((entry) => row(entry.bytes, `${entry.path}/`, `${entry.files} files`)),
54248
+ "",
54249
+ "Largest files:",
54250
+ ...report.files.map((entry) => row(entry.bytes, entry.path, entry.kind ?? "")),
54251
+ ...report.bulk.count === 0 ? [] : [
54252
+ "",
54253
+ `Bulk (\u2265 ${formatBytes(report.bulkThresholdBytes)} or copied trees): ${formatBytes(report.bulk.bytes)}`,
54254
+ ...report.bulk.entries.map((entry) => row(entry.bytes, entry.kind === "bundle" ? `${entry.path}/` : entry.path, entry.kind))
54255
+ ]
54256
+ ];
54257
+ };
54258
+ var du = make39("du", {
54259
+ depth: Int6("depth").pipe(withDefault4(2), withDescription3("Folder depth to total (default 2)")),
54260
+ top: Int6("top").pipe(withDefault4(10), withDescription3("Largest folders and files to list (default 10)")),
54261
+ json: jsonFlag
54262
+ }, ({ depth, top, json }) => gen3(function* () {
54263
+ const report = yield* runStorageReport({ depth, top });
54264
+ if (json)
54265
+ return yield* printJson(report);
54266
+ yield* log2(formatDu(report).join(`
54267
+ `));
54268
+ for (const warning of [budgetWarning(report), bulkWarning(report)])
54269
+ if (warning !== undefined)
54270
+ yield* error(`Warning: ${warning}`);
54271
+ }).pipe(provide4(Project.layer), provideService2(MinimumLogLevel2, "None"))).pipe(withDescription4("Report Scratchpad disk usage: largest folders and files, budget, and flagged run-artifact bulk"));
54272
+
53914
54273
  // packages/cli/src/commands/doctor.ts
53915
54274
  var runDoctor = fn2("cli.runDoctor")(function* () {
53916
54275
  const project = yield* Project;
@@ -53926,7 +54285,7 @@ var runDoctor = fn2("cli.runDoctor")(function* () {
53926
54285
  if (rootExists) {
53927
54286
  const entries = yield* fs.readDirectory(project.notesRoot);
53928
54287
  for (const entry of entries.sort()) {
53929
- const info = yield* maintenanceIO(() => lstat11(join14(project.notesRoot, entry)));
54288
+ const info = yield* maintenanceIO(() => lstat12(join15(project.notesRoot, entry)));
53930
54289
  if (info.isDirectory()) {
53931
54290
  if (!folders.includes(entry))
53932
54291
  outOfLayoutFolders.push(entry);
@@ -53938,6 +54297,7 @@ var runDoctor = fn2("cli.runDoctor")(function* () {
53938
54297
  const stateDbExists = statePath === null ? false : yield* fs.exists(statePath);
53939
54298
  const githubTokenPresent = yield* resolveToken().pipe(as2(true), catchTag2("AuthMissingError", () => succeed6(false)));
53940
54299
  const classifier = yield* classifierStatus;
54300
+ const report = yield* runStorageReport({ top: 1 });
53941
54301
  return {
53942
54302
  projectId: project.projectId,
53943
54303
  notesRoot: project.notesRoot,
@@ -53947,7 +54307,15 @@ var runDoctor = fn2("cli.runDoctor")(function* () {
53947
54307
  stateDbExists,
53948
54308
  githubTokenPresent,
53949
54309
  classifier,
53950
- layout: { folders, files, rootExists, outOfLayoutFolders, looseFiles }
54310
+ layout: { folders, files, rootExists, outOfLayoutFolders, looseFiles },
54311
+ storage: {
54312
+ totalBytes: report.totalBytes,
54313
+ budgetBytes: report.budgetBytes,
54314
+ overBudget: report.overBudget,
54315
+ bulkBytes: report.bulk.bytes,
54316
+ bulkCount: report.bulk.count,
54317
+ warnings: [budgetWarning(report), bulkWarning(report)].filter((warning) => warning !== undefined)
54318
+ }
53951
54319
  };
53952
54320
  });
53953
54321
  var formatDoctor = (summary) => labelValue([
@@ -53961,6 +54329,11 @@ var formatDoctor = (summary) => labelValue([
53961
54329
  ["notes root exists", String(summary.layout.rootExists)],
53962
54330
  ["out-of-layout folders", summary.layout.outOfLayoutFolders.join(", ") || "none"],
53963
54331
  ["loose files", summary.layout.looseFiles.join(", ") || "none"],
54332
+ [
54333
+ "storage",
54334
+ `${formatBytes(summary.storage.totalBytes)} of ${formatBytes(summary.storage.budgetBytes)} budget`
54335
+ ],
54336
+ ["bulk", summary.storage.bulkCount === 0 ? "none" : formatBytes(summary.storage.bulkBytes)],
53964
54337
  ["classifier provider", "OpenRouter Decisions API"],
53965
54338
  ["classifier model", summary.classifier.model],
53966
54339
  ["classifier default model", DEFAULT_MODEL],
@@ -53969,9 +54342,13 @@ var formatDoctor = (summary) => labelValue([
53969
54342
  ]);
53970
54343
  var doctor = make39("doctor", { json: jsonFlag }, ({ json }) => gen3(function* () {
53971
54344
  const summary = yield* runDoctor();
53972
- yield* json ? printJson(summary) : log2(formatDoctor(summary).join(`
54345
+ if (json)
54346
+ return yield* printJson(summary);
54347
+ yield* log2(formatDoctor(summary).join(`
53973
54348
  `));
53974
- }).pipe(provide4(Project.layer), json ? provideService2(MinimumLogLevel2, "None") : identity)).pipe(withDescription4("Report project notes, layout drift, config, state, and GitHub auth availability"));
54349
+ for (const warning of summary.storage.warnings)
54350
+ yield* error(`Warning: ${warning}`);
54351
+ }).pipe(provide4(Project.layer), json ? provideService2(MinimumLogLevel2, "None") : identity)).pipe(withDescription4("Report project notes, layout drift, storage budget and bulk, config, state, and GitHub auth availability"));
53975
54352
 
53976
54353
  // packages/cli/src/commands/feedback.ts
53977
54354
  import { hostname } from "os";
@@ -54676,9 +55053,9 @@ var feedback = make39("feedback").pipe(withSubcommands([
54676
55053
 
54677
55054
  // packages/cli/src/runtime/store.ts
54678
55055
  import { mkdirSync as mkdirSync2 } from "fs";
54679
- import { dirname as dirname12 } from "path";
55056
+ import { dirname as dirname13 } from "path";
54680
55057
  var projectionStoreLayer = (statePath) => {
54681
- mkdirSync2(dirname12(statePath), { recursive: true });
55058
+ mkdirSync2(dirname13(statePath), { recursive: true });
54682
55059
  return ProjectionStore.layer.pipe(provide2(Database2.layer(statePath)));
54683
55060
  };
54684
55061
 
@@ -54846,13 +55223,13 @@ var repair = make39("repair", {
54846
55223
  }).pipe(provide4(Workspace2.layer))).pipe(withDescription4("Resolve sync conflicts interactively or with --take-local/remote"));
54847
55224
 
54848
55225
  // packages/cli/src/commands/review.ts
54849
- import { realpath as realpath10 } from "fs/promises";
54850
- import { relative as relative13, resolve as resolve19, sep as sep8 } from "path";
55226
+ import { realpath as realpath11 } from "fs/promises";
55227
+ import { relative as relative13, resolve as resolve20, sep as sep8 } from "path";
54851
55228
 
54852
55229
  // packages/cli/src/lifecycle/evidence.ts
54853
55230
  import { createHash as createHash10 } from "crypto";
54854
55231
  import { readdir as readdir3, stat as stat6 } from "fs/promises";
54855
- import { dirname as dirname13, isAbsolute as isAbsolute8, relative as relative11, resolve as resolve18 } from "path";
55232
+ import { dirname as dirname14, isAbsolute as isAbsolute8, relative as relative11, resolve as resolve19 } from "path";
54856
55233
  var hash2 = (text) => createHash10("sha256").update(text).digest("hex");
54857
55234
  var noteLinks = (text) => [
54858
55235
  ...text.matchAll(/\]\(\s*(?:<([^>]+)>|([^\s)]+))(?:\s+[^)]*)?\)|^\s*\[[^\]]+\]:\s*(?:<([^>]+)>|([^\s]+))|(?:href|src)=["']([^"']+)["']/gm)
@@ -54872,7 +55249,7 @@ var discoverNotes = async (root) => {
54872
55249
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
54873
55250
  if (entry.isSymbolicLink() || entry.name.startsWith(REVIEW_STAGING_PREFIX))
54874
55251
  continue;
54875
- const path = resolve18(root, entry.name);
55252
+ const path = resolve19(root, entry.name);
54876
55253
  if (entry.isDirectory())
54877
55254
  files.push(...await discoverNotes(path));
54878
55255
  else if (entry.isFile() && /\.(md|html)$/i.test(entry.name))
@@ -54938,7 +55315,7 @@ var makeEvidenceLookup = fn2("Lifecycle.makeEvidenceLookup")(function* (input) {
54938
55315
  });
54939
55316
  return {
54940
55317
  git: async (args) => getOrThrow(await runPromise2(get5(gitCache, JSON.stringify(args)))),
54941
- stat: async (path) => getOrThrow(await runPromise2(get5(fileCache, resolve18(path)))),
55318
+ stat: async (path) => getOrThrow(await runPromise2(get5(fileCache, resolve19(path)))),
54942
55319
  github: async (reference) => getOrThrow(await runPromise2(get5(githubCache, JSON.stringify({
54943
55320
  number: reference.number,
54944
55321
  repo: (reference.repo ?? input.repo)?.toLowerCase()
@@ -54957,11 +55334,11 @@ var buildLinkIndex = (notes) => {
54957
55334
  };
54958
55335
  var inboundLinks = (index, file, notesRoot) => {
54959
55336
  const sources = new Set;
54960
- for (let current = file;; current = dirname13(current)) {
55337
+ for (let current = file;; current = dirname14(current)) {
54961
55338
  for (const source of index.get(current) ?? [])
54962
55339
  if (source !== file)
54963
55340
  sources.add(relative11(notesRoot, source));
54964
- if (current === dirname13(current))
55341
+ if (current === dirname14(current))
54965
55342
  break;
54966
55343
  }
54967
55344
  return [...sources].sort();
@@ -55027,7 +55404,7 @@ var collectEvidence = fn2("Lifecycle.collectEvidence")(function* (input) {
55027
55404
  ].sort((a, b) => a.relativeTo.localeCompare(b.relativeTo) || a.path.localeCompare(b.path));
55028
55405
  const files = [];
55029
55406
  for (const { path, relativeTo } of paths) {
55030
- const target = resolve18(relativeTo === "note" ? dirname13(input.file) : input.root, path);
55407
+ const target = resolve19(relativeTo === "note" ? dirname14(input.file) : input.root, path);
55031
55408
  try {
55032
55409
  await lookup.stat(target);
55033
55410
  files.push({ path, relativeTo, exists: true });
@@ -55061,10 +55438,10 @@ var collectEvidence = fn2("Lifecycle.collectEvidence")(function* (input) {
55061
55438
 
55062
55439
  // packages/cli/src/lifecycle/runtime.ts
55063
55440
  import { mkdir as mkdir7 } from "fs/promises";
55064
- import { dirname as dirname14 } from "path";
55441
+ import { dirname as dirname15 } from "path";
55065
55442
 
55066
55443
  // packages/cli/src/lifecycle/review.ts
55067
- import { readFile as readFile12 } from "fs/promises";
55444
+ import { readFile as readFile13 } from "fs/promises";
55068
55445
  import { relative as relative12, extname as extname4 } from "path";
55069
55446
  var reviewNotes = fn2("Lifecycle.review")(function* (input) {
55070
55447
  const classifier = yield* Classifier;
@@ -55087,7 +55464,7 @@ var reviewNotes = fn2("Lifecycle.review")(function* (input) {
55087
55464
  const questionShape = classifier.lifecycleShape ?? DEFAULT_LIFECYCLE_SHAPE;
55088
55465
  const lookup = yield* makeEvidenceLookup(input);
55089
55466
  const allNotes = yield* forEach2(input.allFiles, (file) => gen3(function* () {
55090
- const text = yield* tryPromise2(() => readFile12(file, "utf8"));
55467
+ const text = yield* tryPromise2(() => readFile13(file, "utf8"));
55091
55468
  const parsed = yield* result2(parseNote(text));
55092
55469
  const modelText = isSuccess2(parsed) ? parsed.success.modelEvidenceText : "";
55093
55470
  const targets = yield* tryPromise2(() => linkedTargets(file, text));
@@ -55106,7 +55483,7 @@ var reviewNotes = fn2("Lifecycle.review")(function* (input) {
55106
55483
  const skipped = [];
55107
55484
  let calls = 0, cacheHits = 0, inputTokens = 0, outputTokens = 0, reportedUsd = 0, estimatedCalls = 0;
55108
55485
  for (const file of selectedFiles) {
55109
- const text = notesByFile.get(file)?.text ?? (yield* tryPromise2(() => readFile12(file, "utf8")));
55486
+ const text = notesByFile.get(file)?.text ?? (yield* tryPromise2(() => readFile13(file, "utf8")));
55110
55487
  const decoded = yield* result2(parseNote(text));
55111
55488
  if (isFailure2(decoded)) {
55112
55489
  skipped.push({ path: relative12(input.notesRoot, file), reason: decoded.failure.message });
@@ -55255,7 +55632,7 @@ var projectReview = fn2("Lifecycle.projectReview")(function* (input) {
55255
55632
  const configRoot = input.configRoot ?? project.toplevel;
55256
55633
  const db = stateDbPath(project.projectId, configRoot, input.config?.mounts ?? []);
55257
55634
  const managedRoots = managedNoteRoots(input.notesRoot, configRoot, input.config);
55258
- yield* tryPromise2(() => mkdir7(dirname14(db), { recursive: true }));
55635
+ yield* tryPromise2(() => mkdir7(dirname15(db), { recursive: true }));
55259
55636
  const token = yield* resolveToken().pipe(catchTag2("AuthMissingError", () => succeed6(undefined)));
55260
55637
  const repo = input.config?.repo ?? (project.projectId.startsWith("github.com/") ? project.projectId.slice(11) : undefined);
55261
55638
  const github = token ? async (reference) => {
@@ -55336,11 +55713,11 @@ var review2 = make39("review", {
55336
55713
  yield* log2(message);
55337
55714
  return;
55338
55715
  }
55339
- const notesRoot = yield* tryPromise2(() => realpath10(project.notesRoot));
55716
+ const notesRoot = yield* tryPromise2(() => realpath11(project.notesRoot));
55340
55717
  const { config, configRoot } = yield* lifecycleWorkspace;
55341
55718
  const files = yield* tryPromise2(() => discoverNotes(notesRoot));
55342
55719
  const selected = paths.length === 0 ? files : yield* tryPromise2({
55343
- try: () => validateNoteFiles(paths.map((path) => resolve19(notesRoot, path)), notesRoot),
55720
+ try: () => validateNoteFiles(paths.map((path) => resolve20(notesRoot, path)), notesRoot),
55344
55721
  catch: (error) => notesCommandError("usage", error)
55345
55722
  });
55346
55723
  for (const file of selected) {
@@ -55438,7 +55815,7 @@ var route = make39("route", {
55438
55815
  }, ({ correction, write, json }) => routeCorrection({ correction, write, json }).pipe(withSelectedClassifier, provide4(Project.layer))).pipe(withDescription4("Suggest where an instruction correction belongs"));
55439
55816
 
55440
55817
  // packages/cli/src/commands/search.ts
55441
- import { dirname as dirname16, join as join16 } from "path";
55818
+ import { dirname as dirname17, join as join17 } from "path";
55442
55819
 
55443
55820
  // packages/cli/src/search/errors.ts
55444
55821
  class SearchError extends TaggedError3()("SearchError", {
@@ -55458,6 +55835,26 @@ var searchError = (cause) => cause instanceof SearchError || cause instanceof Se
55458
55835
  // packages/cli/src/search/embeddings.ts
55459
55836
  var DIMENSIONS = 1024;
55460
55837
  var MODEL = "qwen/qwen3-embedding-8b";
55838
+ var EMBED_REQUEST_SIZE = 64;
55839
+ var EMBED_CONCURRENCY = 8;
55840
+ var mapConcurrent = async (items, limit, f) => {
55841
+ const results = new Array(items.length);
55842
+ let next = 0;
55843
+ let failed = false;
55844
+ const worker = async () => {
55845
+ while (!failed && next < items.length) {
55846
+ const i = next++;
55847
+ try {
55848
+ results[i] = await f(items[i]);
55849
+ } catch (cause) {
55850
+ failed = true;
55851
+ throw cause;
55852
+ }
55853
+ }
55854
+ };
55855
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
55856
+ return results;
55857
+ };
55461
55858
  var Response2 = Struct({
55462
55859
  data: ArraySchema(Struct({
55463
55860
  index: Number6,
@@ -55467,9 +55864,10 @@ var Response2 = Struct({
55467
55864
  var openRouter = (key) => ({
55468
55865
  identity: `${MODEL}:${DIMENSIONS}:v1`,
55469
55866
  async embed(texts) {
55470
- const vectors = [];
55471
- for (let offset = 0;offset < texts.length; offset += 64) {
55472
- const input = texts.slice(offset, offset + 64);
55867
+ const batches = [];
55868
+ for (let offset = 0;offset < texts.length; offset += EMBED_REQUEST_SIZE)
55869
+ batches.push(texts.slice(offset, offset + EMBED_REQUEST_SIZE));
55870
+ const results = await mapConcurrent(batches, EMBED_CONCURRENCY, async (input) => {
55473
55871
  const response = await fetch("https://openrouter.ai/api/v1/embeddings", {
55474
55872
  method: "POST",
55475
55873
  signal: AbortSignal.timeout(60000),
@@ -55487,9 +55885,9 @@ var openRouter = (key) => ({
55487
55885
  throw new SearchError({
55488
55886
  message: "Embedding response has invalid indexes, count or dimensions"
55489
55887
  });
55490
- vectors.push(...data.map((d) => [...d.embedding]));
55491
- }
55492
- return vectors;
55888
+ return data.map((d) => [...d.embedding]);
55889
+ });
55890
+ return results.flat();
55493
55891
  }
55494
55892
  });
55495
55893
  var embed = (embedder, texts) => tryPromise2({ try: () => embedder.embed(texts), catch: searchError });
@@ -55498,7 +55896,7 @@ var embed = (embedder, texts) => tryPromise2({ try: () => embedder.embed(texts),
55498
55896
  import { Database as Database4 } from "bun:sqlite";
55499
55897
  import { createHash as createHash12 } from "crypto";
55500
55898
  import { chmodSync, mkdirSync as mkdirSync4, readFileSync as readFileSync2, readdirSync as readdirSync2, realpathSync as realpathSync2, rmSync } from "fs";
55501
- import { basename as basename7, join as join15 } from "path";
55899
+ import { basename as basename7, join as join16 } from "path";
55502
55900
 
55503
55901
  // packages/cli/src/search/chunk.ts
55504
55902
  import { createHash as createHash11 } from "crypto";
@@ -55601,12 +55999,12 @@ var chunkMarkdown = (notePath, title, content, maxChars = 700) => {
55601
55999
  // packages/cli/src/search/store.ts
55602
56000
  import { Database as Database3 } from "bun:sqlite";
55603
56001
  import { mkdirSync as mkdirSync3 } from "fs";
55604
- import { dirname as dirname15 } from "path";
56002
+ import { dirname as dirname16 } from "path";
55605
56003
 
55606
56004
  class SearchStore {
55607
56005
  db;
55608
56006
  constructor(path) {
55609
- mkdirSync3(dirname15(path), { recursive: true });
56007
+ mkdirSync3(dirname16(path), { recursive: true });
55610
56008
  this.db = new Database3(path, { create: true });
55611
56009
  this.db.exec(`PRAGMA busy_timeout=0;
55612
56010
  CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, hash TEXT NOT NULL);
@@ -55729,11 +56127,29 @@ var inBatches = (items, write) => {
55729
56127
  results.push(...write(items.slice(i, i + VECTOR_WRITE_BATCH)));
55730
56128
  return results;
55731
56129
  };
56130
+ var EMBED_GROUP_CHUNKS = 512;
56131
+ var groupByChunks = (notes, size) => {
56132
+ const groups = [];
56133
+ let group = [];
56134
+ let count = 0;
56135
+ for (const note of notes) {
56136
+ group.push(note);
56137
+ count += note.pending.length;
56138
+ if (count >= size) {
56139
+ groups.push(group);
56140
+ group = [];
56141
+ count = 0;
56142
+ }
56143
+ }
56144
+ if (group.length)
56145
+ groups.push(group);
56146
+ return groups;
56147
+ };
55732
56148
  var Metadata = Struct({
55733
56149
  title: optional2(String5),
55734
56150
  kind: optional2(String5)
55735
56151
  });
55736
- var scopeDirectory = (options) => join15(options.directory, hash3("v3:" + JSON.stringify([...new Set(options.roots.map(physicalMountPath))].sort())).slice(0, 16));
56152
+ var scopeDirectory = (options) => join16(options.directory, hash3("v3:" + JSON.stringify([...new Set(options.roots.map(physicalMountPath))].sort())).slice(0, 16));
55737
56153
  var fuse = (lists) => {
55738
56154
  const scores = new Map;
55739
56155
  for (const list of lists)
@@ -55757,7 +56173,7 @@ var scan = (roots) => {
55757
56173
  return;
55758
56174
  visited.add(physical);
55759
56175
  for (const entry of readdirSync2(physical, { withFileTypes: true })) {
55760
- const path = join15(physical, entry.name);
56176
+ const path = join16(physical, entry.name);
55761
56177
  if (entry.isDirectory() && !entry.name.startsWith("."))
55762
56178
  walk(path);
55763
56179
  else if (entry.isFile() && /\.md$/i.test(entry.name))
@@ -55772,7 +56188,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55772
56188
  try: () => {
55773
56189
  mkdirSync4(options.directory, { recursive: true, mode: 448 });
55774
56190
  chmodSync(options.directory, 448);
55775
- const lock = new Database4(join15(options.directory, "lock.db"), { create: true });
56191
+ const lock = new Database4(join16(options.directory, "lock.db"), { create: true });
55776
56192
  try {
55777
56193
  lock.exec("BEGIN IMMEDIATE");
55778
56194
  return lock;
@@ -55789,7 +56205,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55789
56205
  });
55790
56206
  if (options.rebuild)
55791
56207
  yield* tryPromise2({
55792
- try: () => assertRebuildAvailable(join15(directory, "vectors")),
56208
+ try: () => assertRebuildAvailable(join16(directory, "vectors")),
55793
56209
  catch: searchError
55794
56210
  });
55795
56211
  yield* try_3({
@@ -55802,7 +56218,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55802
56218
  catch: searchError
55803
56219
  });
55804
56220
  const store = yield* acquireRelease2(try_3({
55805
- try: () => new SearchStore(join15(directory, "index.db")),
56221
+ try: () => new SearchStore(join16(directory, "index.db")),
55806
56222
  catch: searchError
55807
56223
  }), (s) => sync2(() => s.close()));
55808
56224
  const sources = yield* try_3({ try: () => scan(options.roots), catch: searchError });
@@ -55815,13 +56231,14 @@ var run6 = fn2("Search.run")(function* (options, query) {
55815
56231
  oldByPath.set(chunk.notePath, list);
55816
56232
  }
55817
56233
  const files = new Map(store.files().map((f) => [f.path, f.hash]));
55818
- const vectorPath = join15(directory, "vectors");
56234
+ const vectorPath = join16(directory, "vectors");
55819
56235
  const vectorWriter = options.embedder ? yield* acquireRelease2(tryPromise2({ try: () => writer(vectorPath), catch: searchError }), (c) => sync2(() => c.closeSync())) : undefined;
55820
56236
  const vectorEmpty = vectorWriter?.stats.docCount === 0;
55821
56237
  let changed = 0;
56238
+ const embeddingIdentity = options.embedder?.identity;
56239
+ const prepared = [];
55822
56240
  for (const [path, text] of sources) {
55823
56241
  const fileHash = hash3(text);
55824
- const embeddingIdentity = options.embedder?.identity;
55825
56242
  const needsVectors = embeddingIdentity !== undefined && (vectorEmpty || (oldByPath.get(path) ?? []).some((c) => c.notePath === path && c.vectorHash !== hash3(`${embeddingIdentity}:${c.contentHash}`)));
55826
56243
  if (!options.rebuild && files.get(path) === fileHash && !needsVectors)
55827
56244
  continue;
@@ -55836,8 +56253,12 @@ var run6 = fn2("Search.run")(function* (options, query) {
55836
56253
  vectorHash: oldChunks.get(c.id)?.contentHash === c.contentHash ? oldChunks.get(c.id)?.vectorHash ?? null : null
55837
56254
  }));
55838
56255
  const pending = chunks.filter((c) => options.rebuild || vectorEmpty || oldChunks.get(c.id)?.vectorHash !== hash3(`${embeddingIdentity}:${c.contentHash}`));
55839
- if (options.embedder && vectorWriter) {
55840
- const vectors = yield* embed(options.embedder, pending.map(embeddingInput));
56256
+ prepared.push({ path, fileHash, chunks, pending });
56257
+ }
56258
+ for (const group of groupByChunks(prepared, EMBED_GROUP_CHUNKS)) {
56259
+ const pending = group.flatMap((note) => note.pending);
56260
+ if (options.embedder && vectorWriter && embeddingIdentity !== undefined) {
56261
+ const vectors = pending.length ? yield* embed(options.embedder, pending.map(embeddingInput)) : [];
55841
56262
  yield* try_3({
55842
56263
  try: () => {
55843
56264
  const docs = pending.map((c, i) => {
@@ -55853,17 +56274,19 @@ var run6 = fn2("Search.run")(function* (options, query) {
55853
56274
  if (failed)
55854
56275
  throw new SearchError({ message: `Vector upsert failed: ${failed.message}` });
55855
56276
  }
55856
- for (const c of chunks)
55857
- c.vectorHash = hash3(`${embeddingIdentity}:${c.contentHash}`);
56277
+ for (const note of group)
56278
+ for (const c of note.chunks)
56279
+ c.vectorHash = hash3(`${embeddingIdentity}:${c.contentHash}`);
55858
56280
  },
55859
56281
  catch: searchError
55860
56282
  });
55861
56283
  }
55862
- yield* try_3({
55863
- try: () => store.replace(path, fileHash, chunks),
55864
- catch: searchError
55865
- });
55866
- changed++;
56284
+ for (const note of group)
56285
+ yield* try_3({
56286
+ try: () => store.replace(note.path, note.fileHash, note.chunks),
56287
+ catch: searchError
56288
+ });
56289
+ changed += group.length;
55867
56290
  }
55868
56291
  const deleted = [...files.keys()].filter((path) => !sources.has(path));
55869
56292
  yield* try_3({
@@ -55894,7 +56317,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55894
56317
  let hits = [];
55895
56318
  if (query) {
55896
56319
  const store = yield* acquireRelease2(try_3({
55897
- try: () => new SearchStore(join15(summary.directory, "index.db")),
56320
+ try: () => new SearchStore(join16(summary.directory, "index.db")),
55898
56321
  catch: searchError
55899
56322
  }), (s) => sync2(() => s.close()));
55900
56323
  const eligible = summary.chunks.filter((c) => query.kind === undefined || c.kind === query.kind);
@@ -55913,7 +56336,7 @@ Query: ${query.text}`
55913
56336
  if (!vector)
55914
56337
  return yield* new SearchError({ message: "Embedder omitted query vector" });
55915
56338
  vectorIds = yield* tryPromise2({
55916
- try: () => search(join15(summary.directory, "vectors"), vector, Math.max(query.limit * 4, 100), new Set(byId.keys())),
56339
+ try: () => search(join16(summary.directory, "vectors"), vector, Math.max(query.limit * 4, 100), new Set(byId.keys())),
55917
56340
  catch: searchError
55918
56341
  });
55919
56342
  }
@@ -55952,9 +56375,9 @@ var execute = (options, query) => gen3(function* () {
55952
56375
  });
55953
56376
  const roots = [project.notesRoot];
55954
56377
  if (options.global)
55955
- roots.push(join16(globalNotesRoot(), "feedback"));
56378
+ roots.push(join17(globalNotesRoot(), "feedback"));
55956
56379
  const report = yield* run6({
55957
- directory: join16(dirname16(stateDbPath(project.projectId, configRoot, config.mounts)), "search"),
56380
+ directory: join17(dirname17(stateDbPath(project.projectId, configRoot, config.mounts)), "search"),
55958
56381
  roots,
55959
56382
  ...key ? { embedder: openRouter(key) } : {},
55960
56383
  ...options.rebuild ? { rebuild: true } : {}
@@ -56439,7 +56862,8 @@ Report without editing:
56439
56862
  - the backlog graph from \`scratchpad backlog graph\` and any problems from
56440
56863
  \`scratchpad backlog validate\`;
56441
56864
  - top-level folders and loose files outside the layout, from \`scratchpad doctor\`;
56442
- - expired artifacts, from the \`scratchpad sweep\` preview;
56865
+ - expired artifacts and closed records' bulk, from the \`scratchpad sweep\` preview;
56866
+ - size over budget and flagged bulk, from \`scratchpad du\`;
56443
56867
  - obvious stale-state risks that need reconciliation.
56444
56868
 
56445
56869
  For a large tree, split the inventory into bounded, non-overlapping areas. Keep the same output
@@ -56586,6 +57010,17 @@ scratchpad sweep --json # version 1 report
56586
57010
  scratchpad sweep --apply # move expired artifacts to the Trash with receipts
56587
57011
  \`\`\`
56588
57012
 
57013
+ Run bulk is swept by ownership, not age. Traces, videos, archives, and executables at or over
57014
+ \`lifecycle.storage.bulkMB\` (default 5), and every file in a copied tree (\`node_modules\`, \`.git\`,
57015
+ \`test-results\`, \`playwright-report\`, \`*.app\`), are bulk. A bulk file is a candidate when every
57016
+ record that owns it has a closed \`status\`: notes that link it or its folder, and the nearest folder
57017
+ \`README.md\`. A link does not protect bulk; an open or status-less owner, or a \`lifecycle.protect\`
57018
+ glob, does. Notes are never bulk.
57019
+
57020
+ \`scratchpad du\` lists the largest folders and files, the flagged bulk, and whether the Scratchpad is
57021
+ over \`lifecycle.storage.budgetMB\` (default 1024); \`doctor\` repeats the totals. When bulk shows up,
57022
+ replace the copy with a receipt and a link to the original run, or close its record.
57023
+
56589
57024
  Run the preview freely. Run \`--apply\` only when the user or the project's maintenance role
56590
57025
  authorizes it, and report the totals. Read-only files or parents are reported as refused with a
56591
57026
  warning and exit 0; they are not failures. Existing \`archive/\` contents are ordinary sweep
@@ -56851,11 +57286,12 @@ files and one writer per file.
56851
57286
 
56852
57287
  Notes are kept while true and archived (to the Trash) once they stop supporting current work;
56853
57288
  artifacts (non-\`.md\`/\`.html\` files) expire through \`scratchpad sweep\` after
56854
- \`lifecycle.artifacts.maxAgeDays\` (default 14). Link a file from a note to protect it. Prefer one
56855
- copy linked from the relevant record. Keep raw traces, builds, and exports only when they support a
56856
- current investigation or a deliberate retention need; record that reason and an exit condition. Do
56857
- not infer deletion authority from \`tmp/\`, age, or a duplicate hash alone; \`sweep --apply\` runs only
56858
- when the user or the project's maintenance role authorizes it.
57289
+ \`lifecycle.artifacts.maxAgeDays\` (default 14). Link a file from a note to protect it from expiry.
57290
+ Evidence is a receipt plus a link to the original run, not a copy of the run: no trace zips, videos,
57291
+ tarballs, binaries, or whole run folders. \`sweep\` retires such bulk once its owning record is
57292
+ closed, link or not; \`du\` reports it. Do not infer deletion authority from \`tmp/\`, age, or a
57293
+ duplicate hash alone; \`sweep --apply\` runs only when the user or the project's maintenance role
57294
+ authorizes it.
56859
57295
 
56860
57296
  Promote durable product decisions into the existing owning tracked doc under the project's root
56861
57297
  \`docs/\` where appropriate. Keep temporary research and delivery history in Scratchpad. Migration
@@ -56964,7 +57400,7 @@ the request and current state.
56964
57400
  | \`feedback\` | Capture or inspect instruction friction | \`feedback new\`, \`feedback list\`, \`feedback review\`; \`--ref instruction-feedback\` |
56965
57401
  | \`reconcile\` (\`sync\`) | Reconcile active notes with current truth, then update or archive | \`--ref modes\` |
56966
57402
  | \`review\` | Judge note kind and staleness against repository evidence | \`review [paths] [--apply] [--json]\`; \`--ref modes\` |
56967
- | \`archive\` | Move inactive notes to the OS Trash with a receipt | \`archive <paths...> --reason "<why>"\`; \`sweep\`; \`doctor\`; \`--ref modes\` |
57403
+ | \`archive\` | Move inactive notes to the OS Trash with a receipt | \`archive <paths...> --reason "<why>"\`; \`sweep\`; \`du\`; \`doctor\`; \`--ref modes\` |
56968
57404
  | \`extract\` | Promote stable facts into tracked docs, tests, or ADRs | \`--ref modes\` |
56969
57405
 
56970
57406
  \`sync\` is this skill's alias for \`reconcile\`; keep accepting it. It is not \`scratchpad sync\`, which
@@ -56974,6 +57410,15 @@ This skill's \`reconcile\` covers \`.scratchpad\` only. Repo-wide Markdown plus
56974
57410
  auto-memories belong to the \`reconcile\` skill. Workflows such as \`delivery\` supply approved backlog
56975
57411
  content and execution evidence; this skill owns its representation and lifecycle.
56976
57412
 
57413
+ ## Evidence, not copies
57414
+
57415
+ Keep receipts in Scratchpad: summaries, JSON, logs, screenshots, and a link or path to the original
57416
+ run. Do not copy run output into it: trace zips, videos, tarballs, extracted binaries,
57417
+ \`node_modules\`, or whole run folders. Link to where the run already lives. If the original will be
57418
+ deleted, keep the one file a claim depends on, say why, and add its path to \`lifecycle.protect\` in
57419
+ \`scratchpad.config.ts\`; a link alone does not keep bulk. Set \`status: done\` on a record when its
57420
+ work lands, so \`scratchpad sweep\` can retire the bulk it owns. \`scratchpad du\` lists what is large.
57421
+
56977
57422
  ## Note lifecycle
56978
57423
 
56979
57424
  Notes may declare \`kind\`, \`status\`, \`updated\`, \`reviewed\`, \`superseded_by\`, and \`expires\` in front
@@ -57347,14 +57792,14 @@ var skillsPathCommand = make39("path", { json: jsonFlag }, ({ json }) => {
57347
57792
  var skillsCommand = make39("skills").pipe(withDescription4("List and print embedded agent skills"), withSubcommands([skillsListCommand, skillsGetCommand, skillsPathCommand]));
57348
57793
 
57349
57794
  // packages/cli/src/commands/status.ts
57350
- import { join as join17 } from "path";
57795
+ import { join as join18 } from "path";
57351
57796
  var readDirectory2 = (fs, directory, name, depth) => gen3(function* () {
57352
57797
  const entries = yield* fs.readDirectory(directory);
57353
57798
  const sorted = entries.toSorted((a, b) => a.localeCompare(b));
57354
57799
  const directories = [];
57355
57800
  let files = 0;
57356
57801
  for (const entry of sorted) {
57357
- const path = join17(directory, entry);
57802
+ const path = join18(directory, entry);
57358
57803
  const info = yield* fs.stat(path);
57359
57804
  if (info.type === "Directory") {
57360
57805
  if (depth > 0)
@@ -57429,11 +57874,11 @@ var status = make39("status", {
57429
57874
  }).pipe(provide4(Workspace2.layer), json ? provideService2(MinimumLogLevel2, "None") : identity)).pipe(withDescription4("Show repo, mount, pending-outbox, and conflict counts"));
57430
57875
 
57431
57876
  // packages/cli/src/commands/sweep.ts
57432
- import { lstat as lstat12, realpath as realpath11 } from "fs/promises";
57433
- import { join as join19 } from "path";
57877
+ import { lstat as lstat13, realpath as realpath12 } from "fs/promises";
57878
+ import { join as join20 } from "path";
57434
57879
 
57435
57880
  // packages/cli/src/lifecycle/candidates.ts
57436
- import { join as join18, basename as basename8 } from "path";
57881
+ import { join as join19, basename as basename8 } from "path";
57437
57882
  var noteCandidates = (context) => gen3(function* () {
57438
57883
  const status = yield* classifierStatus;
57439
57884
  if (!status.enabled)
@@ -57444,8 +57889,8 @@ var noteCandidates = (context) => gen3(function* () {
57444
57889
  return [];
57445
57890
  const report = yield* projectReview({
57446
57891
  notesRoot: context.root,
57447
- files: eligible.map((file) => join18(context.root, file.path)),
57448
- allFiles: files.map((file) => join18(context.root, file.path)),
57892
+ files: eligible.map((file) => join19(context.root, file.path)),
57893
+ allFiles: files.map((file) => join19(context.root, file.path)),
57449
57894
  config: context.config,
57450
57895
  ...context.configRoot === undefined ? {} : { configRoot: context.configRoot },
57451
57896
  apply: false,
@@ -57474,11 +57919,11 @@ var selectNoteCandidates = (context, notes) => {
57474
57919
 
57475
57920
  // packages/cli/src/commands/sweep.ts
57476
57921
  var sweepFiles = fn2("maintenance.sweepFiles")(function* (apply, sources) {
57477
- const { root, candidates, files } = yield* collectCandidates(sources ?? [artifactCandidates, noteCandidates]);
57922
+ const { root, candidates, files } = yield* collectCandidates(sources ?? [artifactCandidates, bulkCandidates, noteCandidates]);
57478
57923
  const refused = [];
57479
57924
  const accepted = [];
57480
57925
  for (const entry of candidates) {
57481
- if (yield* maintenanceIO(() => writableEntry(join19(root, entry.path))))
57926
+ if (yield* maintenanceIO(() => writableEntry(join20(root, entry.path))))
57482
57927
  accepted.push(entry);
57483
57928
  else
57484
57929
  refused.push({ path: entry.path, reason: "read-only file or parent directory" });
@@ -57487,21 +57932,36 @@ var sweepFiles = fn2("maintenance.sweepFiles")(function* (apply, sources) {
57487
57932
  if (apply && accepted.length) {
57488
57933
  const log = yield* prepareTrashLog(root);
57489
57934
  const snapshots = new Map(files.map((file) => [file.path, file]));
57490
- for (const entry of accepted) {
57491
- const snapshot = snapshots.get(entry.path);
57935
+ const unchanged = async (path) => {
57936
+ const snapshot = snapshots.get(path);
57937
+ const absolute = join20(root, path);
57938
+ const current = await lstat13(absolute).catch((error2) => {
57939
+ if (error2.code !== "ENOENT")
57940
+ throw error2;
57941
+ return;
57942
+ });
57943
+ return snapshot !== undefined && current !== undefined && current.isFile() && await realpath12(absolute) === absolute && current.size === snapshot.bytes && current.mtimeMs === snapshot.mtime && current.ctimeMs === snapshot.ctime && current.ino === snapshot.ino && current.dev === snapshot.dev;
57944
+ };
57945
+ const ordered = [
57946
+ ...accepted.filter((entry) => entry.owners !== undefined),
57947
+ ...accepted.filter((entry) => entry.owners === undefined)
57948
+ ];
57949
+ for (const entry of ordered) {
57950
+ let reason = "file changed since candidate scan";
57492
57951
  const moved = yield* trashWithReceipt(root, entry, log, async () => {
57493
- const absolute = join19(root, entry.path);
57494
- const current = await lstat12(absolute).catch((error2) => {
57495
- if (error2.code !== "ENOENT")
57496
- throw error2;
57497
- return;
57498
- });
57499
- return current !== undefined && current.isFile() && await realpath11(absolute) === absolute && current.size === snapshot.bytes && current.mtimeMs === snapshot.mtime && current.ctimeMs === snapshot.ctime && current.ino === snapshot.ino && current.dev === snapshot.dev;
57952
+ if (!await unchanged(entry.path))
57953
+ return false;
57954
+ for (const owner of entry.owners ?? [])
57955
+ if (!await unchanged(owner)) {
57956
+ reason = `owning record ${owner} changed since candidate scan`;
57957
+ return false;
57958
+ }
57959
+ return true;
57500
57960
  });
57501
57961
  if (moved)
57502
57962
  trashed.push(entry);
57503
57963
  else
57504
- refused.push({ path: entry.path, reason: "file changed since candidate scan" });
57964
+ refused.push({ path: entry.path, reason });
57505
57965
  }
57506
57966
  }
57507
57967
  const refusedPaths = new Set(refused.map((entry) => entry.path));
@@ -57533,12 +57993,12 @@ ${group.entries.map((entry) => ` ${entry.path} (${entry.bytes} bytes)`).join(`
57533
57993
  for (const entry of result.refused)
57534
57994
  yield* error(`Warning: ${entry.path}: ${entry.reason}`);
57535
57995
  }
57536
- }).pipe(provide4(Project.layer), provide4(Trash.layer), provideService2(MinimumLogLevel2, "None"))).pipe(withDescription4("List expired artifacts; --apply moves them to Trash with receipts"));
57996
+ }).pipe(provide4(Project.layer), provide4(Trash.layer), provideService2(MinimumLogLevel2, "None"))).pipe(withDescription4("List expired artifacts, bulk owned by closed records, and stale notes; --apply moves them to Trash with receipts"));
57537
57997
 
57538
57998
  // packages/cli/src/commands/upload.ts
57539
57999
  import { createHash as createHash13 } from "crypto";
57540
58000
  import { stat as stat7 } from "fs/promises";
57541
- import { basename as basename9, resolve as resolve20 } from "path";
58001
+ import { basename as basename9, resolve as resolve21 } from "path";
57542
58002
  var uploadContentTypes = {
57543
58003
  png: "image/png",
57544
58004
  jpg: "image/jpeg",
@@ -57576,7 +58036,7 @@ var uploadFiles = async (options) => {
57576
58036
  const client = clientForProfile(target.profile);
57577
58037
  const uploads = [];
57578
58038
  for (const path of options.paths) {
57579
- const absolute = resolve20(cwd(), path);
58039
+ const absolute = resolve21(cwd(), path);
57580
58040
  const info = await stat7(absolute);
57581
58041
  if (!info.isFile())
57582
58042
  throw new Error(`${absolute} is not a file`);
@@ -57756,6 +58216,7 @@ var app = make39("scratchpad").pipe(withDescription4("Working memory for coding
57756
58216
  init,
57757
58217
  path,
57758
58218
  doctor,
58219
+ du,
57759
58220
  skillsCommand,
57760
58221
  backlogCommand,
57761
58222
  feedback,