@aryasaatvik/scratchpad 0.6.3 → 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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## @aryasaatvik/scratchpad@0.7.0
2
+
3
+ ### Keep the Scratchpad from silently growing
4
+
5
+ `scratchpad du` lists the largest folders and files under the notes root, and flags run artifacts copied in as evidence: Playwright traces, videos, tarballs, extracted binaries, and copied trees such as `node_modules`. `doctor` reports the total and warns past `lifecycle.storage.budgetMB` (default 1 GB). `sweep` now previews that bulk once every record that owns it has a closed `status`, even when a note links it. The scratchpad skill tells agents to keep receipts and links, not copies of runs.
6
+
7
+ ### Recover a missing mount directory with `scratchpad pull --full`
8
+
9
+ When a GitHub mount directory disappears while the store still maps objects to it, `pull`, `push` and `sync` still refuse to run, and the error now names the fix: `scratchpad pull --full` recreates the directory and re-projects every open object and recent closure in one pass, after which `push` plans no closes. Previously the error pointed at `scratchpad repair`, which only resolves conflicts. `scratchpad sweep` no longer offers files under a configured mount, because trashing one would close its remote issue on the next push.
10
+
1
11
  ## @aryasaatvik/scratchpad@0.6.3
2
12
 
3
13
  ### Build the search index faster
package/README.md CHANGED
@@ -39,7 +39,8 @@ These commands need no config. Run them in any project directory or worktree.
39
39
 
40
40
  ```sh
41
41
  scratchpad path # where this project's notes live
42
- scratchpad doctor # project id, layout drift, store, token
42
+ scratchpad doctor # project id, layout drift, size, store, token
43
+ scratchpad du # largest folders and files, budget, run bulk
43
44
  scratchpad skills get scratchpad # the agent skill that drives these commands
44
45
  scratchpad feedback new "<what went wrong>" # record instruction feedback
45
46
  scratchpad search "deployment decision" # hybrid text and vector search over notes
@@ -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.3",
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", {
@@ -55519,7 +55896,7 @@ var embed = (embedder, texts) => tryPromise2({ try: () => embedder.embed(texts),
55519
55896
  import { Database as Database4 } from "bun:sqlite";
55520
55897
  import { createHash as createHash12 } from "crypto";
55521
55898
  import { chmodSync, mkdirSync as mkdirSync4, readFileSync as readFileSync2, readdirSync as readdirSync2, realpathSync as realpathSync2, rmSync } from "fs";
55522
- import { basename as basename7, join as join15 } from "path";
55899
+ import { basename as basename7, join as join16 } from "path";
55523
55900
 
55524
55901
  // packages/cli/src/search/chunk.ts
55525
55902
  import { createHash as createHash11 } from "crypto";
@@ -55622,12 +55999,12 @@ var chunkMarkdown = (notePath, title, content, maxChars = 700) => {
55622
55999
  // packages/cli/src/search/store.ts
55623
56000
  import { Database as Database3 } from "bun:sqlite";
55624
56001
  import { mkdirSync as mkdirSync3 } from "fs";
55625
- import { dirname as dirname15 } from "path";
56002
+ import { dirname as dirname16 } from "path";
55626
56003
 
55627
56004
  class SearchStore {
55628
56005
  db;
55629
56006
  constructor(path) {
55630
- mkdirSync3(dirname15(path), { recursive: true });
56007
+ mkdirSync3(dirname16(path), { recursive: true });
55631
56008
  this.db = new Database3(path, { create: true });
55632
56009
  this.db.exec(`PRAGMA busy_timeout=0;
55633
56010
  CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, hash TEXT NOT NULL);
@@ -55772,7 +56149,7 @@ var Metadata = Struct({
55772
56149
  title: optional2(String5),
55773
56150
  kind: optional2(String5)
55774
56151
  });
55775
- 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));
55776
56153
  var fuse = (lists) => {
55777
56154
  const scores = new Map;
55778
56155
  for (const list of lists)
@@ -55796,7 +56173,7 @@ var scan = (roots) => {
55796
56173
  return;
55797
56174
  visited.add(physical);
55798
56175
  for (const entry of readdirSync2(physical, { withFileTypes: true })) {
55799
- const path = join15(physical, entry.name);
56176
+ const path = join16(physical, entry.name);
55800
56177
  if (entry.isDirectory() && !entry.name.startsWith("."))
55801
56178
  walk(path);
55802
56179
  else if (entry.isFile() && /\.md$/i.test(entry.name))
@@ -55811,7 +56188,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55811
56188
  try: () => {
55812
56189
  mkdirSync4(options.directory, { recursive: true, mode: 448 });
55813
56190
  chmodSync(options.directory, 448);
55814
- const lock = new Database4(join15(options.directory, "lock.db"), { create: true });
56191
+ const lock = new Database4(join16(options.directory, "lock.db"), { create: true });
55815
56192
  try {
55816
56193
  lock.exec("BEGIN IMMEDIATE");
55817
56194
  return lock;
@@ -55828,7 +56205,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55828
56205
  });
55829
56206
  if (options.rebuild)
55830
56207
  yield* tryPromise2({
55831
- try: () => assertRebuildAvailable(join15(directory, "vectors")),
56208
+ try: () => assertRebuildAvailable(join16(directory, "vectors")),
55832
56209
  catch: searchError
55833
56210
  });
55834
56211
  yield* try_3({
@@ -55841,7 +56218,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55841
56218
  catch: searchError
55842
56219
  });
55843
56220
  const store = yield* acquireRelease2(try_3({
55844
- try: () => new SearchStore(join15(directory, "index.db")),
56221
+ try: () => new SearchStore(join16(directory, "index.db")),
55845
56222
  catch: searchError
55846
56223
  }), (s) => sync2(() => s.close()));
55847
56224
  const sources = yield* try_3({ try: () => scan(options.roots), catch: searchError });
@@ -55854,7 +56231,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55854
56231
  oldByPath.set(chunk.notePath, list);
55855
56232
  }
55856
56233
  const files = new Map(store.files().map((f) => [f.path, f.hash]));
55857
- const vectorPath = join15(directory, "vectors");
56234
+ const vectorPath = join16(directory, "vectors");
55858
56235
  const vectorWriter = options.embedder ? yield* acquireRelease2(tryPromise2({ try: () => writer(vectorPath), catch: searchError }), (c) => sync2(() => c.closeSync())) : undefined;
55859
56236
  const vectorEmpty = vectorWriter?.stats.docCount === 0;
55860
56237
  let changed = 0;
@@ -55940,7 +56317,7 @@ var run6 = fn2("Search.run")(function* (options, query) {
55940
56317
  let hits = [];
55941
56318
  if (query) {
55942
56319
  const store = yield* acquireRelease2(try_3({
55943
- try: () => new SearchStore(join15(summary.directory, "index.db")),
56320
+ try: () => new SearchStore(join16(summary.directory, "index.db")),
55944
56321
  catch: searchError
55945
56322
  }), (s) => sync2(() => s.close()));
55946
56323
  const eligible = summary.chunks.filter((c) => query.kind === undefined || c.kind === query.kind);
@@ -55959,7 +56336,7 @@ Query: ${query.text}`
55959
56336
  if (!vector)
55960
56337
  return yield* new SearchError({ message: "Embedder omitted query vector" });
55961
56338
  vectorIds = yield* tryPromise2({
55962
- 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())),
55963
56340
  catch: searchError
55964
56341
  });
55965
56342
  }
@@ -55998,9 +56375,9 @@ var execute = (options, query) => gen3(function* () {
55998
56375
  });
55999
56376
  const roots = [project.notesRoot];
56000
56377
  if (options.global)
56001
- roots.push(join16(globalNotesRoot(), "feedback"));
56378
+ roots.push(join17(globalNotesRoot(), "feedback"));
56002
56379
  const report = yield* run6({
56003
- directory: join16(dirname16(stateDbPath(project.projectId, configRoot, config.mounts)), "search"),
56380
+ directory: join17(dirname17(stateDbPath(project.projectId, configRoot, config.mounts)), "search"),
56004
56381
  roots,
56005
56382
  ...key ? { embedder: openRouter(key) } : {},
56006
56383
  ...options.rebuild ? { rebuild: true } : {}
@@ -56485,7 +56862,8 @@ Report without editing:
56485
56862
  - the backlog graph from \`scratchpad backlog graph\` and any problems from
56486
56863
  \`scratchpad backlog validate\`;
56487
56864
  - top-level folders and loose files outside the layout, from \`scratchpad doctor\`;
56488
- - 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\`;
56489
56867
  - obvious stale-state risks that need reconciliation.
56490
56868
 
56491
56869
  For a large tree, split the inventory into bounded, non-overlapping areas. Keep the same output
@@ -56632,6 +57010,17 @@ scratchpad sweep --json # version 1 report
56632
57010
  scratchpad sweep --apply # move expired artifacts to the Trash with receipts
56633
57011
  \`\`\`
56634
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
+
56635
57024
  Run the preview freely. Run \`--apply\` only when the user or the project's maintenance role
56636
57025
  authorizes it, and report the totals. Read-only files or parents are reported as refused with a
56637
57026
  warning and exit 0; they are not failures. Existing \`archive/\` contents are ordinary sweep
@@ -56897,11 +57286,12 @@ files and one writer per file.
56897
57286
 
56898
57287
  Notes are kept while true and archived (to the Trash) once they stop supporting current work;
56899
57288
  artifacts (non-\`.md\`/\`.html\` files) expire through \`scratchpad sweep\` after
56900
- \`lifecycle.artifacts.maxAgeDays\` (default 14). Link a file from a note to protect it. Prefer one
56901
- copy linked from the relevant record. Keep raw traces, builds, and exports only when they support a
56902
- current investigation or a deliberate retention need; record that reason and an exit condition. Do
56903
- not infer deletion authority from \`tmp/\`, age, or a duplicate hash alone; \`sweep --apply\` runs only
56904
- 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.
56905
57295
 
56906
57296
  Promote durable product decisions into the existing owning tracked doc under the project's root
56907
57297
  \`docs/\` where appropriate. Keep temporary research and delivery history in Scratchpad. Migration
@@ -57010,7 +57400,7 @@ the request and current state.
57010
57400
  | \`feedback\` | Capture or inspect instruction friction | \`feedback new\`, \`feedback list\`, \`feedback review\`; \`--ref instruction-feedback\` |
57011
57401
  | \`reconcile\` (\`sync\`) | Reconcile active notes with current truth, then update or archive | \`--ref modes\` |
57012
57402
  | \`review\` | Judge note kind and staleness against repository evidence | \`review [paths] [--apply] [--json]\`; \`--ref modes\` |
57013
- | \`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\` |
57014
57404
  | \`extract\` | Promote stable facts into tracked docs, tests, or ADRs | \`--ref modes\` |
57015
57405
 
57016
57406
  \`sync\` is this skill's alias for \`reconcile\`; keep accepting it. It is not \`scratchpad sync\`, which
@@ -57020,6 +57410,15 @@ This skill's \`reconcile\` covers \`.scratchpad\` only. Repo-wide Markdown plus
57020
57410
  auto-memories belong to the \`reconcile\` skill. Workflows such as \`delivery\` supply approved backlog
57021
57411
  content and execution evidence; this skill owns its representation and lifecycle.
57022
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
+
57023
57422
  ## Note lifecycle
57024
57423
 
57025
57424
  Notes may declare \`kind\`, \`status\`, \`updated\`, \`reviewed\`, \`superseded_by\`, and \`expires\` in front
@@ -57393,14 +57792,14 @@ var skillsPathCommand = make39("path", { json: jsonFlag }, ({ json }) => {
57393
57792
  var skillsCommand = make39("skills").pipe(withDescription4("List and print embedded agent skills"), withSubcommands([skillsListCommand, skillsGetCommand, skillsPathCommand]));
57394
57793
 
57395
57794
  // packages/cli/src/commands/status.ts
57396
- import { join as join17 } from "path";
57795
+ import { join as join18 } from "path";
57397
57796
  var readDirectory2 = (fs, directory, name, depth) => gen3(function* () {
57398
57797
  const entries = yield* fs.readDirectory(directory);
57399
57798
  const sorted = entries.toSorted((a, b) => a.localeCompare(b));
57400
57799
  const directories = [];
57401
57800
  let files = 0;
57402
57801
  for (const entry of sorted) {
57403
- const path = join17(directory, entry);
57802
+ const path = join18(directory, entry);
57404
57803
  const info = yield* fs.stat(path);
57405
57804
  if (info.type === "Directory") {
57406
57805
  if (depth > 0)
@@ -57475,11 +57874,11 @@ var status = make39("status", {
57475
57874
  }).pipe(provide4(Workspace2.layer), json ? provideService2(MinimumLogLevel2, "None") : identity)).pipe(withDescription4("Show repo, mount, pending-outbox, and conflict counts"));
57476
57875
 
57477
57876
  // packages/cli/src/commands/sweep.ts
57478
- import { lstat as lstat12, realpath as realpath11 } from "fs/promises";
57479
- import { join as join19 } from "path";
57877
+ import { lstat as lstat13, realpath as realpath12 } from "fs/promises";
57878
+ import { join as join20 } from "path";
57480
57879
 
57481
57880
  // packages/cli/src/lifecycle/candidates.ts
57482
- import { join as join18, basename as basename8 } from "path";
57881
+ import { join as join19, basename as basename8 } from "path";
57483
57882
  var noteCandidates = (context) => gen3(function* () {
57484
57883
  const status = yield* classifierStatus;
57485
57884
  if (!status.enabled)
@@ -57490,8 +57889,8 @@ var noteCandidates = (context) => gen3(function* () {
57490
57889
  return [];
57491
57890
  const report = yield* projectReview({
57492
57891
  notesRoot: context.root,
57493
- files: eligible.map((file) => join18(context.root, file.path)),
57494
- 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)),
57495
57894
  config: context.config,
57496
57895
  ...context.configRoot === undefined ? {} : { configRoot: context.configRoot },
57497
57896
  apply: false,
@@ -57520,11 +57919,11 @@ var selectNoteCandidates = (context, notes) => {
57520
57919
 
57521
57920
  // packages/cli/src/commands/sweep.ts
57522
57921
  var sweepFiles = fn2("maintenance.sweepFiles")(function* (apply, sources) {
57523
- const { root, candidates, files } = yield* collectCandidates(sources ?? [artifactCandidates, noteCandidates]);
57922
+ const { root, candidates, files } = yield* collectCandidates(sources ?? [artifactCandidates, bulkCandidates, noteCandidates]);
57524
57923
  const refused = [];
57525
57924
  const accepted = [];
57526
57925
  for (const entry of candidates) {
57527
- if (yield* maintenanceIO(() => writableEntry(join19(root, entry.path))))
57926
+ if (yield* maintenanceIO(() => writableEntry(join20(root, entry.path))))
57528
57927
  accepted.push(entry);
57529
57928
  else
57530
57929
  refused.push({ path: entry.path, reason: "read-only file or parent directory" });
@@ -57533,21 +57932,36 @@ var sweepFiles = fn2("maintenance.sweepFiles")(function* (apply, sources) {
57533
57932
  if (apply && accepted.length) {
57534
57933
  const log = yield* prepareTrashLog(root);
57535
57934
  const snapshots = new Map(files.map((file) => [file.path, file]));
57536
- for (const entry of accepted) {
57537
- 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";
57538
57951
  const moved = yield* trashWithReceipt(root, entry, log, async () => {
57539
- const absolute = join19(root, entry.path);
57540
- const current = await lstat12(absolute).catch((error2) => {
57541
- if (error2.code !== "ENOENT")
57542
- throw error2;
57543
- return;
57544
- });
57545
- 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;
57546
57960
  });
57547
57961
  if (moved)
57548
57962
  trashed.push(entry);
57549
57963
  else
57550
- refused.push({ path: entry.path, reason: "file changed since candidate scan" });
57964
+ refused.push({ path: entry.path, reason });
57551
57965
  }
57552
57966
  }
57553
57967
  const refusedPaths = new Set(refused.map((entry) => entry.path));
@@ -57579,12 +57993,12 @@ ${group.entries.map((entry) => ` ${entry.path} (${entry.bytes} bytes)`).join(`
57579
57993
  for (const entry of result.refused)
57580
57994
  yield* error(`Warning: ${entry.path}: ${entry.reason}`);
57581
57995
  }
57582
- }).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"));
57583
57997
 
57584
57998
  // packages/cli/src/commands/upload.ts
57585
57999
  import { createHash as createHash13 } from "crypto";
57586
58000
  import { stat as stat7 } from "fs/promises";
57587
- import { basename as basename9, resolve as resolve20 } from "path";
58001
+ import { basename as basename9, resolve as resolve21 } from "path";
57588
58002
  var uploadContentTypes = {
57589
58003
  png: "image/png",
57590
58004
  jpg: "image/jpeg",
@@ -57622,7 +58036,7 @@ var uploadFiles = async (options) => {
57622
58036
  const client = clientForProfile(target.profile);
57623
58037
  const uploads = [];
57624
58038
  for (const path of options.paths) {
57625
- const absolute = resolve20(cwd(), path);
58039
+ const absolute = resolve21(cwd(), path);
57626
58040
  const info = await stat7(absolute);
57627
58041
  if (!info.isFile())
57628
58042
  throw new Error(`${absolute} is not a file`);
@@ -57802,6 +58216,7 @@ var app = make39("scratchpad").pipe(withDescription4("Working memory for coding
57802
58216
  init,
57803
58217
  path,
57804
58218
  doctor,
58219
+ du,
57805
58220
  skillsCommand,
57806
58221
  backlogCommand,
57807
58222
  feedback,
@@ -61,6 +61,28 @@ reports the planned delete without mutating anything. Remote deletion is availab
61
61
  this explicit command, not through filesystem removal. See
62
62
  [ADR 0007](adr/0007-explicit-remote-delete.md).
63
63
 
64
+ ## Recovering a missing mount directory
65
+
66
+ Losing a whole mount directory is not a deletion. While the store still maps objects to a missing
67
+ mount directory, `pull`, `push` and `sync` refuse to run, so the loss can never read as "close
68
+ every issue". The one recovery is a full pull, which recreates the directories and re-projects
69
+ every open object from GitHub (and recent closures into the archive mount) in one pass:
70
+
71
+ ```sh
72
+ scratchpad pull --full --dry-run # preview the writes and retirements; changes nothing
73
+ scratchpad pull --full # recreate the directory and its files
74
+ scratchpad push --dry-run # should plan no closes
75
+ ```
76
+
77
+ Only a full listing proves which objects belong in the directory, so an incremental `pull` and
78
+ `sync --full` keep refusing. While a restore runs, the directory holds a
79
+ `.scratchpad-restore-pending` marker that is removed only when the pull succeeds; if the restore is
80
+ interrupted, every other command keeps refusing until `scratchpad pull --full` is re-run. Objects
81
+ deleted or transferred on GitHub have nothing to restore: a full pull retires their mappings
82
+ (`remote-missing`) so the next push doesn't try to close them. Local edits that were never pushed went with the directory; a pull
83
+ restores the provider's copy. `scratchpad sweep` never offers files under a configured mount,
84
+ because trashing one would close its remote object on the next push.
85
+
64
86
  ## Backlog file contract
65
87
 
66
88
  Backlog files follow the Scratchpad skill's contract: `status` is free text in the repository's
@@ -76,6 +76,10 @@ the default list. `scratchpad doctor` reports drift; see [notes.md](notes.md#doc
76
76
  - `notes.minFreshDays`: at least 0, default 7. Recently updated notes are protected.
77
77
  - `notes.estimatedCostPerCall`: at least 0, USD, default 0.001. Fallback when OpenRouter reports
78
78
  no cost; labeled an estimate.
79
+ - `storage.budgetMB`: greater than 0, default 1024. `doctor` and `du` warn when the notes root is
80
+ larger.
81
+ - `storage.bulkMB`: greater than 0, default 5. Traces, videos, archives, and executables at or over
82
+ it are bulk; `sweep` retires bulk whose owning records are closed.
79
83
  - `protect`: globs of notes and artifacts that `sweep` never removes. Manual `archive` does not
80
84
  check these globs.
81
85
 
@@ -83,8 +87,10 @@ Behavior: [lifecycle.md](lifecycle.md).
83
87
 
84
88
  ### `search`
85
89
 
86
- `embeddings: false` opts out of hybrid search even when an OpenRouter key is present. Config
87
- discovery walks upward, so ancestor opt-outs apply too. See [search.md](search.md).
90
+ `embeddings: false` opts out of hybrid search even when an OpenRouter key is present. Discovery
91
+ selects the nearest `scratchpad.config.ts` and does not merge ancestors, so an ancestor opt-out
92
+ applies only when that config is selected; a nearer config without `embeddings: false` does not
93
+ inherit it. See [search.md](search.md).
88
94
 
89
95
  ### `classifier`
90
96
 
package/docs/feedback.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # Instruction feedback and routing
2
2
 
3
3
  Agents record corrections and friction as feedback notes. The CLI writes them deterministically and
4
- may classify them with an optional decision model.
4
+ may classify them with an optional decision model. An occurrence's body is immutable after capture:
5
+ corrections and new evidence go in the linked review record, and the CLI only manages front matter.
5
6
 
6
7
  ## Commands
7
8
 
@@ -16,20 +17,36 @@ scratchpad route "<correction>" [--write] [--json]
16
17
 
17
18
  - `feedback new` writes a feedback file under the notes root's `feedback/`; `--slug` overrides the
18
19
  file-name slug derived from the text.
19
- - `feedback normalize` adopts legacy feedback without changing bodies; preview with
20
- `feedback normalize --global --dry-run --json`.
20
+ - `feedback normalize` adopts only the legacy classes it can decode safely: `no-front-matter`,
21
+ `legacy-recorded` (a `recorded` header with no `kind`), and `missing-occurred_at`. It refuses
22
+ ambiguous or undecodable headers and occurrences with no derivable `occurred_at`. Adopted bodies
23
+ keep their bytes, already valid occurrences are unchanged, and `--dry-run` previews the result.
21
24
  - `feedback review` lists feedback with no disposition or an open disposition; `--classify`
22
25
  classifies unclassified entries first and needs a classifier.
23
26
  - `feedback list` filters by status (`new`, `review`, `classified`) and disposition (repeatable);
24
27
  `--all` includes dismissed, installed, and verified occurrences.
25
28
  - `feedback resolve` records a review disposition (`open`, `deferred`, `dismissed`, `source-fixed`,
26
29
  `installed`, `verified`) on one occurrence. The occurrence is the id after the last `-` in the
27
- file name, the file name with or without `.md`, or a path. `--review` names the review record in
28
- `feedback/reviews/` (this scope's, then the global one) or a path; `--evidence` takes a commit,
29
- PR URL, or path and is repeatable.
30
+ file name, the file name with or without `.md`, or a path. `--review` must resolve to an existing
31
+ `.md` file directly inside `feedback/reviews/` (this scope's, then the global one). A bare name,
32
+ with or without `.md`, or a path is accepted; directories and globs are not. `--evidence` takes a
33
+ commit, PR URL, or path and is repeatable.
30
34
  - `route` suggests which instruction layer a correction belongs to; `--write` also records it as a
31
35
  feedback file.
32
36
 
37
+ ## Dispositions
38
+
39
+ `feedback resolve` records what a review concluded, in the front matter of the occurrence:
40
+
41
+ - `open`: not yet decided.
42
+ - `deferred`: accepted, but not acted on yet.
43
+ - `dismissed`: no change is warranted.
44
+ - `source-fixed`: the source change has landed, with evidence linked from the review record;
45
+ an unlanded working-tree edit or unmerged branch does not qualify.
46
+ - `installed`: the installed copy in use is updated and matches the reviewed source.
47
+ - `verified`: representative behavior was exercised with the applicable installed version;
48
+ static inspection alone does not qualify.
49
+
33
50
  ## Global feedback home
34
51
 
35
52
  `--global` feedback lives in `~/.scratchpad` (override with `SCRATCHPAD_GLOBAL_HOME`). Use it for
package/docs/lifecycle.md CHANGED
@@ -6,7 +6,7 @@ stale ones to the operating system's Trash, where they stay recoverable.
6
6
  ```
7
7
  scratchpad archive <paths...> --reason "<why>" # move notes or directories to the OS Trash
8
8
  scratchpad review [paths...] [--apply] [--json] [--limit 100] # classify notes; --apply writes metadata
9
- scratchpad sweep [--apply] [--json] # preview expired artifacts; --apply moves to Trash
9
+ scratchpad sweep [--apply] [--json] # preview expired artifacts and closed bulk; --apply moves to Trash
10
10
  ```
11
11
 
12
12
  `archive` moves the given paths to Trash immediately; it has no preview. `sweep --apply` moves
@@ -46,6 +46,18 @@ artifacts. Symlinks are not traversed or swept. Windows come from `lifecycle.art
46
46
  `sweep` also consumes cached note verdicts, as described under [Review](#review). It never calls
47
47
  the model.
48
48
 
49
+ ### Bulk
50
+
51
+ Run artifacts copied into the notes root are swept by ownership rather than age, in the `bulk`
52
+ group. Bulk is what `scratchpad du` flags (see [notes.md](notes.md#du)). A record owns a bulk file
53
+ when it is a note linking the file or one of its folders, or the `README.md` of the file's nearest
54
+ folder below the notes root. Links to the notes root itself, and notes inside copied trees, are not
55
+ owners. A bulk file is a candidate when it has at least one owner and every owner's front matter
56
+ `status` is closed (`backlog.closedStatuses`, defaulting to `done`, `complete`, `merged`, and the
57
+ rest of the backlog list). Links protect artifacts from expiry but not bulk from this group;
58
+ `lifecycle.protect` globs, `README.md`, `STATE.md`, and the receipt log still protect it. Bulk with
59
+ no owner is left to artifact expiry.
60
+
49
61
  ### Sweep JSON, version 1
50
62
 
51
63
  `sweep --json` emits version 1 of the report: `version: 1`, `apply`, `groups`, `totalBytes`,
package/docs/notes.md CHANGED
@@ -55,6 +55,24 @@ A list given in config replaces the corresponding default list; see
55
55
 
56
56
  `doctor` also reports the project id, notes root and its source, whether a config was found, the
57
57
  state store, the selected classifier model and whether it is enabled, and GitHub auth availability.
58
+ Its `storage` section gives the total size, the budget, and the flagged bulk, and warns on stderr
59
+ when either needs attention; `scratchpad du` has the detail.
60
+
61
+ ### `du`
62
+
63
+ ```
64
+ scratchpad du [--depth 2] [--top 10] [--json]
65
+ ```
66
+
67
+ `du` totals the notes root, lists the largest folders (to `--depth`) and files, and lists the run
68
+ artifacts the evidence policy flags as bulk: traces, videos, archives, and executables at or over
69
+ `lifecycle.storage.bulkMB` (default 5), and copied trees (`node_modules`, `.git`, `test-results`,
70
+ `playwright-report`, `blob-report`, `.next`, `.turbo`, `*.app`, `*.framework`) collapsed to their
71
+ root folder. Markdown and HTML are never bulk. It warns when the total exceeds
72
+ `lifecycle.storage.budgetMB` (default 1024). JSON version 1 holds `totalBytes`, `fileCount`,
73
+ `budgetBytes`, `overBudget`, `bulkThresholdBytes`, `folders`, `files`, and `bulk` (`bytes`,
74
+ `count`, `entries`). Warnings are not failures; `du` exits 0. See
75
+ [lifecycle.md](lifecycle.md#bulk) for how `sweep` retires bulk.
58
76
 
59
77
  ### Skills
60
78
 
package/docs/search.md CHANGED
@@ -29,7 +29,9 @@ mode `0600`. Hybrid indexing sends note title, heading and chunk text to OpenRou
29
29
  `qwen/qwen3-embedding-8b` model at 1024 dimensions; queries are sent there too.
30
30
 
31
31
  To opt out even when a key is present, set `search: { embeddings: false }` in
32
- `scratchpad.config.ts`. Config discovery walks upward, so ancestor opt-outs apply too.
32
+ `scratchpad.config.ts`. Discovery selects the nearest config and does not merge ancestors, so an
33
+ ancestor opt-out applies only when that config is the one selected; a nearer config that omits
34
+ `embeddings` does not inherit it.
33
35
 
34
36
  ## Index location
35
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aryasaatvik/scratchpad",
3
- "version": "0.6.3",
3
+ "version": "0.7.0",
4
4
  "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.",
5
5
  "keywords": [
6
6
  "bun",