synabun 2.4.0 → 2.4.2
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 +47 -0
- package/README.md +1 -1
- package/browser-extension/content.js +73 -11
- package/browser-extension/engine.js +196 -15
- package/browser-extension/manifest.json +4 -2
- package/browser-extension/popup-strings.js +10 -4
- package/browser-extension/popup-view.js +1 -1
- package/browser-extension/popup.css +1 -0
- package/browser-extension/popup.html +4 -1
- package/browser-extension/popup.js +22 -10
- package/browser-extension/protocol.js +102 -11
- package/browser-extension/service-worker.js +20 -4
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +25 -5
- package/lib/data-home-files.js +47 -0
- package/lib/data-home-migration.js +34 -58
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +6 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +13 -8
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +35 -15
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +23 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +33 -14
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +266 -2
- package/neural-interface/i18n/pt-BR.json +267 -3
- package/neural-interface/lib/agents/builtins.json +207 -0
- package/neural-interface/lib/agents/registry.js +60 -15
- package/neural-interface/lib/agents/resolve.js +69 -10
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-brains/opencode.js +60 -11
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +384 -119
- package/neural-interface/lib/assistant-persona.js +17 -5
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +181 -54
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +48 -34
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +836 -322
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +109 -24
- package/neural-interface/lib/browser-extension-bridge.js +42 -8
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +34 -14
- package/neural-interface/lib/opencode-build-preflight.js +30 -8
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/peer-identity.js +13 -8
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +70 -44
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +196 -97
- package/neural-interface/lib/teams/schema.js +1 -1
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +260 -0
- package/neural-interface/public/offline.html +4 -3
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
- package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +3 -2
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +106 -38
- package/neural-interface/public/shared/assistant/asst-route.js +102 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cc-dropdown.js +21 -15
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -51
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/owner-authority-view.js +4 -10
- package/neural-interface/public/shared/page-session.js +1 -1
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/start-bridge.js +2 -2
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +354 -438
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +185 -25
- package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-owner-authority.js +48 -25
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +234 -67
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-sync.js +1 -0
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/sw.js +4 -3
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +17 -4
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +507 -160
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// What a finished run's scratch folder is still needed for.
|
|
2
|
+
//
|
|
3
|
+
// A run's records name its folder all the time: the run view carries `scratchDir`, every status answer the brain
|
|
4
|
+
// reads is saved in its transcript, and the worker's own commands and tool output are full of the path. None of that
|
|
5
|
+
// means a file is still used. What is used after a run ends is what SynaBun shows as its output: the result (summary,
|
|
6
|
+
// changes, files, media, follow-ups, question), the message text, a review, a follow-up, a schedule or a team record
|
|
7
|
+
// that names a file. So:
|
|
8
|
+
// - a reference is a path to something INSIDE a run's folder; the folder itself is only a mention;
|
|
9
|
+
// - tool calls, tool results, reasoning and launch metadata are never read as references;
|
|
10
|
+
// - a reference is matched against the names really on disk, so a path with spaces or followed by prose is exact.
|
|
11
|
+
// No file access here: the caller hands in `list` and `realpath`.
|
|
12
|
+
|
|
13
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
14
|
+
import { parseFileLinkTarget } from '../public/shared/file-links.js';
|
|
15
|
+
|
|
16
|
+
export const RUN_ID = /^[a-f0-9]{32}$/;
|
|
17
|
+
export const MAX_REFS_PER_RUN = 4096;
|
|
18
|
+
const MAX_TAIL = 1024;
|
|
19
|
+
const MAX_DEPTH = 128;
|
|
20
|
+
const REFERENCE = /(?:^|[^\w])scratch\/+([a-f0-9]{32})(?![a-f0-9])/gi;
|
|
21
|
+
export const HAS_SCRATCH = /scratch/i;
|
|
22
|
+
const INSIDE_SCRATCH = /(?:^|\/)scratch\/+[a-f0-9]{32}(?:\/|$)/i;
|
|
23
|
+
// What can follow a name in prose or Markdown. A dot counts only at the end of a sentence.
|
|
24
|
+
const BOUNDARY = /^(?:$|[\s"'`)\]}>,;:!?#|*]|\.(?:$|[\s"'`)\]}>,;:!?#|*]))/;
|
|
25
|
+
const EMPHASIS = /^\*+(?:[\s),;:]|\.(?:\s|$)|$)/;
|
|
26
|
+
const GLOB = /^[^\s/]*(?:\*|\[[^\]\s]*\]|\{[^}\s]*\})/;
|
|
27
|
+
|
|
28
|
+
// Blocks and events that record what a tool did, not what the run reported.
|
|
29
|
+
const TOOL_TYPES = new Set([
|
|
30
|
+
'tool_use', 'tool_result', 'server_tool_use', 'mcp_tool_use', 'mcp_tool_result', 'thinking', 'redacted_thinking',
|
|
31
|
+
'stream_event', 'command_execution', 'file_change', 'mcp_tool_call', 'web_search', 'todo_list', 'reasoning',
|
|
32
|
+
'tool_call', 'tool_call_update', 'synabun.permission_request', 'synabun.permission_resolved', 'synabun.confinement',
|
|
33
|
+
]);
|
|
34
|
+
// Launch metadata, permission requests and tool input. `original` is where a media file was copied from: the page
|
|
35
|
+
// serves the copy in data/media.
|
|
36
|
+
const SKIPPED_KEYS = new Set([
|
|
37
|
+
'scratchDir', 'sandboxPlan', 'resumeInfo', 'notes', 'extraEnv', 'tools', 'toolsRequested', 'tool_use_result', 'input',
|
|
38
|
+
'arguments', 'rawInput', 'rawOutput', 'request', 'pending', 'usage', 'usageState', 'tokens', 'image', 'images', 'original',
|
|
39
|
+
]);
|
|
40
|
+
// What a run was asked to do: it can name another run's file, and never makes its own folder worth keeping.
|
|
41
|
+
const INPUT_KEYS = new Set(['task', 'context', 'brief', 'rawSpec', 'teamBrief', 'team', 'promptPreview']);
|
|
42
|
+
|
|
43
|
+
// A run, a schedule or a session working IN a folder needs all of it, whatever its state.
|
|
44
|
+
const WORKDIR_KEYS = new Set(['cwd', 'project', 'projectPath', 'workingDirectory', 'workdir', 'worktree']);
|
|
45
|
+
const SCRATCH_RUN = /(?:^|[\\/])scratch[\\/]+([a-f0-9]{32})(?:[\\/]|$)/i;
|
|
46
|
+
|
|
47
|
+
const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
48
|
+
|
|
49
|
+
/** The run whose scratch folder holds this path, else null. */
|
|
50
|
+
export function scratchRunOf(path) {
|
|
51
|
+
return SCRATCH_RUN.exec(String(path ?? ''))?.[1].toLowerCase() ?? null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** How this platform compares names: macOS and Windows folders are normally case-insensitive. */
|
|
55
|
+
export function foldFor(platform = process.platform) {
|
|
56
|
+
return platform === 'darwin' || platform === 'win32'
|
|
57
|
+
? (text) => text.normalize('NFC').toLowerCase()
|
|
58
|
+
: (text) => text.normalize('NFC');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function spellings(text) {
|
|
62
|
+
const slashed = text.includes('\\') ? text.replace(/\\+/g, '/') : text;
|
|
63
|
+
if (!slashed.includes('%')) return [slashed];
|
|
64
|
+
const decoded = slashed.replace(/(?:%[0-9a-f]{2})+/gi, (part) => {
|
|
65
|
+
try { return decodeURIComponent(part); } catch { return part; }
|
|
66
|
+
});
|
|
67
|
+
return decoded === slashed ? [slashed] : [slashed, decoded];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function linkTargets(text) {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const match of text.matchAll(/\]\(\s*<?([^)\s>]{1,2048})/g)) out.push(match[1]);
|
|
73
|
+
for (const match of text.matchAll(/`([^`\n]{1,1024})`/g)) out.push(match[1].trim());
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The references one source holds, by the run whose folder they point into. */
|
|
78
|
+
export function createReferenceIndex() {
|
|
79
|
+
const byRun = new Map();
|
|
80
|
+
const overflow = new Set();
|
|
81
|
+
const workdirs = new Set();
|
|
82
|
+
|
|
83
|
+
function add(run, tail) {
|
|
84
|
+
let tails = byRun.get(run);
|
|
85
|
+
if (!tails) byRun.set(run, tails = new Set());
|
|
86
|
+
if (tails.has(tail)) return;
|
|
87
|
+
if (tails.size >= MAX_REFS_PER_RUN) { overflow.add(run); return; }
|
|
88
|
+
tails.add(tail);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function addText(value, { except = null, cwd = null } = {}) {
|
|
92
|
+
if (typeof value !== 'string' || (!HAS_SCRATCH.test(value) && !cwd)) return;
|
|
93
|
+
for (const text of spellings(value)) {
|
|
94
|
+
for (const match of text.matchAll(REFERENCE)) {
|
|
95
|
+
const run = match[1].toLowerCase();
|
|
96
|
+
if (run === except) continue;
|
|
97
|
+
const from = match.index + match[0].length;
|
|
98
|
+
if (text[from] !== '/') continue; // the folder itself
|
|
99
|
+
const line = text.slice(from, from + MAX_TAIL).split(/[\r\n]/, 1)[0].replace(/^\/+/, '');
|
|
100
|
+
if (!line || /^\s/.test(line)) continue; // the folder, then prose
|
|
101
|
+
add(run, line);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (!cwd) return;
|
|
105
|
+
// A run rooted in its scratch folder writes relative links, which the page resolves against that folder.
|
|
106
|
+
for (const target of linkTargets(value)) {
|
|
107
|
+
for (const path of parseFileLinkTarget(target, { cwd })?.candidates || []) addText(path, { except });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function addPath(value, { cwd = null, realpath = null, except = null } = {}) {
|
|
112
|
+
if (typeof value !== 'string' || !value.trim()) return;
|
|
113
|
+
const written = value.trim();
|
|
114
|
+
const path = !isAbsolute(written) && cwd ? resolve(cwd, written) : written;
|
|
115
|
+
addText(path, { except });
|
|
116
|
+
if (!realpath || !isAbsolute(path)) return;
|
|
117
|
+
const real = realpath(path); // a project file can be a link into scratch
|
|
118
|
+
if (real && real !== path) addText(real, { except });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Every string a person can be shown in this value, without tool calls, tool output or launch metadata. */
|
|
122
|
+
function addVisible(value, options = {}) {
|
|
123
|
+
const stack = [[value, 0]];
|
|
124
|
+
while (stack.length) {
|
|
125
|
+
const [item, depth] = stack.pop();
|
|
126
|
+
if (typeof item === 'string') { addText(item, options); continue; }
|
|
127
|
+
if (!item || typeof item !== 'object' || depth > MAX_DEPTH) continue;
|
|
128
|
+
if (Array.isArray(item)) { for (const child of item) stack.push([child, depth + 1]); continue; }
|
|
129
|
+
if (typeof item.type === 'string' && TOOL_TYPES.has(item.type)) continue;
|
|
130
|
+
for (const [key, child] of Object.entries(item)) {
|
|
131
|
+
if (!SKIPPED_KEYS.has(key)) stack.push([child, depth + 1]);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Folders used as a working directory by anything in this value (`except`: a run in its own folder). */
|
|
137
|
+
function addWorkdirs(value, { except = null, realpath = null } = {}) {
|
|
138
|
+
const stack = [[value, 0]];
|
|
139
|
+
while (stack.length) {
|
|
140
|
+
const [item, depth] = stack.pop();
|
|
141
|
+
if (!item || typeof item !== 'object' || depth > MAX_DEPTH) continue;
|
|
142
|
+
if (Array.isArray(item)) { for (const child of item) stack.push([child, depth + 1]); continue; }
|
|
143
|
+
for (const [key, child] of Object.entries(item)) {
|
|
144
|
+
if (typeof child !== 'string') { stack.push([child, depth + 1]); continue; }
|
|
145
|
+
if (!WORKDIR_KEYS.has(key)) continue;
|
|
146
|
+
for (const path of [child, realpath && isAbsolute(child) ? realpath(child) : null]) {
|
|
147
|
+
const run = path ? scratchRunOf(path) : null;
|
|
148
|
+
if (run && run !== except) workdirs.add(run);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { byRun, overflow, workdirs, add, addText, addPath, addVisible, addWorkdirs };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function collectResult(index, result, where) {
|
|
158
|
+
if (typeof result === 'string') { index.addText(result, { cwd: where.scratchCwd }); return; }
|
|
159
|
+
if (!isObject(result)) return;
|
|
160
|
+
const paths = { cwd: where.cwd, realpath: where.realpath };
|
|
161
|
+
for (const [key, value] of Object.entries(result)) {
|
|
162
|
+
if (SKIPPED_KEYS.has(key)) continue;
|
|
163
|
+
if ((key === 'files' || key === 'media' || key === 'changes') && Array.isArray(value)) {
|
|
164
|
+
for (const item of value) {
|
|
165
|
+
if (typeof item === 'string') index.addPath(item, paths);
|
|
166
|
+
else if (isObject(item)) {
|
|
167
|
+
index.addPath(item.path, paths);
|
|
168
|
+
index.addVisible({ ...item, path: undefined }, { cwd: where.scratchCwd });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} else index.addVisible(value, { cwd: where.scratchCwd });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A row of the dispatch registry, the native ledger or a loop state file. */
|
|
176
|
+
export function collectRunRecord(index, row, { realpath = null } = {}) {
|
|
177
|
+
if (!isObject(row)) return;
|
|
178
|
+
const run = typeof row.runId === 'string' ? row.runId.toLowerCase() : null;
|
|
179
|
+
const cwd = typeof row.cwd === 'string' && isAbsolute(row.cwd) ? row.cwd : null;
|
|
180
|
+
const scratchCwd = cwd && INSIDE_SCRATCH.test(cwd.replace(/\\/g, '/')) ? cwd : null;
|
|
181
|
+
const where = { cwd, scratchCwd, realpath };
|
|
182
|
+
index.addWorkdirs(row, { except: run, realpath });
|
|
183
|
+
for (const [key, value] of Object.entries(row)) {
|
|
184
|
+
if (SKIPPED_KEYS.has(key) || key === 'cwd' || key === 'project') continue;
|
|
185
|
+
if (INPUT_KEYS.has(key)) index.addVisible(value, { except: run });
|
|
186
|
+
else if (key === 'lastResult') collectResult(index, value, where);
|
|
187
|
+
else if (key === 'turns' && Array.isArray(value)) {
|
|
188
|
+
for (const turn of value) {
|
|
189
|
+
if (!isObject(turn)) continue;
|
|
190
|
+
index.addText(turn.promptPreview, { except: run });
|
|
191
|
+
index.addText(turn.text, { cwd: scratchCwd });
|
|
192
|
+
collectResult(index, turn.result, where);
|
|
193
|
+
}
|
|
194
|
+
} else if (key === 'media' && Array.isArray(value)) {
|
|
195
|
+
for (const item of value) if (isObject(item)) index.addPath(item.path, { cwd, realpath });
|
|
196
|
+
} else index.addVisible(value, { cwd: scratchCwd });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** One line of an Assistant transcript: what its page draws as the conversation. */
|
|
201
|
+
export function collectTranscriptEntry(index, entry) {
|
|
202
|
+
index.addVisible(isObject(entry) && entry.packet !== undefined ? entry.packet : entry);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function longestEntry(entries, rest, fold) {
|
|
206
|
+
let best = null;
|
|
207
|
+
for (const entry of entries) {
|
|
208
|
+
const name = fold(entry.name);
|
|
209
|
+
if (!name || !rest.startsWith(name) || (best && name.length <= best.length)) continue;
|
|
210
|
+
const after = rest.slice(name.length);
|
|
211
|
+
if (after.startsWith('/') || BOUNDARY.test(after)) best = { entry, length: name.length };
|
|
212
|
+
}
|
|
213
|
+
return best;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The real entry a reference names.
|
|
218
|
+
* @param {string} tail the text after `scratch/<run>/`
|
|
219
|
+
* @param {(rel: string) => Array<{ name: string, directory: boolean }>|null} list a folder of the run, by relative path
|
|
220
|
+
* @returns {{ rel: string, directory: boolean, dangling?: boolean } | { ambiguous: true } | null} null: nothing in the
|
|
221
|
+
* folder is named. A path that goes missing below a real folder keeps that folder.
|
|
222
|
+
*/
|
|
223
|
+
export function resolveReference(tail, list, fold = foldFor()) {
|
|
224
|
+
let rest = fold(String(tail)).replace(/^\/+/, '');
|
|
225
|
+
let rel = '';
|
|
226
|
+
for (let depth = 0; depth <= MAX_DEPTH; depth += 1) {
|
|
227
|
+
while (rest.startsWith('./')) rest = rest.slice(2).replace(/^\/+/, '');
|
|
228
|
+
if (!rest) return rel ? { rel, directory: true } : null;
|
|
229
|
+
if (rest === '..' || rest.startsWith('../')) return { ambiguous: true };
|
|
230
|
+
const found = longestEntry(list(rel) || [], rest, fold);
|
|
231
|
+
if (found) {
|
|
232
|
+
const child = rel ? `${rel}/${found.entry.name}` : found.entry.name;
|
|
233
|
+
const after = rest.slice(found.length);
|
|
234
|
+
if (!found.entry.directory || !after.startsWith('/')) return { rel: child, directory: !!found.entry.directory };
|
|
235
|
+
rel = child;
|
|
236
|
+
rest = after.replace(/^\/+/, '');
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (EMPHASIS.test(rest)) return rel ? { rel, directory: true } : null;
|
|
240
|
+
if (GLOB.test(rest)) return { ambiguous: true };
|
|
241
|
+
if (BOUNDARY.test(rest)) return rel ? { rel, directory: true } : null;
|
|
242
|
+
return rel ? { rel, directory: true, dangling: true } : null;
|
|
243
|
+
}
|
|
244
|
+
return { ambiguous: true };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The relative paths to keep. `ambiguous`: a reference (a glob, a `..`) that cannot be tied to entries. */
|
|
248
|
+
export function resolveKeepSet(tails, list, fold = foldFor()) {
|
|
249
|
+
const keep = new Set();
|
|
250
|
+
const listed = new Map();
|
|
251
|
+
const cached = (rel) => {
|
|
252
|
+
if (!listed.has(rel)) listed.set(rel, list(rel));
|
|
253
|
+
return listed.get(rel);
|
|
254
|
+
};
|
|
255
|
+
for (const tail of tails) {
|
|
256
|
+
const hit = resolveReference(tail, cached, fold);
|
|
257
|
+
if (!hit) continue;
|
|
258
|
+
if (hit.ambiguous) return { keep: new Set(), ambiguous: true };
|
|
259
|
+
keep.add(hit.rel);
|
|
260
|
+
}
|
|
261
|
+
return { keep, ambiguous: false };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Every folder above a kept entry: it stays so the entry keeps its path. */
|
|
265
|
+
export function ancestorsOf(keep) {
|
|
266
|
+
const out = new Set();
|
|
267
|
+
for (const rel of keep) {
|
|
268
|
+
const parts = rel.split('/');
|
|
269
|
+
for (let n = 1; n < parts.length; n += 1) out.add(parts.slice(0, n).join('/'));
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Is this relative path a kept entry or inside one? */
|
|
275
|
+
export function isCovered(keep, rel) {
|
|
276
|
+
const parts = rel.split('/');
|
|
277
|
+
for (let n = 1; n <= parts.length; n += 1) if (keep.has(parts.slice(0, n).join('/'))) return true;
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// One scratch retention pass. Runs inside a worker thread (scratch-retention-worker.js): the walk, the measuring and
|
|
2
|
+
// every delete happen off the server's main thread, in small batches with a pause between them.
|
|
3
|
+
//
|
|
4
|
+
// A folder is touched only when its run is positively finished and past the retention period. What the run's visible
|
|
5
|
+
// output still points at stays (scratch-references.js); everything else in the folder goes. Before any delete of a
|
|
6
|
+
// folder: no process inside it, nothing changed, the same references, the run still terminal on disk and in the
|
|
7
|
+
// server's memory, and the path still the same real directory directly under data/scratch.
|
|
8
|
+
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmdirSync, unlinkSync } from 'node:fs';
|
|
11
|
+
import { dirname, join, posix } from 'node:path';
|
|
12
|
+
import { DAY_MS, Evidence, Keep, reasonOf } from './scratch-evidence.js';
|
|
13
|
+
import { ancestorsOf, foldFor, isCovered, resolveKeepSet } from './scratch-references.js';
|
|
14
|
+
import { createProcessProbe, recoverProbes } from './scratch-process-guard.js';
|
|
15
|
+
|
|
16
|
+
const GRACE_MS = DAY_MS;
|
|
17
|
+
const BATCH = 128;
|
|
18
|
+
const PAUSE_MS = 5;
|
|
19
|
+
const MAX_DEPTH = 128;
|
|
20
|
+
const LINK_ROUNDS = 8;
|
|
21
|
+
const BIG = { bigint: true };
|
|
22
|
+
const DIRECTORY_FLAGS = constants.O_RDONLY | (constants.O_DIRECTORY || 0) | (constants.O_NOFOLLOW || 0);
|
|
23
|
+
const SQLITE_BUSY = 5;
|
|
24
|
+
|
|
25
|
+
const defaultPause = () => new Promise((done) => setTimeout(done, PAUSE_MS));
|
|
26
|
+
const sameEntry = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
27
|
+
const stampOf = (st) => `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
|
|
28
|
+
const changedMs = (st) => Math.max(Number(st.mtimeNs / 1_000_000n), Number(st.ctimeNs / 1_000_000n));
|
|
29
|
+
// The Windows process check renames the run folder aside and back, which moves that folder's own change time.
|
|
30
|
+
const rootStamp = (st, platform) => (platform === 'win32' ? `${st.dev}:${st.ino}:${st.mtimeNs}` : stampOf(st));
|
|
31
|
+
const rootChangedMs = (st, platform) => (platform === 'win32' ? Number(st.mtimeNs / 1_000_000n) : changedMs(st));
|
|
32
|
+
|
|
33
|
+
function pacer(pause) {
|
|
34
|
+
let count = 0;
|
|
35
|
+
return async () => {
|
|
36
|
+
count += 1;
|
|
37
|
+
if (count % BATCH === 0) await pause();
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function bytesOf(st, platform) {
|
|
42
|
+
return platform === 'win32' ? Number(st.size) : Number(st.blocks) * 512;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Mount points below the scratch root (a Linux bind mount can share its parent's device number). */
|
|
46
|
+
function mountsBelow(root, platform) {
|
|
47
|
+
if (platform !== 'linux') return [];
|
|
48
|
+
try {
|
|
49
|
+
return readFileSync('/proc/self/mountinfo', 'utf8').split('\n')
|
|
50
|
+
.map((line) => line.split(' ')[4])
|
|
51
|
+
.filter(Boolean)
|
|
52
|
+
.map((point) => point.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8))))
|
|
53
|
+
.filter((point) => point.startsWith(`${root}/`));
|
|
54
|
+
} catch { throw new Keep('unknown-mount'); }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function assertDirectory(path, info) {
|
|
58
|
+
const now = lstatSync(path, BIG);
|
|
59
|
+
if (!now.isDirectory() || !sameEntry(now, info) || realpathSync.native(path) !== path) throw new Keep('replaced');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Measure a folder and classify every entry as kept or removable. Reads names and metadata only. */
|
|
63
|
+
async function scanTree(ctx, root, info, keep) {
|
|
64
|
+
const ancestors = ancestorsOf(keep);
|
|
65
|
+
const digest = createHash('sha256');
|
|
66
|
+
const tree = { bytes: 0, keptBytes: 0, removable: 0, keptEntries: 0, newest: rootChangedMs(info, ctx.platform), shared: new Map(), links: new Map(), linkTargets: [] };
|
|
67
|
+
const named = new Map();
|
|
68
|
+
const own = bytesOf(info, ctx.platform);
|
|
69
|
+
tree.bytes += own;
|
|
70
|
+
if (keep.size) tree.keptBytes += own;
|
|
71
|
+
digest.update(`.\0${rootStamp(info, ctx.platform)}\n`);
|
|
72
|
+
|
|
73
|
+
const visit = async (dir, rel, dirInfo, insideKept, depth) => {
|
|
74
|
+
if (depth > MAX_DEPTH) throw new Keep('too-deep');
|
|
75
|
+
for (const name of readdirSync(dir)) {
|
|
76
|
+
await ctx.pace();
|
|
77
|
+
const abs = join(dir, name);
|
|
78
|
+
const child = rel ? `${rel}/${name}` : name;
|
|
79
|
+
const st = lstatSync(abs, BIG);
|
|
80
|
+
if (st.dev !== ctx.device) throw new Keep('mount');
|
|
81
|
+
digest.update(`${child}\0${stampOf(st)}${st.isDirectory() ? '' : `:${st.nlink}`}\n`);
|
|
82
|
+
tree.newest = Math.max(tree.newest, changedMs(st));
|
|
83
|
+
const kept = insideKept || keep.has(child);
|
|
84
|
+
const stays = kept || ancestors.has(child);
|
|
85
|
+
const size = bytesOf(st, ctx.platform);
|
|
86
|
+
if (!st.isDirectory() && st.nlink > 1n) {
|
|
87
|
+
const key = `${st.dev}:${st.ino}`;
|
|
88
|
+
const seen = named.get(key) || { size, nlink: st.nlink, names: 0n, stays: false, steady: true, known: ctx.platform !== 'win32' && st.ino !== 0n };
|
|
89
|
+
seen.names += 1n;
|
|
90
|
+
seen.stays ||= stays;
|
|
91
|
+
seen.steady &&= seen.nlink === st.nlink;
|
|
92
|
+
named.set(key, seen);
|
|
93
|
+
} else {
|
|
94
|
+
tree.bytes += size;
|
|
95
|
+
if (stays) tree.keptBytes += size;
|
|
96
|
+
}
|
|
97
|
+
if (kept) tree.keptEntries += 1;
|
|
98
|
+
else if (!stays) tree.removable += 1;
|
|
99
|
+
if (st.isDirectory()) {
|
|
100
|
+
if (ctx.mounts.includes(abs)) throw new Keep('mount');
|
|
101
|
+
await visit(abs, child, st, kept, depth + 1);
|
|
102
|
+
} else if (st.isSymbolicLink()) {
|
|
103
|
+
if (kept) {
|
|
104
|
+
// A kept link must keep working: what it points at inside this folder stays too.
|
|
105
|
+
const target = readlinkSync(abs).replace(/\\/g, '/');
|
|
106
|
+
if (!target.startsWith('/') && !/^[a-z]:/i.test(target)) {
|
|
107
|
+
const resolved = posix.normalize(posix.join(posix.dirname(child), target));
|
|
108
|
+
if (resolved !== '.' && resolved !== '..' && !resolved.startsWith('../')) tree.linkTargets.push(resolved);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
} else if (!st.isFile()) throw new Keep('special-file');
|
|
112
|
+
}
|
|
113
|
+
const after = lstatSync(dir, BIG);
|
|
114
|
+
const same = dir === root ? rootStamp(after, ctx.platform) === rootStamp(dirInfo, ctx.platform) : stampOf(after) === stampOf(dirInfo);
|
|
115
|
+
if (!same) throw new Keep('changing-folder');
|
|
116
|
+
};
|
|
117
|
+
await visit(root, '', info, false, 0);
|
|
118
|
+
// A hard-linked file belongs to this folder only when the names counted here are all the names it has. Where the
|
|
119
|
+
// identity of a file cannot be trusted (Windows, an inode of 0) that is never proven, so the folder stays.
|
|
120
|
+
for (const [key, seen] of named) {
|
|
121
|
+
if (!seen.known || !seen.steady || seen.names !== seen.nlink) { tree.shared.set(key, seen.size); continue; }
|
|
122
|
+
tree.links.set(key, { total: seen.nlink, left: seen.nlink });
|
|
123
|
+
tree.bytes += seen.size;
|
|
124
|
+
if (seen.stays) tree.keptBytes += seen.size;
|
|
125
|
+
}
|
|
126
|
+
tree.digest = digest.digest('hex');
|
|
127
|
+
return tree;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** What stays and what goes in one folder, under the references that point into it now. */
|
|
131
|
+
async function planFolder(ctx, root, info, references) {
|
|
132
|
+
if (references.overflow) throw new Keep('too-many-references');
|
|
133
|
+
const list = (rel) => {
|
|
134
|
+
try {
|
|
135
|
+
return readdirSync(rel ? join(root, ...rel.split('/')) : root, { withFileTypes: true })
|
|
136
|
+
.map((entry) => ({ name: entry.name, directory: entry.isDirectory() }));
|
|
137
|
+
} catch { return null; }
|
|
138
|
+
};
|
|
139
|
+
const { keep, ambiguous } = resolveKeepSet(references.tails, list, ctx.fold);
|
|
140
|
+
if (ambiguous) throw new Keep('ambiguous-reference');
|
|
141
|
+
for (let round = 0; round < LINK_ROUNDS; round += 1) {
|
|
142
|
+
const tree = await scanTree(ctx, root, info, keep);
|
|
143
|
+
const missing = tree.linkTargets.filter((rel) => !isCovered(keep, rel));
|
|
144
|
+
if (!missing.length) return { keep, tree };
|
|
145
|
+
for (const rel of missing) keep.add(rel);
|
|
146
|
+
}
|
|
147
|
+
throw new Keep('ambiguous-reference');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Remove everything under `dir` that is not kept. Paths are checked again right before each removal. */
|
|
151
|
+
async function removeContents(ctx, dir, rel, dirInfo, keep, ancestors, links, credit) {
|
|
152
|
+
assertDirectory(dir, dirInfo);
|
|
153
|
+
for (const name of readdirSync(dir)) {
|
|
154
|
+
await ctx.pace();
|
|
155
|
+
const abs = join(dir, name);
|
|
156
|
+
const child = rel ? `${rel}/${name}` : name;
|
|
157
|
+
const st = lstatSync(abs, BIG);
|
|
158
|
+
if (st.dev !== ctx.device) throw new Keep('mount');
|
|
159
|
+
const link = st.isDirectory() ? undefined : links.get(`${st.dev}:${st.ino}`);
|
|
160
|
+
if (link && st.nlink !== link.left) throw new Keep('hard-linked');
|
|
161
|
+
// Removing a name moves the change time of the names left, so once this pass has done that only the content time
|
|
162
|
+
// can speak for the file; the link count above says whether anyone else touched its names.
|
|
163
|
+
const changed = link && link.left < link.total ? Number(st.mtimeNs / 1_000_000n) : changedMs(st);
|
|
164
|
+
if (changed >= ctx.cutoff) throw new Keep('recent-change');
|
|
165
|
+
if (keep.has(child)) continue;
|
|
166
|
+
if (st.isDirectory()) {
|
|
167
|
+
await removeContents(ctx, abs, child, st, keep, ancestors, links, credit);
|
|
168
|
+
if (!ancestors.has(child)) {
|
|
169
|
+
assertDirectory(dir, dirInfo);
|
|
170
|
+
assertDirectory(abs, st);
|
|
171
|
+
rmdirSync(abs);
|
|
172
|
+
credit(bytesOf(st, ctx.platform));
|
|
173
|
+
}
|
|
174
|
+
} else if (st.isFile() || st.isSymbolicLink()) {
|
|
175
|
+
if (!link && st.nlink !== 1n) throw new Keep('hard-linked');
|
|
176
|
+
assertDirectory(dir, dirInfo);
|
|
177
|
+
unlinkSync(abs);
|
|
178
|
+
if (link) link.left -= 1n;
|
|
179
|
+
// The bytes of a linked file are freed by its last name only; a kept name means they never are.
|
|
180
|
+
credit(!link || link.left === 0n ? bytesOf(st, ctx.platform) : 0);
|
|
181
|
+
} else throw new Keep('special-file');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** An OS-held lock: released however the holder ends, so a crash leaves nothing to clean up. */
|
|
186
|
+
async function withPassLock(path, fn) {
|
|
187
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
188
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
189
|
+
const db = new DatabaseSync(path);
|
|
190
|
+
try {
|
|
191
|
+
db.exec('PRAGMA busy_timeout=0');
|
|
192
|
+
try { db.exec('BEGIN IMMEDIATE'); }
|
|
193
|
+
catch (error) {
|
|
194
|
+
if ((Number(error?.errcode) & 0xff) === SQLITE_BUSY || /database is locked/i.test(String(error?.message))) return { busy: true };
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
try { await fn(); return { busy: false }; }
|
|
198
|
+
finally { try { db.exec('ROLLBACK'); } catch { /* closing gives it back */ } }
|
|
199
|
+
} finally {
|
|
200
|
+
try { db.close(); } catch { /* already closed */ }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* @param {object} o
|
|
206
|
+
* @param {string} o.dataHome
|
|
207
|
+
* @param {boolean} [o.dryRun] only say what would be removed
|
|
208
|
+
* @param {(row: { check: string, task: boolean, finished: number }) => boolean|Promise<boolean>} [o.confirm] the live
|
|
209
|
+
* owners' last word, right before a delete
|
|
210
|
+
* @param {(row: object) => void} [o.emit] one row per folder on a dry run
|
|
211
|
+
*/
|
|
212
|
+
export async function runPass({
|
|
213
|
+
dataHome, dryRun = true, confirm = async () => false, now = Date.now, probe = null, emit = () => {},
|
|
214
|
+
platform = process.platform, pause = defaultPause,
|
|
215
|
+
}) {
|
|
216
|
+
const summary = {
|
|
217
|
+
dryRun, removed: 0, pruned: 0, freedBytes: 0, wouldRemove: 0, wouldPrune: 0, wouldFreeBytes: 0,
|
|
218
|
+
totalBytes: 0, kept: {}, keptBytes: {},
|
|
219
|
+
};
|
|
220
|
+
const held = (reason, runId, bytes = 0) => {
|
|
221
|
+
summary.kept[reason] = (summary.kept[reason] || 0) + 1;
|
|
222
|
+
summary.keptBytes[reason] = (summary.keptBytes[reason] || 0) + bytes;
|
|
223
|
+
if (dryRun) emit({ runId, action: 'keep', reason, bytes });
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
let home;
|
|
227
|
+
try { home = realpathSync.native(dataHome); }
|
|
228
|
+
catch { summary.passReason = 'missing-directory-or-state'; return summary; }
|
|
229
|
+
const data = join(home, 'data');
|
|
230
|
+
const root = join(data, 'scratch');
|
|
231
|
+
let rootInfo;
|
|
232
|
+
try {
|
|
233
|
+
if (!lstatSync(data).isDirectory()) throw new Keep('linked-root');
|
|
234
|
+
rootInfo = lstatSync(root, BIG);
|
|
235
|
+
if (!rootInfo.isDirectory()) throw new Keep('linked-root');
|
|
236
|
+
if (realpathSync.native(root) !== root) throw new Keep('linked-root');
|
|
237
|
+
} catch (error) {
|
|
238
|
+
summary.passReason = error?.code === 'ENOENT' ? 'missing-directory-or-state' : reasonOf(error);
|
|
239
|
+
return summary;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const pass = async () => {
|
|
243
|
+
recoverProbes(root, { platform });
|
|
244
|
+
const evidence = new Evidence(data, { pause });
|
|
245
|
+
let settings;
|
|
246
|
+
try { settings = evidence.settings(); }
|
|
247
|
+
catch (error) {
|
|
248
|
+
for (const name of readdirSync(root)) held(reasonOf(error), name);
|
|
249
|
+
throw error;
|
|
250
|
+
}
|
|
251
|
+
const ctx = { device: rootInfo.dev, platform, fold: foldFor(platform), pace: pacer(pause), mounts: mountsBelow(root, platform), cutoff: 0 };
|
|
252
|
+
const check = probe || createProcessProbe({ platform, pause });
|
|
253
|
+
let holds = new Map();
|
|
254
|
+
let holdError = null;
|
|
255
|
+
try { holds = await evidence.collect(); }
|
|
256
|
+
catch (error) { holdError = reasonOf(error); }
|
|
257
|
+
|
|
258
|
+
const shared = new Map();
|
|
259
|
+
const candidates = [];
|
|
260
|
+
let total = 0;
|
|
261
|
+
const measured = (tree) => {
|
|
262
|
+
total += tree.bytes;
|
|
263
|
+
for (const [key, size] of tree.shared) shared.set(key, size);
|
|
264
|
+
return tree.bytes;
|
|
265
|
+
};
|
|
266
|
+
for (const name of readdirSync(root)) {
|
|
267
|
+
const path = join(root, name);
|
|
268
|
+
let bytes = 0;
|
|
269
|
+
try {
|
|
270
|
+
const st = lstatSync(path, BIG);
|
|
271
|
+
if (!st.isDirectory()) {
|
|
272
|
+
bytes = bytesOf(st, platform);
|
|
273
|
+
if (st.nlink > 1n) shared.set(`${st.dev}:${st.ino}`, bytes);
|
|
274
|
+
else total += bytes;
|
|
275
|
+
throw new Keep('not-directory');
|
|
276
|
+
}
|
|
277
|
+
let verdict = null;
|
|
278
|
+
let failure = holdError ? new Keep(holdError) : null;
|
|
279
|
+
if (!failure) {
|
|
280
|
+
try { verdict = evidence.evaluate(name, holds); } catch (error) { failure = error; }
|
|
281
|
+
}
|
|
282
|
+
// Measured whatever the verdict: a kept folder still counts against the disk budget.
|
|
283
|
+
const references = verdict ? evidence.referencesTo(name) : { tails: new Set(), overflow: false };
|
|
284
|
+
let plan;
|
|
285
|
+
try { plan = await planFolder(ctx, path, st, references); }
|
|
286
|
+
catch (error) {
|
|
287
|
+
if (failure || !(error instanceof Keep) || !['too-many-references', 'ambiguous-reference'].includes(error.reason)) throw failure || error;
|
|
288
|
+
bytes = measured((await planFolder(ctx, path, st, { tails: new Set(), overflow: false })).tree);
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
bytes = measured(plan.tree);
|
|
292
|
+
if (failure) throw failure;
|
|
293
|
+
if (now() - verdict.end <= settings.floorMs) throw new Keep('minimum-age');
|
|
294
|
+
if (plan.keep.size && !plan.tree.removable) throw new Keep('referenced');
|
|
295
|
+
if (now() - plan.tree.newest <= GRACE_MS) throw new Keep('recent-change');
|
|
296
|
+
if (plan.tree.shared.size) throw new Keep('hard-linked');
|
|
297
|
+
candidates.push({ run: name, end: verdict.end, task: verdict.task, st, digest: plan.tree.digest, keep: plan.keep, bytes });
|
|
298
|
+
} catch (error) {
|
|
299
|
+
held(reasonOf(error), name, bytes);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
total += [...shared.values()].reduce((sum, size) => sum + size, 0);
|
|
303
|
+
summary.totalBytes = total;
|
|
304
|
+
|
|
305
|
+
candidates.sort((a, b) => a.end - b.end || a.run.localeCompare(b.run));
|
|
306
|
+
for (const candidate of candidates) {
|
|
307
|
+
const { run, st } = candidate;
|
|
308
|
+
const path = join(root, run);
|
|
309
|
+
let fd = null;
|
|
310
|
+
let freed = 0;
|
|
311
|
+
let touched = false;
|
|
312
|
+
try {
|
|
313
|
+
const expired = now() - candidate.end > settings.ageMs;
|
|
314
|
+
if (!expired && total - summary.freedBytes - summary.wouldFreeBytes <= settings.limitBytes) throw new Keep('within-budget');
|
|
315
|
+
if (platform !== 'win32') {
|
|
316
|
+
fd = openSync(path, DIRECTORY_FLAGS);
|
|
317
|
+
if (!sameEntry(fstatSync(fd, BIG), st)) throw new Keep('replaced');
|
|
318
|
+
}
|
|
319
|
+
assertDirectory(path, st);
|
|
320
|
+
await check(path, fd);
|
|
321
|
+
assertDirectory(path, st);
|
|
322
|
+
ctx.mounts = mountsBelow(root, platform);
|
|
323
|
+
if (ctx.mounts.some((point) => point === path || point.startsWith(`${path}/`))) throw new Keep('mount');
|
|
324
|
+
|
|
325
|
+
// Everything again, after the slowest step: state, settings, references, then the tree.
|
|
326
|
+
const fresh = await evidence.collect();
|
|
327
|
+
const final = evidence.evaluate(run, fresh);
|
|
328
|
+
const settingsNow = evidence.settings();
|
|
329
|
+
if (final.end !== candidate.end || final.task !== candidate.task
|
|
330
|
+
|| settingsNow.ageMs !== settings.ageMs || settingsNow.limitBytes !== settings.limitBytes || settingsNow.floorMs !== settings.floorMs) {
|
|
331
|
+
throw new Keep('changed-state');
|
|
332
|
+
}
|
|
333
|
+
const current = lstatSync(path, BIG);
|
|
334
|
+
if (rootStamp(current, platform) !== rootStamp(st, platform)) throw new Keep('changing-folder');
|
|
335
|
+
const plan = await planFolder(ctx, path, current, evidence.referencesTo(run));
|
|
336
|
+
if ([...plan.keep].sort().join('\0') !== [...candidate.keep].sort().join('\0')) throw new Keep('changed-references');
|
|
337
|
+
if (now() - plan.tree.newest <= GRACE_MS || plan.tree.digest !== candidate.digest) throw new Keep('changing-folder');
|
|
338
|
+
if (plan.tree.shared.size) throw new Keep('hard-linked');
|
|
339
|
+
const removable = plan.tree.bytes - plan.tree.keptBytes;
|
|
340
|
+
const whole = plan.keep.size === 0;
|
|
341
|
+
|
|
342
|
+
if (dryRun) {
|
|
343
|
+
if (whole) summary.wouldRemove += 1;
|
|
344
|
+
else summary.wouldPrune += 1;
|
|
345
|
+
summary.wouldFreeBytes += removable;
|
|
346
|
+
emit({
|
|
347
|
+
runId: run, action: whole ? 'remove' : 'prune', reason: expired ? 'age' : 'pressure', bytes: removable,
|
|
348
|
+
entries: plan.tree.removable + (whole ? 1 : 0), keptBytes: plan.tree.keptBytes, keptEntries: plan.tree.keptEntries,
|
|
349
|
+
keep: [...plan.keep].sort().slice(0, 20),
|
|
350
|
+
});
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (await confirm({ check: run, task: candidate.task, finished: candidate.end }) !== true) throw new Keep('live-owner');
|
|
355
|
+
assertDirectory(path, st);
|
|
356
|
+
if (fd !== null && !sameEntry(fstatSync(fd, BIG), st)) throw new Keep('replaced');
|
|
357
|
+
ctx.cutoff = now() - GRACE_MS;
|
|
358
|
+
const credit = (size) => { touched = true; freed += size; summary.freedBytes += size; };
|
|
359
|
+
await removeContents(ctx, path, '', st, plan.keep, ancestorsOf(plan.keep), plan.tree.links, credit);
|
|
360
|
+
if (whole) {
|
|
361
|
+
if (fd !== null) { closeSync(fd); fd = null; }
|
|
362
|
+
assertDirectory(path, st);
|
|
363
|
+
rmdirSync(path);
|
|
364
|
+
credit(bytesOf(st, platform));
|
|
365
|
+
summary.removed += 1;
|
|
366
|
+
} else summary.pruned += 1;
|
|
367
|
+
} catch (error) {
|
|
368
|
+
if (touched) {
|
|
369
|
+
summary.pruned += 1;
|
|
370
|
+
held(`stopped:${reasonOf(error)}`, run, Math.max(0, candidate.bytes - freed));
|
|
371
|
+
} else held(reasonOf(error), run, candidate.bytes);
|
|
372
|
+
} finally {
|
|
373
|
+
if (fd !== null) { try { closeSync(fd); } catch { /* already closed */ } }
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
try {
|
|
379
|
+
const lock = await withPassLock(join(home, 'runtime', 'scratch-retention.mutex'), pass);
|
|
380
|
+
if (lock.busy) summary.passReason = 'another-pass';
|
|
381
|
+
} catch (error) {
|
|
382
|
+
summary.passReason = error?.code === 'ENOENT' ? 'missing-directory-or-state' : reasonOf(error);
|
|
383
|
+
}
|
|
384
|
+
return summary;
|
|
385
|
+
}
|