nova-personal-agent-server 0.0.0-stage → 0.4.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/LICENSE +201 -0
- package/README.md +30 -2
- package/bin/novapersonal-server.mjs +4 -0
- package/package.json +61 -4
- package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
- package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
- package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
- package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
- package/resources/native/codex-sandbox-probe +0 -0
- package/resources/native/project-native/nova_project_native.node +0 -0
- package/resources/native-resources-v1.json +1 -0
- package/runtime/dist/eval/demos.js +156 -0
- package/runtime/dist/eval/fixture-host.js +385 -0
- package/runtime/dist/eval/fixtures.js +319 -0
- package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
- package/runtime/dist/eval/scorecard.js +285 -0
- package/runtime/dist/eval/sim.js +43 -0
- package/runtime/dist/src/cascaded-text-provider.js +31 -0
- package/runtime/dist/src/cli.js +96 -0
- package/runtime/dist/src/composition/assembly.js +352 -0
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
- package/runtime/dist/src/composition/production-composition.js +389 -0
- package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
- package/runtime/dist/src/config/capability-registry.js +315 -0
- package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
- package/runtime/dist/src/config/coding-backends.js +8 -0
- package/runtime/dist/src/config/coding-profiles.js +98 -0
- package/runtime/dist/src/config/config.js +857 -0
- package/runtime/dist/src/config/diagnostics.js +139 -0
- package/runtime/dist/src/config/environment-contract.js +202 -0
- package/runtime/dist/src/config/self-hosted.js +23 -0
- package/runtime/dist/src/connectors/composio/client.js +195 -0
- package/runtime/dist/src/connectors/composio/google.js +208 -0
- package/runtime/dist/src/connectors/composio/index.js +334 -0
- package/runtime/dist/src/connectors/feishu/cli.js +220 -0
- package/runtime/dist/src/connectors/feishu/index.js +980 -0
- package/runtime/dist/src/connectors/macos/calendar.js +35 -0
- package/runtime/dist/src/connectors/macos/mail.js +32 -0
- package/runtime/dist/src/connectors/macos/reader.js +62 -0
- package/runtime/dist/src/conversation-voice-provider.js +41 -0
- package/runtime/dist/src/core/approval-port.js +9 -0
- package/runtime/dist/src/core/approval.js +1328 -0
- package/runtime/dist/src/core/calls.js +35 -0
- package/runtime/dist/src/core/camera-session.js +32 -0
- package/runtime/dist/src/core/causal-runtime.js +650 -0
- package/runtime/dist/src/core/clock.js +139 -0
- package/runtime/dist/src/core/context-view.js +156 -0
- package/runtime/dist/src/core/effects.js +62 -0
- package/runtime/dist/src/core/events.js +217 -0
- package/runtime/dist/src/core/executor-diagnostic.js +9 -0
- package/runtime/dist/src/core/ids.js +32 -0
- package/runtime/dist/src/core/media-store.js +104 -0
- package/runtime/dist/src/core/memory.js +296 -0
- package/runtime/dist/src/core/pending-decision.js +64 -0
- package/runtime/dist/src/core/ports.js +125 -0
- package/runtime/dist/src/core/runtime.js +1459 -0
- package/runtime/dist/src/core/schedule-tools.js +15 -0
- package/runtime/dist/src/core/sims.js +186 -0
- package/runtime/dist/src/core/slots.js +97 -0
- package/runtime/dist/src/core/source-processing-instructions.js +3 -0
- package/runtime/dist/src/core/source-processing-tools.js +12 -0
- package/runtime/dist/src/core/suggestions.js +143 -0
- package/runtime/dist/src/core/task-tools.js +22 -0
- package/runtime/dist/src/core/tool-schema.js +212 -0
- package/runtime/dist/src/core/trace.js +34 -0
- package/runtime/dist/src/core/work-tools.js +94 -0
- package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
- package/runtime/dist/src/desktop/desktop-camera.js +281 -0
- package/runtime/dist/src/desktop/desktop-control.js +140 -0
- package/runtime/dist/src/desktop/desktop-progress.js +162 -0
- package/runtime/dist/src/desktop/desktop-session.js +2106 -0
- package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
- package/runtime/dist/src/desktop/desktop-wire.js +605 -0
- package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
- package/runtime/dist/src/desktop/startup-error.js +18 -0
- package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
- package/runtime/dist/src/desktop-entry.js +106 -0
- package/runtime/dist/src/desktop.js +1092 -0
- package/runtime/dist/src/executors/acp/backends.js +105 -0
- package/runtime/dist/src/executors/acp/mcp.js +81 -0
- package/runtime/dist/src/executors/acp/preflight.js +14 -0
- package/runtime/dist/src/executors/acp/process-owner.js +112 -0
- package/runtime/dist/src/executors/acp/transport.js +760 -0
- package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
- package/runtime/dist/src/executors/agent-controller.js +244 -0
- package/runtime/dist/src/executors/autoglm.js +376 -0
- package/runtime/dist/src/executors/browser-device.js +102 -0
- package/runtime/dist/src/executors/browser.js +61 -0
- package/runtime/dist/src/executors/camera.js +101 -0
- package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
- package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
- package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
- package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
- package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
- package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
- package/runtime/dist/src/executors/codex/common.js +655 -0
- package/runtime/dist/src/executors/codex/contract.js +581 -0
- package/runtime/dist/src/executors/codex/controller.js +141 -0
- package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
- package/runtime/dist/src/executors/codex/factory.js +463 -0
- package/runtime/dist/src/executors/codex/host-config.js +238 -0
- package/runtime/dist/src/executors/codex/host.js +17 -0
- package/runtime/dist/src/executors/codex/index.js +19 -0
- package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
- package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
- package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
- package/runtime/dist/src/executors/codex/process-owner.js +398 -0
- package/runtime/dist/src/executors/codex/production-host.js +887 -0
- package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
- package/runtime/dist/src/executors/codex/protocol.js +581 -0
- package/runtime/dist/src/executors/codex/safe-json.js +87 -0
- package/runtime/dist/src/executors/codex/session-title.js +61 -0
- package/runtime/dist/src/executors/codex/shared-home.js +29 -0
- package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
- package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
- package/runtime/dist/src/executors/codex/version.js +38 -0
- package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
- package/runtime/dist/src/executors/coding/intake-model.js +103 -0
- package/runtime/dist/src/executors/coding/intake.js +824 -0
- package/runtime/dist/src/executors/coding/json-completion.js +14 -0
- package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
- package/runtime/dist/src/executors/coding/work-order.js +50 -0
- package/runtime/dist/src/executors/coding-executor.js +23 -0
- package/runtime/dist/src/executors/computer-backend.js +188 -0
- package/runtime/dist/src/executors/computer-device.js +187 -0
- package/runtime/dist/src/executors/computer-worker.js +125 -0
- package/runtime/dist/src/executors/computer.js +100 -0
- package/runtime/dist/src/executors/device-lock.js +127 -0
- package/runtime/dist/src/executors/frame-source.js +29 -0
- package/runtime/dist/src/executors/gui-evidence.js +30 -0
- package/runtime/dist/src/executors/gui-execution.js +237 -0
- package/runtime/dist/src/executors/gui-runner.js +88 -0
- package/runtime/dist/src/executors/host-executor-capability.js +12 -0
- package/runtime/dist/src/executors/index.js +13 -0
- package/runtime/dist/src/executors/mcp-client.js +198 -0
- package/runtime/dist/src/executors/mcp.js +210 -0
- package/runtime/dist/src/executors/mobile-android.js +180 -0
- package/runtime/dist/src/executors/mobile-ios.js +303 -0
- package/runtime/dist/src/executors/mobile.js +78 -0
- package/runtime/dist/src/executors/search-mcp.js +146 -0
- package/runtime/dist/src/executors/search.js +524 -0
- package/runtime/dist/src/executors/task-resources.js +38 -0
- package/runtime/dist/src/executors/vision/assess.js +296 -0
- package/runtime/dist/src/executors/vision/controller-core.js +373 -0
- package/runtime/dist/src/executors/vision/controller.js +164 -0
- package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
- package/runtime/dist/src/executors/vision.js +5 -0
- package/runtime/dist/src/executors/watcher.js +718 -0
- package/runtime/dist/src/http/bounded-response.js +37 -0
- package/runtime/dist/src/index.js +56 -0
- package/runtime/dist/src/knowledge/assembly.js +60 -0
- package/runtime/dist/src/knowledge/documents.js +520 -0
- package/runtime/dist/src/knowledge/embeddings.js +201 -0
- package/runtime/dist/src/knowledge/mcp.js +218 -0
- package/runtime/dist/src/knowledge/parse-worker.js +122 -0
- package/runtime/dist/src/knowledge/references.js +51 -0
- package/runtime/dist/src/knowledge/service.js +526 -0
- package/runtime/dist/src/knowledge/store-client.js +185 -0
- package/runtime/dist/src/knowledge/store-worker.js +843 -0
- package/runtime/dist/src/knowledge/types.js +2 -0
- package/runtime/dist/src/mcp/http-server.js +177 -0
- package/runtime/dist/src/mem0/resource.js +35 -0
- package/runtime/dist/src/mem0/store-worker.js +330 -0
- package/runtime/dist/src/memory/blackboard-session.js +205 -0
- package/runtime/dist/src/memory/blackboard-store.js +194 -0
- package/runtime/dist/src/memory/blackboard-worker.js +369 -0
- package/runtime/dist/src/memory/entry.js +39 -0
- package/runtime/dist/src/memory/factory.js +20 -0
- package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
- package/runtime/dist/src/memory/personal-memory.js +10 -0
- package/runtime/dist/src/memory/prerecall.js +20 -0
- package/runtime/dist/src/memory/provenance.js +17 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
- package/runtime/dist/src/memory/retrieval.js +235 -0
- package/runtime/dist/src/memory/sensitivity.js +261 -0
- package/runtime/dist/src/memory-ledger/models.js +98 -0
- package/runtime/dist/src/memory-ledger/store-client.js +210 -0
- package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
- package/runtime/dist/src/memory-ledger/store.js +597 -0
- package/runtime/dist/src/memory-substrate/candidates.js +16 -0
- package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
- package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
- package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
- package/runtime/dist/src/memory-substrate/migration.js +87 -0
- package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
- package/runtime/dist/src/memory-substrate/purge.js +398 -0
- package/runtime/dist/src/memory-substrate/resolution.js +32 -0
- package/runtime/dist/src/memory-substrate/resource.js +867 -0
- package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
- package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
- package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
- package/runtime/dist/src/memory-substrate/source-state.js +93 -0
- package/runtime/dist/src/memory-substrate/store.js +534 -0
- package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
- package/runtime/dist/src/memory-substrate/workspace.js +21 -0
- package/runtime/dist/src/model/jev-client.js +25 -0
- package/runtime/dist/src/model/model-adapters.js +64 -0
- package/runtime/dist/src/model/model-gateway.js +399 -0
- package/runtime/dist/src/model/model-lane.js +34 -0
- package/runtime/dist/src/model/model-purpose.js +5 -0
- package/runtime/dist/src/model/personal-writer.js +361 -0
- package/runtime/dist/src/model/proactivity.js +72 -0
- package/runtime/dist/src/model/prompting.js +279 -0
- package/runtime/dist/src/model/task-verifier.js +217 -0
- package/runtime/dist/src/model/vision-capability.js +10 -0
- package/runtime/dist/src/news/feeds.js +114 -0
- package/runtime/dist/src/news/jev-ranking.js +25 -0
- package/runtime/dist/src/news/ranking.js +26 -0
- package/runtime/dist/src/news/service.js +262 -0
- package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
- package/runtime/dist/src/notifications/adapters/nova.js +15 -0
- package/runtime/dist/src/notifications/content.js +15 -0
- package/runtime/dist/src/notifications/contracts.js +9 -0
- package/runtime/dist/src/notifications/feed.js +8 -0
- package/runtime/dist/src/notifications/service.js +412 -0
- package/runtime/dist/src/notifications/store.js +4 -0
- package/runtime/dist/src/personal-agent/app-context.js +113 -0
- package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
- package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
- package/runtime/dist/src/personal-agent/contracts.js +32 -0
- package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
- package/runtime/dist/src/personal-agent/conversations.js +187 -0
- package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2403 -0
- package/runtime/dist/src/personal-agent/intake-task.js +37 -0
- package/runtime/dist/src/personal-agent/life.js +260 -0
- package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
- package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
- package/runtime/dist/src/personal-agent/project-digests.js +242 -0
- package/runtime/dist/src/personal-agent/sampling.js +20 -0
- package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
- package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
- package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
- package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
- package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
- package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
- package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
- package/runtime/dist/src/personal-agent/source-priority.js +142 -0
- package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
- package/runtime/dist/src/personal-agent/source-walk.js +25 -0
- package/runtime/dist/src/personal-agent/sources.js +1484 -0
- package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
- package/runtime/dist/src/personal-agent/store.js +146 -0
- package/runtime/dist/src/personal-agent/task-loop.js +163 -0
- package/runtime/dist/src/personal-agent/tasks.js +920 -0
- package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
- package/runtime/dist/src/personal-agent/understanding.js +160 -0
- package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
- package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
- package/runtime/dist/src/projects/host-paths.js +133 -0
- package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
- package/runtime/dist/src/projects/project-confirmation.js +486 -0
- package/runtime/dist/src/projects/project-native-resource.js +284 -0
- package/runtime/dist/src/projects/project-node-files.js +169 -0
- package/runtime/dist/src/projects/project-root-file.js +16 -0
- package/runtime/dist/src/projects/project-state.js +504 -0
- package/runtime/dist/src/projects/project-store-files.js +1271 -0
- package/runtime/dist/src/projects/project-store.js +1345 -0
- package/runtime/dist/src/realtime/aoq.js +141 -0
- package/runtime/dist/src/realtime/bridge.js +652 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
- package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
- package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
- package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
- package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
- package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
- package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
- package/runtime/dist/src/realtime/dictation.js +28 -0
- package/runtime/dist/src/realtime/evidence.js +276 -0
- package/runtime/dist/src/realtime/floor.js +43 -0
- package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
- package/runtime/dist/src/realtime/gemini.js +517 -0
- package/runtime/dist/src/realtime/history.js +122 -0
- package/runtime/dist/src/realtime/host-delivery.js +1711 -0
- package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
- package/runtime/dist/src/realtime/memory-board.js +105 -0
- package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
- package/runtime/dist/src/realtime/playback.js +242 -0
- package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
- package/runtime/dist/src/realtime/prompt-language.js +17 -0
- package/runtime/dist/src/realtime/protocol.js +428 -0
- package/runtime/dist/src/realtime/provider-projection.js +526 -0
- package/runtime/dist/src/realtime/provider-session.js +491 -0
- package/runtime/dist/src/realtime/qwen-transport.js +144 -0
- package/runtime/dist/src/realtime/qwen.js +1377 -0
- package/runtime/dist/src/realtime/recall.js +341 -0
- package/runtime/dist/src/realtime/service-ports.js +8 -0
- package/runtime/dist/src/realtime/service-state.js +259 -0
- package/runtime/dist/src/realtime/service.js +1726 -0
- package/runtime/dist/src/realtime/session-state.js +684 -0
- package/runtime/dist/src/realtime/session.js +1976 -0
- package/runtime/dist/src/realtime/speech-prep.js +63 -0
- package/runtime/dist/src/realtime/streaming-speech.js +120 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
- package/runtime/dist/src/realtime/telemetry.js +144 -0
- package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
- package/runtime/dist/src/realtime/transport.js +8 -0
- package/runtime/dist/src/realtime/usage.js +55 -0
- package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
- package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
- package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
- package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
- package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
- package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
- package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
- package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
- package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
- package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
- package/runtime/dist/src/server/aoq-chat-server.js +497 -0
- package/runtime/dist/src/server/client-pairing.js +192 -0
- package/runtime/dist/src/server/client-protocol.js +87 -0
- package/runtime/dist/src/server/client-server.js +312 -0
- package/runtime/dist/src/server/server-config.js +72 -0
- package/runtime/dist/src/server-entry.js +135 -0
- package/runtime/dist/src/storage/bounded-json.js +63 -0
- package/runtime/dist/src/storage/native-file-lock.js +8 -0
- package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
- package/runtime/dist/src/storage/private-database.js +120 -0
- package/runtime/dist/src/text/canonical-json.js +60 -0
- package/runtime/dist/src/text/python-number.js +18 -0
- package/runtime/dist/src/text/python-text.js +92 -0
- package/runtime/dist/src/text/unicode-casefold.js +29 -0
- package/runtime/dist/src/text/unicode-normalize.js +138 -0
- package/runtime/dist/src/text/unicode-tables.js +210 -0
- package/runtime/dist/src/understanding/candidates.js +77 -0
- package/runtime/dist/src/understanding/fixture.js +7 -0
- package/runtime/dist/src/understanding/jev.js +20 -0
- package/runtime/dist/src/understanding/pipeline.js +38 -0
- package/runtime/dist/src/voicemem/store-client.js +476 -0
- package/runtime/dist/src/voicemem/store-worker.js +380 -0
- package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
- package/runtime/scripts/pair-device.mjs +109 -0
- package/src/command.mjs +48 -0
|
@@ -0,0 +1,1484 @@
|
|
|
1
|
+
import { assertAcceptanceGrant, appendAcceptanceCounts } from '../desktop/workbench-acceptance.js';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { watch } from 'node:fs';
|
|
4
|
+
import { processingGrantSchema } from '../memory-substrate/source-state.js';
|
|
5
|
+
import { interleave } from './sampling.js';
|
|
6
|
+
import { GitActivityCache, gitIgnoredDirectories, nextComputerRoot } from './source-priority.js';
|
|
7
|
+
import { scanDirectory } from './source-walk.js';
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { acquirePersonalLock } from './store.js';
|
|
10
|
+
import { lstat, opendir, open, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
|
|
11
|
+
import { basename, parse, dirname, extname, isAbsolute, join, relative, sep } from 'node:path';
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
import { preparePrivateDatabasePath } from '../storage/private-database.js';
|
|
14
|
+
import { SensitivePathPolicy } from '../memory/sensitivity.js';
|
|
15
|
+
import { readKnowledgeFile, KnowledgeDocumentFailure } from '../knowledge/documents.js';
|
|
16
|
+
export const SOURCE_EXCLUDES = ['.git', '.worktrees', '.codex', '.claude', 'node_modules', 'dist', 'build', 'target', '.cache', '__pycache__', '.venv', 'venv', 'Library', 'Browser', 'Chrome', 'Chromium', 'Firefox', 'Safari'];
|
|
17
|
+
const COMPUTER_EXCLUDES = ['Applications', 'opt', 'System', 'Windows', 'Program Files', 'Program Files (x86)', '$RECYCLE.BIN', 'System Volume Information', 'private', 'dev', 'proc', 'sys', 'bin', 'sbin', 'usr', 'etc', 'var', '.Trash', '.Trashes', '.npm', '.cargo', '.rustup', '.local', '.nova-audio-agent'];
|
|
18
|
+
const policy = new SensitivePathPolicy();
|
|
19
|
+
const pathSchema = z.string().min(1).max(4096).refine(value => isAbsolute(value) && !value.includes('\0'));
|
|
20
|
+
const idSchema = z.string().uuid();
|
|
21
|
+
const excludeSchema = z.array(z.string().min(1).max(100).regex(/^[^/\\\0]+$/u)).max(32);
|
|
22
|
+
const scanStageSchema = z.enum(['recover_pending', 'path_validation', 'cleanup', 'computer_batch', 'metadata_walk', 'reconcile', 'knowledge_list', 'recheck', 'ingest', 'health_update', 'on_invalidate', 'on_change', 'observe', 'finalize', 'on_change_final']);
|
|
23
|
+
const snapshotSchema = z.object({
|
|
24
|
+
scope: z.enum(['directory', 'computer']).default('directory'), scan_pending: z.boolean().default(false), indexed: z.number().int().nonnegative().default(0),
|
|
25
|
+
coverage: z.enum(['complete', 'partial']).optional(), health: z.enum(['healthy', 'degraded', 'error']).optional(),
|
|
26
|
+
priority_dirs: z.array(pathSchema).max(16).default([]),
|
|
27
|
+
id: idSchema, path: pathSchema, state: z.enum(['connected', 'paused', 'disconnected', 'error']),
|
|
28
|
+
scanned: z.number().int().nonnegative(), read: z.number().int().nonnegative(), skipped: z.number().int().nonnegative(),
|
|
29
|
+
reasons: z.record(z.string(), z.number().int().nonnegative()),
|
|
30
|
+
failures: z.array(z.object({ path: z.string().max(4096), code: z.string().max(80), stage: scanStageSchema.optional() }).strict()).max(50),
|
|
31
|
+
last_sync: z.string().datetime().nullable(), excludes: excludeSchema,
|
|
32
|
+
processing_consent_required: z.boolean().optional(),
|
|
33
|
+
max_files: z.number().int().min(1).max(200), max_bytes: z.number().int().min(1).max(20 * 1024 * 1024),
|
|
34
|
+
}).strict();
|
|
35
|
+
const trackedSchema = z.object({ unit: pathSchema.optional(), path: pathSchema, id: z.string().min(1).max(80), fingerprint: z.string().max(256),
|
|
36
|
+
cleanup_hidden: z.boolean().optional(), cleanup_attempts: z.number().int().nonnegative().optional(), cleanup_retry_at: z.number().optional(),
|
|
37
|
+
evidence_ids: z.array(z.string().min(1).max(600)).min(1).max(2).optional(), size: z.number().nonnegative(), mtime: z.number(), checked_at: z.number().optional(), recheck_attempts: z.number().int().nonnegative().optional(), recheck_eligible_at: z.number().optional(), recheck_terminal: z.boolean().optional(), observe_attempts: z.number().int().nonnegative().optional(), observe_retry_at: z.number().optional(), observe_error: z.string().max(80).optional(), owned: z.boolean(), valid: z.boolean().default(true), excerpt: z.string().max(900).nullable().default(null), observed: z.boolean().default(false), observation_ref: z.string().max(80).nullable().default(null) }).strict();
|
|
38
|
+
const walkFileSchema = z.object({ path: pathSchema, size: z.number().nonnegative(), mtime: z.number(), unit: pathSchema, attempts: z.number().int().nonnegative().optional(), eligible_at: z.number().optional(), reason: z.enum(['body_budget', 'retry']).optional() }).strict();
|
|
39
|
+
const deferredFileSchema = walkFileSchema.extend({ eligible_at: z.number().default(0), attempts: z.number().int().nonnegative().default(0), reason: z.enum(['body_budget', 'retry']).default('retry') }).strict();
|
|
40
|
+
const directoryLedgerSchema = z.object({ path: pathSchema, unit: pathSchema.optional(), generation: z.number().int().nonnegative(), status: z.enum(['queued', 'done', 'partial']), identity: z.object({ dev: z.string(), ino: z.string(), mtimeNs: z.string() }).strict().optional(), eligible_at: z.number().optional(), attempts: z.number().int().nonnegative().default(0) }).strict();
|
|
41
|
+
const walkSchema = z.object({ queue: z.array(z.object({ path: pathSchema, offset: z.number().int().nonnegative().optional(), unit: pathSchema.optional() }).strict()).max(20000), ledger: z.array(directoryLedgerSchema).max(20000).default([]), generation: z.number().int().nonnegative().default(1), turn: z.number().int().nonnegative().default(0), cursors: z.array(z.number().int().nonnegative()).min(3).max(4).transform(value => [...value, 0, 0, 0].slice(0, 4)).default([0, 0, 0, 0]), probe_cursor: z.number().int().nonnegative().default(0), pending: z.array(walkFileSchema).max(200), deferred: z.array(deferredFileSchema).max(200).default([]), workspace_seeded: pathSchema.optional() }).strict();
|
|
42
|
+
const recordSchema = z.object({ walk: walkSchema.nullable().default(null), processing_consent: processingGrantSchema.optional(), view: snapshotSchema, files: z.array(trackedSchema).max(20000),
|
|
43
|
+
deleting: z.boolean().default(false), observation: z.string().max(500).default(''), cleanup_cursor: z.string().max(80).nullable().default(null),
|
|
44
|
+
pending: z.object({ path: pathSchema, size: z.number().nonnegative(), mtime: z.number(), owned: z.boolean(), previous_updated_at: z.number().nullable() }).strict().nullable().default(null) }).strict();
|
|
45
|
+
const diskSchema = z.object({ version: z.literal(1), sources: z.array(recordSchema).max(8) }).strict();
|
|
46
|
+
const supported = new Set(['.txt', '.md', '.markdown', '.json', '.yaml', '.yml', '.csv', '.ts', '.tsx', '.js', '.jsx', '.py', '.rs', '.go', '.java', '.c', '.h', '.cpp', '.pdf', '.docx']);
|
|
47
|
+
const overviewDocument = (path) => /^(?:readme(?:[._-][a-z]+)?|overview|about|project)\.(?:md|markdown|txt)$/iu.test(basename(path));
|
|
48
|
+
const representativeDocument = (path) => /\.(?:md|markdown|txt|pdf|docx)$/iu.test(path);
|
|
49
|
+
const generatedFile = (path) => /^(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$|\.min\.js$|\.d\.ts$|\.generated\./iu.test(basename(path));
|
|
50
|
+
function balanced(files, root) {
|
|
51
|
+
const groups = new Map();
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
const unit = file.unit ?? join(root, relative(root, file.path).split(sep).slice(0, -1)[0] ?? '');
|
|
54
|
+
const group = groups.get(unit) ?? [];
|
|
55
|
+
group.push(file);
|
|
56
|
+
groups.set(unit, group);
|
|
57
|
+
}
|
|
58
|
+
return interleave(groups.values(), files.length);
|
|
59
|
+
}
|
|
60
|
+
const refFor = (file) => `file:${file.id}:${file.fingerprint}`;
|
|
61
|
+
const errorCode = (error) => error instanceof Error && /^(?:screening_rejected|unsupported_file|file_changed|file_unavailable|embedding_failed|store_failed|knowledge_busy|ingest_failed|source_busy|index_capacity)$/u.test(error.message) ? error.message : 'source_unavailable';
|
|
62
|
+
function isAutoHiddenPath(root, path, selected = []) {
|
|
63
|
+
const parts = relative(root, path).split(sep);
|
|
64
|
+
if (parts.includes('.git'))
|
|
65
|
+
return true;
|
|
66
|
+
const allowed = selected.filter(value => within(value, path)).map(value => relative(root, value).split(sep));
|
|
67
|
+
return parts.some((part, index) => part.startsWith('.') && !allowed.some(prefix => index < prefix.length && prefix[index] === part));
|
|
68
|
+
}
|
|
69
|
+
function isComputerExcludedPath(view, path) {
|
|
70
|
+
if (isAutoHiddenPath(view.path, path, view.priority_dirs))
|
|
71
|
+
return true;
|
|
72
|
+
const excluded = new Set([...SOURCE_EXCLUDES, ...COMPUTER_EXCLUDES, ...view.excludes].map(part => part.toLowerCase()));
|
|
73
|
+
return relative(view.path, path).split(sep).some(part => excluded.has(part.toLowerCase()));
|
|
74
|
+
}
|
|
75
|
+
function hiddenPrefixDepth(view, path) {
|
|
76
|
+
if (view.scope === 'directory')
|
|
77
|
+
return basename(view.path).startsWith('.') ? 1 : 0;
|
|
78
|
+
const selected = view.priority_dirs.filter(dir => within(dir, path)).sort((a, b) => b.length - a.length)[0];
|
|
79
|
+
return selected ? relative(view.path, selected).split(sep).length : 0;
|
|
80
|
+
}
|
|
81
|
+
function computerUnit(root, path) {
|
|
82
|
+
const home = homedir();
|
|
83
|
+
const base = within(home, path) && within(root, home) ? home : root;
|
|
84
|
+
if (dirname(path) === base)
|
|
85
|
+
return base;
|
|
86
|
+
return join(base, relative(base, path).split(sep)[0] ?? '');
|
|
87
|
+
}
|
|
88
|
+
function settlePending(record, path) {
|
|
89
|
+
if (record.walk) {
|
|
90
|
+
record.walk.pending = record.walk.pending.filter(item => item.path !== path);
|
|
91
|
+
record.walk.deferred = record.walk.deferred.filter(item => item.path !== path);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function deferPending(record, file, reason, eligibleAt) {
|
|
95
|
+
if (!record.walk)
|
|
96
|
+
return;
|
|
97
|
+
const previous = record.walk.deferred.find(item => item.path === file.path);
|
|
98
|
+
const attempts = Math.max(file.attempts ?? 0, previous?.attempts ?? 0) + (reason === 'retry' ? 1 : 0);
|
|
99
|
+
settlePending(record, file.path);
|
|
100
|
+
if (record.walk.deferred.length < 200)
|
|
101
|
+
record.walk.deferred.push({ ...file, eligible_at: eligibleAt, attempts, reason });
|
|
102
|
+
else
|
|
103
|
+
record.walk.pending.push({ ...file, eligible_at: eligibleAt, attempts, reason });
|
|
104
|
+
}
|
|
105
|
+
/** Opt-in local grants. Existing knowledge ingestion owns parsing, screening and embeddings. */
|
|
106
|
+
export class LocalDirectorySources {
|
|
107
|
+
#options;
|
|
108
|
+
#records = [];
|
|
109
|
+
#release;
|
|
110
|
+
#path = '';
|
|
111
|
+
#timer;
|
|
112
|
+
#closed = true;
|
|
113
|
+
#polling = false;
|
|
114
|
+
#active = new Map();
|
|
115
|
+
#writes = Promise.resolve();
|
|
116
|
+
#commands = Promise.resolve();
|
|
117
|
+
#workspacePath = null;
|
|
118
|
+
#activity;
|
|
119
|
+
#activityWarmup;
|
|
120
|
+
#watchers = [];
|
|
121
|
+
#dirtyHints = new Map();
|
|
122
|
+
#hintTimers = new Map();
|
|
123
|
+
/** Outlives a scan so pause, removal, and withdrawal also stop background embedding. */
|
|
124
|
+
#lifecycles = new Map();
|
|
125
|
+
#ignored = new Map();
|
|
126
|
+
// Cumulative scan time per stage, reported in acceptance counts.
|
|
127
|
+
#stageTimes = new Map();
|
|
128
|
+
async #timed(key, run) { const at = performance.now(); try {
|
|
129
|
+
return await run();
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
const row = this.#stageTimes.get(key) ?? { ms: 0, n: 0 };
|
|
133
|
+
row.ms += performance.now() - at;
|
|
134
|
+
row.n++;
|
|
135
|
+
this.#stageTimes.set(key, row);
|
|
136
|
+
} }
|
|
137
|
+
constructor(options) { this.#options = options; }
|
|
138
|
+
async open() {
|
|
139
|
+
this.#path = preparePrivateDatabasePath(this.#options.path);
|
|
140
|
+
this.#release = await acquirePersonalLock(this.#path);
|
|
141
|
+
const info = await lstat(this.#path);
|
|
142
|
+
if (info.size > 32 * 1024 * 1024)
|
|
143
|
+
throw new Error('sources_state_too_large');
|
|
144
|
+
const text = await readFile(this.#path, 'utf8');
|
|
145
|
+
const raw = text.trim() ? JSON.parse(text) : { version: 1, sources: [] };
|
|
146
|
+
// Older scans could append a 51st terminal failure after the capped per-file list.
|
|
147
|
+
if (raw && typeof raw === 'object' && 'sources' in raw && Array.isArray(raw.sources))
|
|
148
|
+
for (const item of raw.sources) {
|
|
149
|
+
if (!item || typeof item !== 'object' || !('view' in item))
|
|
150
|
+
continue;
|
|
151
|
+
const view = item.view;
|
|
152
|
+
if (view && typeof view === 'object' && 'failures' in view && Array.isArray(view.failures) && view.failures.length > 50)
|
|
153
|
+
view.failures = view.failures.slice(-50);
|
|
154
|
+
// Older scan writes copied retry metadata from a pending item into an
|
|
155
|
+
// indexed file. It has no meaning once the file is indexed.
|
|
156
|
+
if ('files' in item && Array.isArray(item.files))
|
|
157
|
+
for (const file of item.files) {
|
|
158
|
+
if (!file || typeof file !== 'object')
|
|
159
|
+
continue;
|
|
160
|
+
if ('attempts' in file)
|
|
161
|
+
delete file.attempts;
|
|
162
|
+
if ('eligible_at' in file)
|
|
163
|
+
delete file.eligible_at;
|
|
164
|
+
if ('reason' in file)
|
|
165
|
+
delete file.reason;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
this.#records = diskSchema.parse(raw).sources;
|
|
169
|
+
this.#workspacePath = await this.#options.priorityWorkspace?.().catch(() => null) ?? null;
|
|
170
|
+
assertAcceptanceGrant(this.#options.processingGrant?.(true, 1, 0), this.#records.filter(record => !record.deleting && ['connected', 'error'].includes(record.view.state)).map(record => record.processing_consent ?? { extraction_provider: null, embedding_provider: null }));
|
|
171
|
+
appendAcceptanceCounts('sources_open', { sources: this.#records.length, indexed: this.#records.reduce((sum, record) => sum + record.files.filter(file => file.valid).length, 0) });
|
|
172
|
+
this.#closed = false;
|
|
173
|
+
this.#options.knowledge.setVectorGate?.((id, queuedByOwner) => {
|
|
174
|
+
const record = this.#records.find(item => item.files.some(file => file.id === id));
|
|
175
|
+
// An id no record owns may belong to an unrecovered pending file; only a file this
|
|
176
|
+
// instance is syncing right now, fenced by its lifecycle signal, may proceed unowned.
|
|
177
|
+
if (!record)
|
|
178
|
+
return queuedByOwner ? undefined : null;
|
|
179
|
+
if (this.#closed || record.deleting || !['connected', 'error'].includes(record.view.state))
|
|
180
|
+
return null;
|
|
181
|
+
return { signal: this.#lifecycle(record).signal, grant: record.processing_consent };
|
|
182
|
+
});
|
|
183
|
+
const roots = [...new Set(this.#records.filter(record => !record.deleting && ['connected', 'error'].includes(record.view.state)).flatMap(record => record.files.filter(file => file.valid && file.excerpt).map(file => file.unit ?? computerUnit(record.view.path, file.path))))].slice(0, 64);
|
|
184
|
+
const activity = this.#activity = new GitActivityCache(join(dirname(this.#path), basename(this.#path, '.json') + '.activity.json'));
|
|
185
|
+
this.#activityWarmup = (async () => {
|
|
186
|
+
await activity.open();
|
|
187
|
+
for (let i = 0; i < roots.length && !this.#closed; i += 8)
|
|
188
|
+
await Promise.all(roots.slice(i, i + 8).map(root => activity.get(root, 0)));
|
|
189
|
+
await activity.flush();
|
|
190
|
+
if (!this.#closed && roots.length)
|
|
191
|
+
await this.#options.onChange?.(true);
|
|
192
|
+
})().catch(() => { });
|
|
193
|
+
const resumeVectors = () => void this.#options.knowledge.resumeVectors?.().catch(() => undefined);
|
|
194
|
+
if (this.#options.scanOnOpen === false) {
|
|
195
|
+
resumeVectors();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
for (const record of [...this.#records])
|
|
199
|
+
await this.#recoverPending(record);
|
|
200
|
+
// Resume after pending ownership is recovered, so the gate can fence those files.
|
|
201
|
+
resumeVectors();
|
|
202
|
+
for (const record of [...this.#records]) {
|
|
203
|
+
if (record.deleting)
|
|
204
|
+
await this.#delete(record);
|
|
205
|
+
else if (record.view.state === 'connected' || record.view.state === 'error') {
|
|
206
|
+
if (record.view.scope === 'computer') {
|
|
207
|
+
const timer = setTimeout(() => { if (!this.#closed)
|
|
208
|
+
void this.#sync(record).catch(() => undefined); }, 0);
|
|
209
|
+
timer.unref();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
await this.#poll(true);
|
|
214
|
+
for (const record of this.#records)
|
|
215
|
+
if (record.view.scope === 'computer' && record.view.state === 'connected')
|
|
216
|
+
this.#watchComputer(record);
|
|
217
|
+
const pollMs = this.#options.pollMs ?? 300000;
|
|
218
|
+
if (pollMs > 0) {
|
|
219
|
+
this.#timer = setInterval(() => { void this.#poll().catch(() => undefined); }, pollMs);
|
|
220
|
+
this.#timer.unref();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async close() {
|
|
224
|
+
this.#closed = true;
|
|
225
|
+
await this.#activityWarmup;
|
|
226
|
+
await this.#activity?.flush();
|
|
227
|
+
for (const watcher of this.#watchers)
|
|
228
|
+
watcher.close();
|
|
229
|
+
this.#watchers = [];
|
|
230
|
+
for (const timer of this.#hintTimers.values())
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
this.#hintTimers.clear();
|
|
233
|
+
clearInterval(this.#timer);
|
|
234
|
+
for (const lifecycle of this.#lifecycles.values())
|
|
235
|
+
lifecycle.abort();
|
|
236
|
+
this.#lifecycles.clear();
|
|
237
|
+
for (const active of this.#active.values())
|
|
238
|
+
active.abort.abort();
|
|
239
|
+
await Promise.allSettled([...this.#active.values()].map(active => active.done));
|
|
240
|
+
await this.#commands.catch(() => undefined);
|
|
241
|
+
await this.#writes;
|
|
242
|
+
await this.#release?.();
|
|
243
|
+
this.#release = undefined;
|
|
244
|
+
}
|
|
245
|
+
acceptanceCounts() {
|
|
246
|
+
const now = Date.now(), counts = { sources: this.#records.length, indexed: 0, excerpts: 0, remaining_queue: 0, eligible_queue: 0, deferred_queue: 0, next_due_at: 0, body_budget: 0, retry: 0, directories: 0 };
|
|
247
|
+
for (const record of this.#records) {
|
|
248
|
+
counts.indexed += record.files.filter(file => file.valid).length;
|
|
249
|
+
counts.excerpts += record.files.filter(file => file.valid && file.excerpt).length;
|
|
250
|
+
const dueByPath = new Map((record.walk?.ledger ?? []).map(row => [row.path, row.eligible_at ?? 0]));
|
|
251
|
+
const directories = (record.walk?.queue ?? []).map(item => ({ eligible_at: dueByPath.get(item.path) ?? 0, reason: 'directory' }));
|
|
252
|
+
const work = [...directories, ...(record.walk?.pending ?? []), ...(record.walk?.deferred ?? [])];
|
|
253
|
+
for (const item of work) {
|
|
254
|
+
const due = Number(item.eligible_at ?? 0);
|
|
255
|
+
counts.remaining_queue++;
|
|
256
|
+
if (item.reason === 'body_budget')
|
|
257
|
+
counts.body_budget++;
|
|
258
|
+
else if (item.reason === 'retry')
|
|
259
|
+
counts.retry++;
|
|
260
|
+
else if (item.reason === 'directory')
|
|
261
|
+
counts.directories++;
|
|
262
|
+
if (due <= now)
|
|
263
|
+
counts.eligible_queue++;
|
|
264
|
+
else {
|
|
265
|
+
counts.deferred_queue++;
|
|
266
|
+
counts.next_due_at = counts.next_due_at === 0 ? due : Math.min(counts.next_due_at, due);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const stages = {};
|
|
271
|
+
for (const [stage, row] of this.#stageTimes) {
|
|
272
|
+
stages[`scan_${stage}_ms`] = Math.round(row.ms);
|
|
273
|
+
stages[`scan_${stage}_n`] = row.n;
|
|
274
|
+
}
|
|
275
|
+
return { ...counts, ...stages, ...this.#options.knowledge.timings?.() };
|
|
276
|
+
}
|
|
277
|
+
list() { const expected = this.#options.processingGrant?.(true, 1, 0); return this.#records.map(record => ({ ...structuredClone(record.view), processing_consent_required: !record.processing_consent?.extraction_provider || record.processing_consent.extraction_provider !== expected?.extraction_provider || record.processing_consent.embedding_provider !== expected?.embedding_provider, excludes: [...new Set([...SOURCE_EXCLUDES, ...(record.view.scope === 'computer' ? COMPUTER_EXCLUDES : []), ...record.view.excludes])] })); }
|
|
278
|
+
#watchComputer(record) {
|
|
279
|
+
const hint = (path) => {
|
|
280
|
+
if (!['connected', 'error'].includes(record.view.state))
|
|
281
|
+
return;
|
|
282
|
+
const pending = this.#dirtyHints.get(record.view.id) ?? new Set();
|
|
283
|
+
if (pending.size >= 64) {
|
|
284
|
+
pending.clear();
|
|
285
|
+
pending.add(record.view.path);
|
|
286
|
+
}
|
|
287
|
+
else if (!pending.has(record.view.path))
|
|
288
|
+
pending.add(path);
|
|
289
|
+
this.#dirtyHints.set(record.view.id, pending);
|
|
290
|
+
if (this.#hintTimers.has(record.view.id))
|
|
291
|
+
return;
|
|
292
|
+
// Keep the last verified Git signal while the hinted root is rescanned.
|
|
293
|
+
// Dropping every root here made existing documents lose priority mid-session.
|
|
294
|
+
const timer = setTimeout(() => {
|
|
295
|
+
this.#hintTimers.delete(record.view.id);
|
|
296
|
+
if (this.#closed || !['connected', 'error'].includes(record.view.state))
|
|
297
|
+
return;
|
|
298
|
+
const active = this.#active.get(record.view.id);
|
|
299
|
+
if (active)
|
|
300
|
+
void active.done.catch(() => undefined).then(() => { if (!this.#closed && ['connected', 'error'].includes(record.view.state))
|
|
301
|
+
void this.#sync(record).catch(() => undefined); });
|
|
302
|
+
else
|
|
303
|
+
void this.#sync(record).catch(() => undefined);
|
|
304
|
+
}, 1000);
|
|
305
|
+
timer.unref();
|
|
306
|
+
this.#hintTimers.set(record.view.id, timer);
|
|
307
|
+
};
|
|
308
|
+
try {
|
|
309
|
+
const watcher = watch(record.view.path, { recursive: true }, (_event, filename) => {
|
|
310
|
+
const path = filename ? join(record.view.path, String(filename)) : record.view.path;
|
|
311
|
+
hint(within(record.view.path, path) ? dirname(path) : record.view.path);
|
|
312
|
+
});
|
|
313
|
+
watcher.on('error', () => hint(record.view.path));
|
|
314
|
+
this.#watchers.push(watcher);
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
hint(record.view.path);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
evidence(ref) {
|
|
321
|
+
for (const record of this.#records) {
|
|
322
|
+
const file = record.files.find(file => refFor(file) === ref);
|
|
323
|
+
if (file?.valid && !record.deleting && (record.view.scope !== 'computer' || !isComputerExcludedPath(record.view, file.path)))
|
|
324
|
+
return { subject_key: `file:${file.id}`, source: { type: 'file', ref } };
|
|
325
|
+
}
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
contextEntries() {
|
|
329
|
+
const expected = this.#options.processingGrant?.(true, 1, 0);
|
|
330
|
+
return this.#records.filter(r => !r.deleting && ['connected', 'error'].includes(r.view.state) && !!r.processing_consent?.extraction_provider && r.processing_consent.extraction_provider === expected?.extraction_provider && r.processing_consent.embedding_provider === expected?.embedding_provider).flatMap(record => record.files.filter(f => f.valid && f.excerpt && (record.view.scope !== 'computer' || !isComputerExcludedPath(record.view, f.path))).map(file => { const root = file.unit ?? computerUnit(record.view.path, file.path), activity = this.#activity?.peek(root), gitMs = activity?.lastGitCommitMs; return { last_commit_ms: gitMs ?? null, own_commits: activity?.ownCommits ?? 0, kind: 'file', id: 'source:' + file.id, version: file.fingerprint, content: file.excerpt, source_id: record.view.id, file_id: file.id, root, rel_path: record.view.scope === 'computer' ? relative(record.view.path, file.path) : join(basename(record.view.path), relative(record.view.path, file.path)), role: /\.(?:md|markdown|txt|pdf|docx)$/iu.test(file.path) ? 'document' : /\.(?:json|yaml|yml|csv)$/iu.test(file.path) ? 'config' : 'code', mtime_ms: file.mtime, hidden_prefix_depth: hiddenPrefixDepth(record.view, file.path), priority: record.view.priority_dirs.some(dir => within(dir, file.path)) ? 3 : record.view.scope === 'directory' ? 2 : this.#workspacePath && within(this.#workspacePath, file.path) ? 1 : gitMs !== null && gitMs !== undefined && Date.now() - gitMs < 30 * 86_400_000 ? 1 : 0 }; }));
|
|
331
|
+
}
|
|
332
|
+
evidenceSnapshot() {
|
|
333
|
+
const fingerprints = new Set();
|
|
334
|
+
return interleave(this.#records.filter(record => !record.deleting).map(record => balanced(record.files.filter(file => file.valid && (record.view.scope !== 'computer' || !isComputerExcludedPath(record.view, file.path))), record.view.path).map(file => ({
|
|
335
|
+
ref: refFor(file), fingerprint: file.fingerprint,
|
|
336
|
+
summary: `已授权本地文件:${relative(record.view.path, file.path).slice(0, 160)}`,
|
|
337
|
+
}))), Infinity).filter(file => {
|
|
338
|
+
if (fingerprints.has(file.fingerprint))
|
|
339
|
+
return false;
|
|
340
|
+
fingerprints.add(file.fingerprint);
|
|
341
|
+
return true;
|
|
342
|
+
}).slice(0, 8).map(({ ref, summary }) => ({ ref, summary }));
|
|
343
|
+
}
|
|
344
|
+
command(method, params) {
|
|
345
|
+
// Revocation fences the current ingestion immediately, before waiting for serialized commands.
|
|
346
|
+
if (['sources.pause', 'sources.disconnect', 'sources.delete', 'sources.consent'].includes(method)) {
|
|
347
|
+
const parsed = z.object({ id: idSchema, consent: z.boolean().optional() }).strict().safeParse(params);
|
|
348
|
+
if (parsed.success)
|
|
349
|
+
this.#active.get(parsed.data.id)?.abort.abort();
|
|
350
|
+
if (parsed.success && (method !== 'sources.consent' || parsed.data.consent === false))
|
|
351
|
+
this.#lifecycles.get(parsed.data.id)?.abort();
|
|
352
|
+
}
|
|
353
|
+
const result = this.#commands.then(async () => {
|
|
354
|
+
const target = z.object({ id: idSchema }).passthrough().safeParse(params);
|
|
355
|
+
if (target.success)
|
|
356
|
+
await this.#active.get(target.data.id)?.done.catch(() => undefined);
|
|
357
|
+
else
|
|
358
|
+
await Promise.allSettled([...this.#active.values()].map(active => active.done));
|
|
359
|
+
return this.#command(method, params);
|
|
360
|
+
});
|
|
361
|
+
if (method !== 'sources.sync')
|
|
362
|
+
this.#commands = result.catch(() => undefined);
|
|
363
|
+
return result;
|
|
364
|
+
}
|
|
365
|
+
async #command(method, params) {
|
|
366
|
+
if (this.#closed)
|
|
367
|
+
throw new Error('sources_closed');
|
|
368
|
+
if (method === 'sources.priority.add' || method === 'sources.priority.remove') {
|
|
369
|
+
const { path } = z.object({ path: pathSchema }).strict().parse(params);
|
|
370
|
+
const computer = this.#records.find(record => record.view.scope === 'computer' && !record.deleting && record.view.state !== 'disconnected');
|
|
371
|
+
if (!computer)
|
|
372
|
+
throw Error('source_gone');
|
|
373
|
+
if (method === 'sources.priority.add') {
|
|
374
|
+
const canonical = await realpath(path);
|
|
375
|
+
const excluded = new Set([...SOURCE_EXCLUDES, ...COMPUTER_EXCLUDES, ...computer.view.excludes].map(part => part.toLowerCase()));
|
|
376
|
+
if (canonical !== path || !within(computer.view.path, path) || !policy.allows(path) || !((await lstat(path)).isDirectory()) || relative(computer.view.path, path).split(sep).some(part => excluded.has(part.toLowerCase())))
|
|
377
|
+
throw Error('path_denied');
|
|
378
|
+
if (this.#records.some(record => record !== computer && within(record.view.path, path)))
|
|
379
|
+
throw Error('source_exists');
|
|
380
|
+
if (!computer.view.priority_dirs.includes(path)) {
|
|
381
|
+
if (computer.view.priority_dirs.length >= 16)
|
|
382
|
+
throw Error('source_limit');
|
|
383
|
+
computer.view.priority_dirs.push(path);
|
|
384
|
+
await this.#save();
|
|
385
|
+
}
|
|
386
|
+
if (computer.walk) {
|
|
387
|
+
computer.walk.queue = computer.walk.queue.filter(entry => entry.path !== path);
|
|
388
|
+
computer.walk.queue.unshift({ path });
|
|
389
|
+
computer.walk.ledger = computer.walk.ledger.filter(entry => entry.path !== path);
|
|
390
|
+
await this.#save();
|
|
391
|
+
}
|
|
392
|
+
if (computer.view.state === 'connected' || computer.view.state === 'error')
|
|
393
|
+
void this.#sync(computer).catch(() => undefined);
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
computer.view.priority_dirs = computer.view.priority_dirs.filter(value => value !== path);
|
|
397
|
+
await this.#save();
|
|
398
|
+
}
|
|
399
|
+
await this.#options.onChange?.(false);
|
|
400
|
+
return { ok: true };
|
|
401
|
+
}
|
|
402
|
+
if (method === 'sources.authorize_computer') {
|
|
403
|
+
z.object({ consent: z.literal(true) }).strict().parse(params);
|
|
404
|
+
const existing = this.#records.find(r => r.view.scope === 'computer');
|
|
405
|
+
if (existing)
|
|
406
|
+
return { id: existing.view.id };
|
|
407
|
+
return this.#addComputer();
|
|
408
|
+
}
|
|
409
|
+
if (method === 'sources.add') {
|
|
410
|
+
const parsed = z.object({ path: pathSchema, consent: z.literal(true), excludes: excludeSchema.optional(),
|
|
411
|
+
max_files: snapshotSchema.shape.max_files.optional(), max_bytes: snapshotSchema.shape.max_bytes.optional() }).strict().safeParse(params);
|
|
412
|
+
if (!parsed.success)
|
|
413
|
+
throw new Error('invalid_request');
|
|
414
|
+
const path = await realpath(parsed.data.path);
|
|
415
|
+
if (!policy.allows(path) || !policy.allows(parsed.data.path) || path.split(/[/\\]/u).some(part => SOURCE_EXCLUDES.some(excluded => excluded.toLowerCase() === part.toLowerCase())) || !(await lstat(path)).isDirectory())
|
|
416
|
+
throw new Error('path_denied');
|
|
417
|
+
if (this.#records.length >= 8)
|
|
418
|
+
throw new Error('source_limit');
|
|
419
|
+
if (this.#records.some(record => within(record.view.path, path) || within(path, record.view.path)))
|
|
420
|
+
throw new Error('source_exists');
|
|
421
|
+
const record = { walk: null, view: { scope: 'directory', scan_pending: false, indexed: 0, id: randomUUID(), path, state: 'connected', scanned: 0, read: 0, skipped: 0,
|
|
422
|
+
reasons: {}, failures: [], last_sync: null, excludes: parsed.data.excludes ?? [],
|
|
423
|
+
priority_dirs: [], max_files: parsed.data.max_files ?? 200, max_bytes: parsed.data.max_bytes ?? 20 * 1024 * 1024 }, files: [], deleting: false, observation: '', cleanup_cursor: null, pending: null };
|
|
424
|
+
const grant = this.#options.processingGrant?.(parsed.data.consent, 1, 0);
|
|
425
|
+
if (grant)
|
|
426
|
+
record.processing_consent = grant;
|
|
427
|
+
this.#records.push(record);
|
|
428
|
+
try {
|
|
429
|
+
await this.#save();
|
|
430
|
+
}
|
|
431
|
+
catch (error) {
|
|
432
|
+
this.#records.pop();
|
|
433
|
+
throw error;
|
|
434
|
+
}
|
|
435
|
+
await this.#sync(record);
|
|
436
|
+
return { id: record.view.id };
|
|
437
|
+
}
|
|
438
|
+
if (method === 'sources.consent') {
|
|
439
|
+
const q = z.object({ id: idSchema, consent: z.boolean() }).strict().parse(params);
|
|
440
|
+
const record = this.#records.find(r => r.view.id === q.id);
|
|
441
|
+
if (!record)
|
|
442
|
+
throw Error('source_gone');
|
|
443
|
+
const grant = this.#options.processingGrant?.(q.consent, (record.processing_consent?.revision ?? 0) + 1, record.processing_consent?.scope_revision ?? 0);
|
|
444
|
+
if (!grant)
|
|
445
|
+
throw Error('memory_unavailable');
|
|
446
|
+
await this.#options.onProcessingConsent?.(record.files.flatMap(f => ['knowledge:' + f.id, ...(f.observation_ref ? [f.observation_ref] : [])]), grant);
|
|
447
|
+
record.processing_consent = grant;
|
|
448
|
+
for (const file of record.files)
|
|
449
|
+
file.observed = false;
|
|
450
|
+
await this.#save();
|
|
451
|
+
if (q.consent) {
|
|
452
|
+
// A re-grant lifts the fence a withdrawal left; a paused source stays fenced by its state.
|
|
453
|
+
if (this.#lifecycles.get(record.view.id)?.signal.aborted && ['connected', 'error'].includes(record.view.state))
|
|
454
|
+
this.#lifecycles.delete(record.view.id);
|
|
455
|
+
void this.#options.knowledge.resumeVectors?.().catch(() => undefined);
|
|
456
|
+
}
|
|
457
|
+
await this.#options.onChange?.(false);
|
|
458
|
+
return { ok: true };
|
|
459
|
+
}
|
|
460
|
+
const parsed = z.object({ id: idSchema }).strict().safeParse(params);
|
|
461
|
+
if (!parsed.success)
|
|
462
|
+
throw new Error('invalid_request');
|
|
463
|
+
const record = this.#records.find(record => record.view.id === parsed.data.id);
|
|
464
|
+
if (!record)
|
|
465
|
+
throw new Error('source_gone');
|
|
466
|
+
if (method === 'sources.delete') {
|
|
467
|
+
await this.#delete(record);
|
|
468
|
+
return { ok: true };
|
|
469
|
+
}
|
|
470
|
+
if (record.view.state === 'disconnected' && ['sources.pause', 'sources.resume', 'sources.sync'].includes(method))
|
|
471
|
+
throw new Error('source_disconnected');
|
|
472
|
+
if (method === 'sources.pause' || method === 'sources.disconnect') {
|
|
473
|
+
const before = record.view.state;
|
|
474
|
+
record.view.state = method === 'sources.pause' ? 'paused' : 'disconnected';
|
|
475
|
+
try {
|
|
476
|
+
await this.#save();
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
record.view.state = before;
|
|
480
|
+
throw error;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
else if (method === 'sources.resume') {
|
|
484
|
+
record.view.state = 'connected';
|
|
485
|
+
await this.#save();
|
|
486
|
+
await this.#sync(record);
|
|
487
|
+
void this.#options.knowledge.resumeVectors?.().catch(() => undefined);
|
|
488
|
+
}
|
|
489
|
+
else if (method === 'sources.sync') {
|
|
490
|
+
if (record.view.state === 'connected' || record.view.state === 'error')
|
|
491
|
+
await this.#sync(record, true);
|
|
492
|
+
}
|
|
493
|
+
else
|
|
494
|
+
throw new Error('invalid_request');
|
|
495
|
+
await this.#options.onChange?.(false);
|
|
496
|
+
return { ok: true };
|
|
497
|
+
}
|
|
498
|
+
async #addComputer() {
|
|
499
|
+
if (this.#records.length >= 8)
|
|
500
|
+
throw Error('source_limit');
|
|
501
|
+
const path = await realpath(this.#options.computerRoot ?? parse(homedir()).root);
|
|
502
|
+
const record = { walk: null, view: { scope: 'computer', scan_pending: true, indexed: 0, priority_dirs: [], id: randomUUID(), path, state: 'connected', scanned: 0, read: 0, skipped: 0, reasons: {}, failures: [], last_sync: null, excludes: [], max_files: 200, max_bytes: 20 * 1024 * 1024 }, files: [], deleting: false, observation: '', cleanup_cursor: null, pending: null };
|
|
503
|
+
const grant = this.#options.processingGrant?.(true, 1, 0);
|
|
504
|
+
if (grant)
|
|
505
|
+
record.processing_consent = grant;
|
|
506
|
+
this.#records.push(record);
|
|
507
|
+
try {
|
|
508
|
+
await this.#save();
|
|
509
|
+
}
|
|
510
|
+
catch (error) {
|
|
511
|
+
this.#records.pop();
|
|
512
|
+
throw error;
|
|
513
|
+
}
|
|
514
|
+
// The grant returns immediately; indexing cannot block the settings window.
|
|
515
|
+
void this.#sync(record).catch(() => undefined);
|
|
516
|
+
this.#watchComputer(record);
|
|
517
|
+
return { id: record.view.id };
|
|
518
|
+
}
|
|
519
|
+
async #computerBatch(record, signal, force = false) {
|
|
520
|
+
const walk = record.walk ?? (record.walk = { queue: [...record.view.priority_dirs.map(path => ({ path })), { path: record.view.path }], ledger: [], generation: 1, turn: 0, cursors: [0, 0, 0, 0], probe_cursor: 0, pending: [], deferred: [] });
|
|
521
|
+
// v1 offsets are deliberately ignored: reopening a changed directory starts a new pass.
|
|
522
|
+
const ledger = new Map(walk.ledger.map(item => [item.path, item]));
|
|
523
|
+
for (const item of walk.queue)
|
|
524
|
+
if (!ledger.has(item.path)) {
|
|
525
|
+
if (ledger.size >= 20000) {
|
|
526
|
+
record.view.reasons.directory_capacity = (record.view.reasons.directory_capacity ?? 0) + 1;
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
ledger.set(item.path, { path: item.path, unit: item.unit, generation: walk.generation, status: 'queued', attempts: 0 });
|
|
530
|
+
}
|
|
531
|
+
walk.queue = walk.queue.filter(item => ledger.has(item.path));
|
|
532
|
+
const resumePaths = new Set(walk.queue.map(item => item.path));
|
|
533
|
+
for (const item of ledger.values())
|
|
534
|
+
if (item.status === 'queued' && !resumePaths.has(item.path) && walk.queue.length < 20000) {
|
|
535
|
+
walk.queue.push({ path: item.path, ...(item.unit ? { unit: item.unit } : {}) });
|
|
536
|
+
resumePaths.add(item.path);
|
|
537
|
+
}
|
|
538
|
+
if (force && walk.queue.length === 0 && walk.pending.length === 0 && walk.deferred.length === 0 && ledger.size > 0) {
|
|
539
|
+
walk.generation++;
|
|
540
|
+
for (const entry of ledger.values())
|
|
541
|
+
entry.status = 'queued';
|
|
542
|
+
walk.queue = [...record.view.priority_dirs.map(path => ({ path })), { path: record.view.path }];
|
|
543
|
+
}
|
|
544
|
+
else if (walk.queue.length === 0 && walk.pending.length === 0 && walk.deferred.length === 0) {
|
|
545
|
+
const due = [...ledger.values()].filter(item => (item.eligible_at ?? Infinity) <= Date.now()).slice(0, 64);
|
|
546
|
+
if (due.length) {
|
|
547
|
+
walk.generation++;
|
|
548
|
+
for (const item of due) {
|
|
549
|
+
item.generation = walk.generation;
|
|
550
|
+
item.status = 'queued';
|
|
551
|
+
walk.queue.push({ path: item.path, ...(item.unit ? { unit: item.unit } : {}) });
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
const hints = this.#dirtyHints.get(record.view.id);
|
|
556
|
+
if (hints?.size) {
|
|
557
|
+
walk.generation++;
|
|
558
|
+
const existing = new Set(walk.queue.map(item => item.path));
|
|
559
|
+
for (const path of [...hints].slice(0, 64)) {
|
|
560
|
+
const old = ledger.get(path);
|
|
561
|
+
if (!old && ledger.size >= 20000 || !existing.has(path) && walk.queue.length >= 20000) {
|
|
562
|
+
record.view.reasons.directory_capacity = (record.view.reasons.directory_capacity ?? 0) + 1;
|
|
563
|
+
hints.delete(path);
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
// Watch events can name subtrees that the normal walk deliberately never entered.
|
|
567
|
+
let unit;
|
|
568
|
+
for (let ancestor = path; within(record.view.path, ancestor); ancestor = dirname(ancestor)) {
|
|
569
|
+
const marker = await lstat(join(ancestor, '.git')).catch(() => null);
|
|
570
|
+
if (marker && (marker.isDirectory() || marker.isFile()) && !marker.isSymbolicLink()) {
|
|
571
|
+
unit = ancestor;
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
if (ancestor === record.view.path)
|
|
575
|
+
break;
|
|
576
|
+
}
|
|
577
|
+
ledger.set(path, { ...old, path, unit, generation: walk.generation, status: 'queued', attempts: old?.attempts ?? 0 });
|
|
578
|
+
const queued = walk.queue.find(item => item.path === path);
|
|
579
|
+
if (queued)
|
|
580
|
+
queued.unit = unit;
|
|
581
|
+
else {
|
|
582
|
+
walk.queue.push({ path, ...(unit ? { unit } : {}) });
|
|
583
|
+
existing.add(path);
|
|
584
|
+
}
|
|
585
|
+
hints.delete(path);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const now = Date.now();
|
|
589
|
+
const eligible = walk.deferred.filter(item => item.eligible_at <= now).slice(0, Math.max(0, 200 - walk.pending.length));
|
|
590
|
+
const eligiblePaths = new Set(eligible.map(item => item.path));
|
|
591
|
+
walk.deferred = walk.deferred.filter(item => !eligiblePaths.has(item.path));
|
|
592
|
+
const pendingPaths = new Set(walk.pending.map(item => item.path));
|
|
593
|
+
const queuedPaths = new Set(walk.queue.map(item => item.path));
|
|
594
|
+
for (const item of eligible)
|
|
595
|
+
if (!pendingPaths.has(item.path)) {
|
|
596
|
+
walk.pending.push({ ...item });
|
|
597
|
+
pendingPaths.add(item.path);
|
|
598
|
+
}
|
|
599
|
+
const excluded = new Set([...SOURCE_EXCLUDES, ...COMPUTER_EXCLUDES, ...record.view.excludes].map(s => s.toLowerCase()));
|
|
600
|
+
const workspace = await this.#options.priorityWorkspace?.().catch(() => null) ?? null;
|
|
601
|
+
this.#workspacePath = workspace;
|
|
602
|
+
const enqueue = (path, unit) => {
|
|
603
|
+
const prior = ledger.get(path);
|
|
604
|
+
if (prior?.generation === walk.generation && (prior.status === 'done' || prior.status === 'partial' || queuedPaths.has(path)))
|
|
605
|
+
return;
|
|
606
|
+
if (walk.queue.length >= 20000 || ledger.size >= 20000) {
|
|
607
|
+
record.view.reasons.directory_capacity = (record.view.reasons.directory_capacity ?? 0) + 1;
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
ledger.set(path, { ...prior, path, unit, generation: walk.generation, status: 'queued', attempts: prior?.attempts ?? 0 });
|
|
611
|
+
walk.queue.push({ path, ...(unit ? { unit } : {}) });
|
|
612
|
+
queuedPaths.add(path);
|
|
613
|
+
};
|
|
614
|
+
if (workspace && walk.workspace_seeded !== workspace) {
|
|
615
|
+
walk.workspace_seeded = workspace;
|
|
616
|
+
if (workspace !== record.view.path && !isComputerExcludedPath(record.view, workspace) && policy.allows(workspace) && await realpath(workspace).catch(() => null) === workspace && await lstat(workspace).then(stat => stat.isDirectory()).catch(() => false)) {
|
|
617
|
+
enqueue(workspace);
|
|
618
|
+
const index = walk.queue.findIndex(item => item.path === workspace);
|
|
619
|
+
if (index > 0)
|
|
620
|
+
walk.queue.unshift(walk.queue.splice(index, 1)[0]);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
const knownFiles = new Map(record.files.filter(file => file.valid).map(file => [file.path, file]));
|
|
624
|
+
const indexedActivity = new Map();
|
|
625
|
+
for (const file of knownFiles.values()) {
|
|
626
|
+
let directory = dirname(file.path);
|
|
627
|
+
while (within(record.view.path, directory)) {
|
|
628
|
+
indexedActivity.set(directory, Math.max(indexedActivity.get(directory) ?? 0, file.mtime));
|
|
629
|
+
if (directory === record.view.path)
|
|
630
|
+
break;
|
|
631
|
+
const parent = dirname(directory);
|
|
632
|
+
if (parent === directory)
|
|
633
|
+
break;
|
|
634
|
+
directory = parent;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const signalFor = async (path) => {
|
|
638
|
+
const recent = await (this.#activity ??= new GitActivityCache()).get(path);
|
|
639
|
+
// Only already-indexed eligible files can add a file-activity clue. This avoids
|
|
640
|
+
// using generated or unreadable files to promote an otherwise inactive tree.
|
|
641
|
+
const indexedFileMtime = indexedActivity.get(path) ?? 0;
|
|
642
|
+
return { path, selected: record.view.priority_dirs.some(value => within(value, path)), currentWorkspace: !!workspace && within(workspace, path), ...recent, mtimeMs: Math.max(recent.mtimeMs, indexedFileMtime) };
|
|
643
|
+
};
|
|
644
|
+
let turns = 0;
|
|
645
|
+
let metadataSeen = 0;
|
|
646
|
+
let statCalls = 0;
|
|
647
|
+
let recheckAdmitted = 0;
|
|
648
|
+
const statBudget = this.#options.metadataStatBudget ?? 20_000;
|
|
649
|
+
const yielded = new Set();
|
|
650
|
+
const cursors = walk.cursors;
|
|
651
|
+
try {
|
|
652
|
+
while (walk.queue.length && walk.pending.length < 16 && metadataSeen < 20_000 && statCalls < statBudget && turns++ < 64) {
|
|
653
|
+
signal.throwIfAborted();
|
|
654
|
+
// Rotate roots; ranking is a tier hint, not a permanent sort of every turn.
|
|
655
|
+
const front = walk.queue.slice(0, Math.min(32, walk.queue.length));
|
|
656
|
+
const tail = walk.queue.slice(front.length);
|
|
657
|
+
const tailStart = tail.length ? walk.probe_cursor % tail.length : 0;
|
|
658
|
+
const tailCount = Math.min(8, tail.length);
|
|
659
|
+
const tailProbe = Array.from({ length: tailCount }, (_, index) => tail[(tailStart + index) % tail.length]);
|
|
660
|
+
if (tailProbe.length)
|
|
661
|
+
walk.probe_cursor = (tailStart + tailCount) % tail.length;
|
|
662
|
+
const sample = [...front, ...tailProbe];
|
|
663
|
+
const signals = await Promise.all(sample.map(item => signalFor(item.path)));
|
|
664
|
+
const turn = walk.turn++;
|
|
665
|
+
const candidate = nextComputerRoot(signals, turn, cursors, yielded) ?? nextComputerRoot(signals, turn, cursors);
|
|
666
|
+
const selected = sample.find(item => item.path === candidate.path);
|
|
667
|
+
const index = walk.queue.indexOf(selected), directory = walk.queue.splice(index, 1)[0];
|
|
668
|
+
if (index < front.length && walk.queue.length > front.length)
|
|
669
|
+
walk.probe_cursor = Math.max(0, walk.probe_cursor - 1);
|
|
670
|
+
else if (index >= front.length && index - front.length < walk.probe_cursor)
|
|
671
|
+
walk.probe_cursor--;
|
|
672
|
+
const remainingTail = Math.max(0, walk.queue.length - Math.min(32, walk.queue.length));
|
|
673
|
+
if (remainingTail)
|
|
674
|
+
walk.probe_cursor %= remainingTail;
|
|
675
|
+
else
|
|
676
|
+
walk.probe_cursor = 0;
|
|
677
|
+
queuedPaths.delete(directory.path);
|
|
678
|
+
const item = ledger.get(directory.path) ?? { path: directory.path, generation: walk.generation, status: 'queued', attempts: 0 };
|
|
679
|
+
item.generation = walk.generation;
|
|
680
|
+
ledger.set(directory.path, item);
|
|
681
|
+
if (directory.path !== record.view.path && (isAutoHiddenPath(record.view.path, directory.path, record.view.priority_dirs) || relative(record.view.path, directory.path).split(sep).some(part => excluded.has(part.toLowerCase())))) {
|
|
682
|
+
ledger.delete(directory.path);
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
const seen = new Set();
|
|
686
|
+
let admitted = 0;
|
|
687
|
+
try {
|
|
688
|
+
if (await realpath(directory.path) !== directory.path)
|
|
689
|
+
throw Error('changed_path');
|
|
690
|
+
const marker = await lstat(join(directory.path, '.git')).catch(() => null);
|
|
691
|
+
if (marker && (marker.isDirectory() || marker.isFile()) && !marker.isSymbolicLink())
|
|
692
|
+
directory.unit = directory.path;
|
|
693
|
+
item.unit = directory.unit;
|
|
694
|
+
const ignored = directory.unit ? await this.#ignoredIn(directory.unit) : undefined;
|
|
695
|
+
if (ignored === null)
|
|
696
|
+
throw Error('git_ignore_unavailable');
|
|
697
|
+
if (ignored && [...ignored].some(path => within(path, directory.path) && !record.view.priority_dirs.some(dir => within(path, dir)))) {
|
|
698
|
+
ledger.delete(directory.path);
|
|
699
|
+
record.view.skipped++;
|
|
700
|
+
record.view.reasons.git_ignored = (record.view.reasons.git_ignored ?? 0) + 1;
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
const safetyCap = this.#options.directorySafetyCap ?? 20_000;
|
|
704
|
+
const passCap = Math.min(safetyCap, 20_000 - metadataSeen);
|
|
705
|
+
const result = await scanDirectory(directory.path, signal, async (entry) => {
|
|
706
|
+
metadataSeen++;
|
|
707
|
+
const path = join(directory.path, entry.name);
|
|
708
|
+
seen.add(entry.name);
|
|
709
|
+
if (isAutoHiddenPath(record.view.path, path, record.view.priority_dirs) || excluded.has(entry.name.toLowerCase()) || !policy.allows(path) || entry.isSymbolicLink()) {
|
|
710
|
+
record.view.skipped++;
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (entry.isDirectory()) {
|
|
714
|
+
if (this.#records.some(r => r !== record && within(r.view.path, path)) || record.view.priority_dirs.includes(path))
|
|
715
|
+
return;
|
|
716
|
+
if (ignored?.has(path) && !record.view.priority_dirs.some(dir => within(path, dir))) {
|
|
717
|
+
record.view.skipped++;
|
|
718
|
+
record.view.reasons.git_ignored = (record.view.reasons.git_ignored ?? 0) + 1;
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
enqueue(path, directory.unit);
|
|
722
|
+
}
|
|
723
|
+
else if (entry.isFile()) {
|
|
724
|
+
record.view.scanned++;
|
|
725
|
+
if (!supported.has(extname(path).toLowerCase()) || generatedFile(path)) {
|
|
726
|
+
record.view.skipped++;
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (pendingPaths.has(path))
|
|
730
|
+
return;
|
|
731
|
+
if (walk.pending.length >= 16 || admitted >= 4 && walk.queue.length)
|
|
732
|
+
throw Error('directory_yield');
|
|
733
|
+
if (statCalls >= statBudget)
|
|
734
|
+
throw Error('stat_budget');
|
|
735
|
+
const stat = await lstat(path);
|
|
736
|
+
statCalls++;
|
|
737
|
+
this.#options.onMetadataStat?.();
|
|
738
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
739
|
+
return;
|
|
740
|
+
const prior = knownFiles.get(path);
|
|
741
|
+
if (prior?.size === stat.size && prior.mtime === stat.mtimeMs) {
|
|
742
|
+
if ((prior.checked_at ?? 0) + (this.#options.contentRecheckMs ?? 300_000) > Date.now() || recheckAdmitted >= 4)
|
|
743
|
+
return;
|
|
744
|
+
recheckAdmitted++;
|
|
745
|
+
}
|
|
746
|
+
walk.pending.push({ path, size: stat.size, mtime: stat.mtimeMs, unit: directory.unit ?? computerUnit(record.view.path, path) });
|
|
747
|
+
pendingPaths.add(path);
|
|
748
|
+
admitted++;
|
|
749
|
+
}
|
|
750
|
+
}, { hardSafetyCap: passCap });
|
|
751
|
+
if (result.complete && (!item.identity || item.identity.dev === result.identity.dev && item.identity.ino === result.identity.ino)) {
|
|
752
|
+
// A complete, same-filesystem parent pass is the sole deletion authority.
|
|
753
|
+
if (item.identity) {
|
|
754
|
+
for (const file of [...record.files])
|
|
755
|
+
if (within(directory.path, file.path) && file.path !== directory.path && !seen.has(relative(directory.path, file.path).split(sep)[0]))
|
|
756
|
+
await this.#removeFile(record, file);
|
|
757
|
+
const removed = new Set();
|
|
758
|
+
for (const path of ledger.keys())
|
|
759
|
+
if (path !== directory.path && within(directory.path, path) && !seen.has(relative(directory.path, path).split(sep)[0])) {
|
|
760
|
+
ledger.delete(path);
|
|
761
|
+
queuedPaths.delete(path);
|
|
762
|
+
removed.add(path);
|
|
763
|
+
}
|
|
764
|
+
if (removed.size)
|
|
765
|
+
walk.queue = walk.queue.filter(entry => !removed.has(entry.path));
|
|
766
|
+
}
|
|
767
|
+
item.status = 'done';
|
|
768
|
+
item.identity = result.identity;
|
|
769
|
+
item.attempts = 0;
|
|
770
|
+
item.eligible_at = Date.now() + (record.view.priority_dirs.some(path => within(path, directory.path)) || !!workspace && within(workspace, directory.path) ? 300_000 : 86_400_000);
|
|
771
|
+
}
|
|
772
|
+
else if (result.capped && passCap < safetyCap) {
|
|
773
|
+
walk.queue.push(directory);
|
|
774
|
+
queuedPaths.add(directory.path);
|
|
775
|
+
}
|
|
776
|
+
else {
|
|
777
|
+
const changedFilesystem = !!item.identity && (item.identity.dev !== result.identity.dev || item.identity.ino !== result.identity.ino);
|
|
778
|
+
item.status = 'partial';
|
|
779
|
+
item.eligible_at = Date.now() + (result.capped || changedFilesystem ? 86_400_000 : 60_000);
|
|
780
|
+
record.view.reasons.directory_partial = (record.view.reasons.directory_partial ?? 0) + 1;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
catch (error) {
|
|
784
|
+
if (signal.aborted) {
|
|
785
|
+
walk.queue.push(directory);
|
|
786
|
+
queuedPaths.add(directory.path);
|
|
787
|
+
signal.throwIfAborted();
|
|
788
|
+
}
|
|
789
|
+
if (error instanceof Error && ['directory_yield', 'stat_budget'].includes(error.message)) {
|
|
790
|
+
walk.queue.push(directory);
|
|
791
|
+
queuedPaths.add(directory.path);
|
|
792
|
+
yielded.add(directory.path);
|
|
793
|
+
continue;
|
|
794
|
+
}
|
|
795
|
+
item.status = 'partial';
|
|
796
|
+
item.attempts++;
|
|
797
|
+
item.eligible_at = Date.now() + Math.min(6 * 60 * 60_000, 60_000 * 2 ** Math.min(item.attempts - 1, 8));
|
|
798
|
+
record.view.reasons.directory_unavailable = (record.view.reasons.directory_unavailable ?? 0) + 1;
|
|
799
|
+
if (record.view.failures.length < 50)
|
|
800
|
+
record.view.failures.push({ path: directory.path, code: error instanceof Error && 'code' in error ? String(error.code) : 'directory_unavailable' });
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
finally {
|
|
805
|
+
walk.ledger = [...ledger.values()];
|
|
806
|
+
record.view.scan_pending = walk.queue.length > 0 || walk.pending.length > 0 || walk.deferred.length > 0 || walk.ledger.some(item => item.status === 'partial');
|
|
807
|
+
await this.#save();
|
|
808
|
+
}
|
|
809
|
+
return walk.pending.filter(item => (item.eligible_at ?? 0) <= Date.now());
|
|
810
|
+
}
|
|
811
|
+
async #poll(directoryOnly = false) {
|
|
812
|
+
if (this.#closed || this.#polling)
|
|
813
|
+
return;
|
|
814
|
+
this.#polling = true;
|
|
815
|
+
const records = this.#records.filter(record => (!directoryOnly || record.view.scope === 'directory') && ['connected', 'error'].includes(record.view.state));
|
|
816
|
+
let next = 0;
|
|
817
|
+
try {
|
|
818
|
+
await Promise.all(Array.from({ length: Math.min(4, records.length) }, async () => {
|
|
819
|
+
while (next < records.length && !this.#closed)
|
|
820
|
+
await this.#sync(records[next++]);
|
|
821
|
+
}));
|
|
822
|
+
}
|
|
823
|
+
finally {
|
|
824
|
+
this.#polling = false;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
/** One bounded Git listing per repository per ten minutes; the walk never descends into what it ignores. */
|
|
828
|
+
#ignoredIn(root) {
|
|
829
|
+
const cached = this.#ignored.get(root);
|
|
830
|
+
if (cached && Date.now() - cached.checked < 600_000)
|
|
831
|
+
return cached.dirs;
|
|
832
|
+
// A timed-out or failed probe is not cached, so the next batch asks Git again.
|
|
833
|
+
const entry = { dirs: gitIgnoredDirectories(root).then(found => { if (!found && this.#ignored.get(root) === entry)
|
|
834
|
+
this.#ignored.delete(root); return found; }), checked: Date.now() };
|
|
835
|
+
this.#ignored.set(root, entry);
|
|
836
|
+
if (this.#ignored.size > 256)
|
|
837
|
+
this.#ignored.delete(this.#ignored.keys().next().value);
|
|
838
|
+
return entry.dirs;
|
|
839
|
+
}
|
|
840
|
+
#lifecycle(record) {
|
|
841
|
+
let lifecycle = this.#lifecycles.get(record.view.id);
|
|
842
|
+
if (!lifecycle) {
|
|
843
|
+
lifecycle = new AbortController();
|
|
844
|
+
this.#lifecycles.set(record.view.id, lifecycle);
|
|
845
|
+
}
|
|
846
|
+
return lifecycle;
|
|
847
|
+
}
|
|
848
|
+
async #sync(record, force = false) {
|
|
849
|
+
if (this.#closed)
|
|
850
|
+
return;
|
|
851
|
+
while (this.#active.size >= 4 && !this.#active.has(record.view.id) && !this.#closed)
|
|
852
|
+
await Promise.race([...this.#active.values()].map(active => active.done)).catch(() => undefined);
|
|
853
|
+
if (this.#closed || record.deleting || !['connected', 'error'].includes(record.view.state))
|
|
854
|
+
return;
|
|
855
|
+
const existing = this.#active.get(record.view.id);
|
|
856
|
+
if (existing)
|
|
857
|
+
return existing.done;
|
|
858
|
+
// A scan only runs while the source is connected, so it may renew a fence left by a failed pause.
|
|
859
|
+
if (this.#lifecycles.get(record.view.id)?.signal.aborted)
|
|
860
|
+
this.#lifecycles.delete(record.view.id);
|
|
861
|
+
const abort = new AbortController();
|
|
862
|
+
const done = this.#scan(record, abort.signal, force).finally(() => {
|
|
863
|
+
this.#active.delete(record.view.id);
|
|
864
|
+
void this.#activity?.flush();
|
|
865
|
+
if (record.view.scope !== 'computer' || !record.view.scan_pending || this.#closed || !['connected', 'error'].includes(record.view.state))
|
|
866
|
+
return;
|
|
867
|
+
const walk = record.walk, now = Date.now();
|
|
868
|
+
const duePending = !!walk?.pending.some(item => (item.eligible_at ?? 0) <= now);
|
|
869
|
+
const canDiscover = !!walk?.queue.length && walk.pending.length < 16;
|
|
870
|
+
const cleanupFiles = record.files.filter(file => isComputerExcludedPath(record.view, file.path));
|
|
871
|
+
const cleanupPending = cleanupFiles.some(file => (file.cleanup_retry_at ?? 0) <= now);
|
|
872
|
+
const immediate = duePending || canDiscover || cleanupPending;
|
|
873
|
+
const pendingDue = walk?.pending.filter(item => (item.eligible_at ?? 0) > now).map(item => item.eligible_at) ?? [];
|
|
874
|
+
const deferredDue = walk && walk.pending.length < 200 ? walk.deferred.map(item => item.eligible_at) : [];
|
|
875
|
+
const directoryDue = walk && !walk.queue.length && !walk.pending.length && !walk.deferred.length ? walk.ledger.filter(item => item.status === 'partial' && item.eligible_at !== undefined).map(item => item.eligible_at) : [];
|
|
876
|
+
const cleanupDue = cleanupFiles.map(file => file.cleanup_retry_at).filter((due) => due !== undefined && due > now);
|
|
877
|
+
const due = Math.min(...pendingDue, ...deferredDue, ...directoryDue, ...cleanupDue, Infinity);
|
|
878
|
+
const delay = immediate ? (record.view.state === 'error' ? 30000 : 1000) : Number.isFinite(due) ? Math.min(Math.max(1, due - now), 6 * 60 * 60_000) : 30000;
|
|
879
|
+
const timer = setTimeout(() => { if (!this.#closed && !this.#active.has(record.view.id) && ['connected', 'error'].includes(record.view.state))
|
|
880
|
+
void this.#sync(record).catch(() => undefined); }, delay);
|
|
881
|
+
timer.unref();
|
|
882
|
+
});
|
|
883
|
+
this.#active.set(record.view.id, { abort, done });
|
|
884
|
+
await done;
|
|
885
|
+
}
|
|
886
|
+
async #scan(record, signal, force = false) {
|
|
887
|
+
const view = record.view;
|
|
888
|
+
const beforeEvidence = record.files.filter(file => file.valid).map(refFor).sort().join();
|
|
889
|
+
const beforeObservation = record.observation;
|
|
890
|
+
view.read = 0;
|
|
891
|
+
if (view.scope !== 'computer' || record.walk === null) {
|
|
892
|
+
view.scanned = 0;
|
|
893
|
+
view.skipped = 0;
|
|
894
|
+
view.reasons = {};
|
|
895
|
+
view.failures = [];
|
|
896
|
+
}
|
|
897
|
+
const skip = (reason) => { view.skipped++; view.reasons[reason] = (view.reasons[reason] ?? 0) + 1; };
|
|
898
|
+
const files = [];
|
|
899
|
+
const seen = new Set(), excluded = new Set([...SOURCE_EXCLUDES, ...view.excludes].map(name => name.toLowerCase()));
|
|
900
|
+
const directories = [{ path: view.path, depth: 0, project: null }];
|
|
901
|
+
const projectEntries = new Map();
|
|
902
|
+
const projects = new Set();
|
|
903
|
+
let complete = true, visited = 0;
|
|
904
|
+
let currentReadFailure = false, currentObserveFailure = false, currentCleanupFailure = false;
|
|
905
|
+
let observationPaths = new Set();
|
|
906
|
+
let stage = 'recover_pending';
|
|
907
|
+
let stageAt = performance.now();
|
|
908
|
+
const enter = (next) => { const now = performance.now(), row = this.#stageTimes.get(stage) ?? { ms: 0, n: 0 }; row.ms += now - stageAt; row.n++; this.#stageTimes.set(stage, row); stage = next; stageAt = now; };
|
|
909
|
+
try {
|
|
910
|
+
// Finish an interrupted replacement before metadata discovery can
|
|
911
|
+
// overwrite the checkpoint with the already-committed index timestamp.
|
|
912
|
+
await this.#recoverPending(record);
|
|
913
|
+
enter('path_validation');
|
|
914
|
+
if (view.scope !== 'computer' && await realpath(view.path) !== view.path)
|
|
915
|
+
throw new Error('path_denied');
|
|
916
|
+
if (view.scope === 'computer') {
|
|
917
|
+
enter('cleanup');
|
|
918
|
+
currentCleanupFailure = await this.#cleanupExcludedFiles(record, signal);
|
|
919
|
+
if (record.walk) {
|
|
920
|
+
record.walk.pending = record.walk.pending.filter(file => !isComputerExcludedPath(view, file.path));
|
|
921
|
+
record.walk.deferred = record.walk.deferred.filter(file => !isComputerExcludedPath(view, file.path));
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (view.scope === 'computer') {
|
|
925
|
+
enter('computer_batch');
|
|
926
|
+
files.push(...await this.#computerBatch(record, signal, force));
|
|
927
|
+
directories.length = 0;
|
|
928
|
+
complete = false;
|
|
929
|
+
}
|
|
930
|
+
enter('metadata_walk');
|
|
931
|
+
while (directories.length > 0 && visited < 20000) {
|
|
932
|
+
signal.throwIfAborted();
|
|
933
|
+
const directory = directories.shift();
|
|
934
|
+
if (await realpath(directory.path) !== directory.path) {
|
|
935
|
+
complete = false;
|
|
936
|
+
skip('changed_path');
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
939
|
+
const marker = await lstat(join(directory.path, '.git')).catch(() => null);
|
|
940
|
+
if (marker && !marker.isSymbolicLink() && (marker.isDirectory() || marker.isFile())) {
|
|
941
|
+
directory.project = directory.path;
|
|
942
|
+
projects.add(directory.path);
|
|
943
|
+
}
|
|
944
|
+
for await (const entry of await opendir(directory.path)) {
|
|
945
|
+
signal.throwIfAborted();
|
|
946
|
+
if (directory.project) {
|
|
947
|
+
const count = (projectEntries.get(directory.project) ?? 0) + 1;
|
|
948
|
+
projectEntries.set(directory.project, count);
|
|
949
|
+
if (count > 2000) {
|
|
950
|
+
complete = false;
|
|
951
|
+
skip('project_metadata_limit');
|
|
952
|
+
break;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
if (++visited > 20000) {
|
|
956
|
+
complete = false;
|
|
957
|
+
break;
|
|
958
|
+
}
|
|
959
|
+
const path = join(directory.path, entry.name);
|
|
960
|
+
if (excluded.has(entry.name.toLowerCase()) || !policy.allows(path)) {
|
|
961
|
+
skip('excluded');
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (entry.isSymbolicLink()) {
|
|
965
|
+
skip('symbolic_link');
|
|
966
|
+
continue;
|
|
967
|
+
}
|
|
968
|
+
if (entry.isDirectory()) {
|
|
969
|
+
if (directory.depth < 16)
|
|
970
|
+
directories.push({ path, depth: directory.depth + 1, project: directory.project });
|
|
971
|
+
else {
|
|
972
|
+
skip('depth_limit');
|
|
973
|
+
complete = false;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
else if (entry.isFile()) {
|
|
977
|
+
view.scanned++;
|
|
978
|
+
seen.add(path);
|
|
979
|
+
if (generatedFile(path)) {
|
|
980
|
+
skip('generated_file');
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
if (!supported.has(extname(path).toLowerCase())) {
|
|
984
|
+
skip('unsupported_type');
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
const stat = await lstat(path);
|
|
988
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
989
|
+
skip('changed_path');
|
|
990
|
+
complete = false;
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
files.push({ path, size: stat.size, mtime: stat.mtimeMs, unit: directory.project ?? (directory.depth === 0 ? view.path : join(view.path, relative(view.path, directory.path).split(sep)[0])) });
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
if (directories.length || visited >= 20000) {
|
|
998
|
+
complete = false;
|
|
999
|
+
skip('metadata_limit');
|
|
1000
|
+
}
|
|
1001
|
+
// Reconcile only after a complete metadata pass; unreadable/offline is never deletion.
|
|
1002
|
+
enter('reconcile');
|
|
1003
|
+
if (complete)
|
|
1004
|
+
for (const previous of [...record.files]) {
|
|
1005
|
+
if (seen.has(previous.path))
|
|
1006
|
+
continue;
|
|
1007
|
+
signal.throwIfAborted();
|
|
1008
|
+
await this.#removeFile(record, previous);
|
|
1009
|
+
}
|
|
1010
|
+
enter('knowledge_list');
|
|
1011
|
+
const known = new Map((await this.#options.knowledge.listSources()).map(item => [item.locator, item]));
|
|
1012
|
+
let bytes = 0;
|
|
1013
|
+
const counts = new Map();
|
|
1014
|
+
const selected = files.sort((a, b) => Number(overviewDocument(b.path)) - Number(overviewDocument(a.path)) || Number(representativeDocument(b.path)) - Number(representativeDocument(a.path)) || relative(a.unit, a.path).split(sep).length - relative(b.unit, b.path).split(sep).length || b.mtime - a.mtime || a.path.localeCompare(b.path)).filter(file => {
|
|
1015
|
+
const count = (counts.get(file.unit) ?? 0) + 1;
|
|
1016
|
+
counts.set(file.unit, count);
|
|
1017
|
+
// ponytail: Git overview reads eight documents; task-directed retrieval owns deeper investigation.
|
|
1018
|
+
if (projects.has(file.unit) && count > 8) {
|
|
1019
|
+
skip('project_budget');
|
|
1020
|
+
return false;
|
|
1021
|
+
}
|
|
1022
|
+
return true;
|
|
1023
|
+
});
|
|
1024
|
+
const selectedPaths = new Set(selected.map(file => file.path));
|
|
1025
|
+
observationPaths = selectedPaths;
|
|
1026
|
+
const trackedByPath = new Map(record.files.map(file => [file.path, file]));
|
|
1027
|
+
let rechecks = 0;
|
|
1028
|
+
// Budgeting must not keep a changed, no-longer-selected version authoritative.
|
|
1029
|
+
for (const file of files) {
|
|
1030
|
+
const previous = trackedByPath.get(file.path);
|
|
1031
|
+
if (previous && !selectedPaths.has(file.path) && (previous.mtime !== file.mtime || previous.size !== file.size)) {
|
|
1032
|
+
signal.throwIfAborted();
|
|
1033
|
+
previous.valid = false;
|
|
1034
|
+
await this.#save();
|
|
1035
|
+
await this.#removeFile(record, previous);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
for (const file of balanced(selected, view.path)) {
|
|
1039
|
+
enter('recheck');
|
|
1040
|
+
signal.throwIfAborted();
|
|
1041
|
+
const previous = trackedByPath.get(file.path);
|
|
1042
|
+
if (previous)
|
|
1043
|
+
previous.unit = file.unit;
|
|
1044
|
+
if (previous && view.scope === 'directory') {
|
|
1045
|
+
if (previous.mtime !== file.mtime || previous.size !== file.size) {
|
|
1046
|
+
delete previous.recheck_attempts;
|
|
1047
|
+
delete previous.recheck_eligible_at;
|
|
1048
|
+
delete previous.recheck_terminal;
|
|
1049
|
+
}
|
|
1050
|
+
else {
|
|
1051
|
+
const exhausted = (previous.recheck_attempts ?? 0) > 5;
|
|
1052
|
+
const eligibleAt = previous.recheck_eligible_at ?? (exhausted ? (previous.checked_at ?? 0) + 24 * 60 * 60_000 : 0);
|
|
1053
|
+
if (previous.recheck_terminal || eligibleAt > Date.now())
|
|
1054
|
+
continue;
|
|
1055
|
+
if (exhausted) {
|
|
1056
|
+
// Exhausted transient gaps get one durable daily reconciliation attempt.
|
|
1057
|
+
// Persist before I/O so a failed or interrupted attempt cannot hot-loop.
|
|
1058
|
+
previous.recheck_eligible_at = Date.now() + 24 * 60 * 60_000;
|
|
1059
|
+
await this.#save();
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
const discardStaleIndex = async () => { if (previous?.owned) {
|
|
1064
|
+
await this.#options.knowledge.handle('knowledge.remove', { id: previous.id });
|
|
1065
|
+
known.delete(file.path);
|
|
1066
|
+
} };
|
|
1067
|
+
if (previous?.valid && known.has(file.path) && (!representativeDocument(file.path) || previous.excerpt !== null)) {
|
|
1068
|
+
const sameMetadata = previous.mtime === file.mtime && previous.size === file.size;
|
|
1069
|
+
if (sameMetadata && ((previous.checked_at ?? 0) + (this.#options.contentRecheckMs ?? 300_000) > Date.now() || rechecks++ >= 4)) {
|
|
1070
|
+
settlePending(record, file.path);
|
|
1071
|
+
continue;
|
|
1072
|
+
}
|
|
1073
|
+
let recheckError;
|
|
1074
|
+
const checked = await readKnowledgeFile(file.path, signal, view.path).catch(error => { recheckError = error; return null; });
|
|
1075
|
+
signal.throwIfAborted();
|
|
1076
|
+
const terminal = recheckError instanceof KnowledgeDocumentFailure && ['sensitive_content', 'path_denied', 'unsupported_mime', 'invalid_file', 'file_too_large', 'empty_text', 'invalid_text', 'parse_failed', 'parse_timeout'].includes(recheckError.code);
|
|
1077
|
+
if (sameMetadata && checked === null && !terminal) {
|
|
1078
|
+
settlePending(record, file.path);
|
|
1079
|
+
const attempts = record.walk ? file.attempts ?? 0 : previous.recheck_attempts ?? 0;
|
|
1080
|
+
if (attempts >= 5) {
|
|
1081
|
+
previous.valid = false;
|
|
1082
|
+
await this.#save();
|
|
1083
|
+
await this.#invalidateFile(previous);
|
|
1084
|
+
await discardStaleIndex();
|
|
1085
|
+
skip('read_failed');
|
|
1086
|
+
currentReadFailure = true;
|
|
1087
|
+
if (view.failures.length < 50)
|
|
1088
|
+
view.failures.push({ path: relative(view.path, file.path), code: errorCode(recheckError) });
|
|
1089
|
+
if (!record.walk) {
|
|
1090
|
+
previous.recheck_attempts = attempts + 1;
|
|
1091
|
+
previous.recheck_eligible_at = Date.now() + 24 * 60 * 60_000;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
else if (record.walk)
|
|
1095
|
+
deferPending(record, file, 'retry', Date.now() + 30_000);
|
|
1096
|
+
else {
|
|
1097
|
+
previous.recheck_attempts = attempts + 1;
|
|
1098
|
+
previous.recheck_eligible_at = Date.now() + 30_000;
|
|
1099
|
+
}
|
|
1100
|
+
await this.#save();
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
if (checked?.fingerprint === previous.fingerprint) {
|
|
1104
|
+
previous.size = file.size;
|
|
1105
|
+
previous.mtime = file.mtime;
|
|
1106
|
+
previous.checked_at = Date.now();
|
|
1107
|
+
delete previous.recheck_attempts;
|
|
1108
|
+
delete previous.recheck_eligible_at;
|
|
1109
|
+
settlePending(record, file.path);
|
|
1110
|
+
await this.#save();
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
if (previous?.valid) {
|
|
1115
|
+
previous.valid = false;
|
|
1116
|
+
await this.#save();
|
|
1117
|
+
}
|
|
1118
|
+
if (previous) {
|
|
1119
|
+
// Retry propagation after interruption before accepting a replacement version.
|
|
1120
|
+
await this.#invalidateFile(previous);
|
|
1121
|
+
// The owned knowledge index remains until a replacement is committed.
|
|
1122
|
+
}
|
|
1123
|
+
if (file.size > 10 * 1024 * 1024 || file.size === 0) {
|
|
1124
|
+
await discardStaleIndex();
|
|
1125
|
+
skip('file_size');
|
|
1126
|
+
settlePending(record, file.path);
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
if (file.size > view.max_bytes) {
|
|
1130
|
+
await discardStaleIndex();
|
|
1131
|
+
skip('body_budget');
|
|
1132
|
+
settlePending(record, file.path);
|
|
1133
|
+
continue;
|
|
1134
|
+
}
|
|
1135
|
+
if (view.read >= view.max_files || bytes + file.size > view.max_bytes) {
|
|
1136
|
+
await discardStaleIndex();
|
|
1137
|
+
skip('body_budget');
|
|
1138
|
+
deferPending(record, file, 'body_budget', Date.now() + 60_000);
|
|
1139
|
+
continue;
|
|
1140
|
+
}
|
|
1141
|
+
if (record.files.length >= 20000 && !previous) {
|
|
1142
|
+
skip('index_limit');
|
|
1143
|
+
settlePending(record, file.path);
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
try {
|
|
1147
|
+
enter('ingest');
|
|
1148
|
+
if (await realpath(file.path) !== file.path) {
|
|
1149
|
+
await discardStaleIndex();
|
|
1150
|
+
skip('changed_path');
|
|
1151
|
+
settlePending(record, file.path);
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
record.pending = { path: file.path, size: file.size, mtime: file.mtime, owned: previous?.owned ?? !known.has(file.path), previous_updated_at: known.get(file.path)?.updated_at ?? null };
|
|
1155
|
+
await this.#timed('ingest_save_pending', () => this.#save());
|
|
1156
|
+
const result = await this.#timed('ingest_sync_file', () => this.#options.knowledge.syncFile(file.path, view.path, signal, previous?.id, record.processing_consent, this.#lifecycle(record).signal));
|
|
1157
|
+
const tracked = { path: file.path, unit: file.unit, size: file.size, mtime: file.mtime, id: result.id, fingerprint: result.fingerprint, checked_at: Date.now(), owned: previous?.owned ?? !known.has(file.path), valid: true, excerpt: result.excerpt, observed: false, observation_ref: result.evidence_ids?.length ? `knowledge:${result.id}` : randomUUID(), ...(result.evidence_ids?.length ? { evidence_ids: result.evidence_ids } : {}) };
|
|
1158
|
+
record.files = record.files.filter(old => old.path !== file.path);
|
|
1159
|
+
record.files.push(tracked);
|
|
1160
|
+
trackedByPath.set(file.path, tracked);
|
|
1161
|
+
record.pending = null;
|
|
1162
|
+
settlePending(record, file.path);
|
|
1163
|
+
bytes += file.size;
|
|
1164
|
+
view.read++;
|
|
1165
|
+
await this.#timed('ingest_save_tracked', () => this.#save());
|
|
1166
|
+
}
|
|
1167
|
+
catch (error) {
|
|
1168
|
+
await this.#recoverPending(record);
|
|
1169
|
+
signal.throwIfAborted();
|
|
1170
|
+
settlePending(record, file.path);
|
|
1171
|
+
const code = errorCode(error);
|
|
1172
|
+
skip(code === 'index_capacity' ? 'index_capacity' : 'read_failed');
|
|
1173
|
+
currentReadFailure = true;
|
|
1174
|
+
if (view.failures.length < 50)
|
|
1175
|
+
view.failures.push({ path: relative(view.path, file.path), code });
|
|
1176
|
+
if (previous && view.scope === 'directory' && ['screening_rejected', 'unsupported_file'].includes(code)) {
|
|
1177
|
+
previous.recheck_terminal = true;
|
|
1178
|
+
previous.size = file.size;
|
|
1179
|
+
previous.mtime = file.mtime;
|
|
1180
|
+
await this.#save();
|
|
1181
|
+
}
|
|
1182
|
+
if (['screening_rejected', 'unsupported_file'].includes(code) || (file.attempts ?? 0) >= 5)
|
|
1183
|
+
await discardStaleIndex();
|
|
1184
|
+
if (record.walk && ['knowledge_busy', 'source_busy', 'ingest_failed', 'source_unavailable', 'file_changed', 'file_unavailable', 'embedding_failed', 'store_failed'].includes(code) && (file.attempts ?? 0) < 5) {
|
|
1185
|
+
const attempts = (file.attempts ?? 0) + 1;
|
|
1186
|
+
deferPending(record, file, 'retry', Date.now() + Math.min(6 * 60 * 60_000, 30_000 * 2 ** attempts));
|
|
1187
|
+
}
|
|
1188
|
+
if (code === 'knowledge_busy')
|
|
1189
|
+
break;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
signal.throwIfAborted();
|
|
1193
|
+
enter('health_update');
|
|
1194
|
+
if (view.state !== 'paused' && view.state !== 'disconnected')
|
|
1195
|
+
view.state = 'connected';
|
|
1196
|
+
const cleanupPending = view.scope === 'computer' && record.files.some(file => isComputerExcludedPath(view, file.path));
|
|
1197
|
+
const partial = cleanupPending || [record.walk?.queue.length, record.walk?.pending.length, record.walk?.deferred.length].some(count => !!count) || !!record.walk?.ledger.some(item => item.status === 'partial') || Object.entries(view.reasons).some(([reason, count]) => count > 0 && ['body_budget', 'index_limit', 'index_capacity', 'metadata_limit', 'project_metadata_limit', 'depth_limit', 'directory_capacity'].includes(reason));
|
|
1198
|
+
view.health = partial || currentReadFailure || currentCleanupFailure ? 'degraded' : 'healthy';
|
|
1199
|
+
view.coverage = partial || currentReadFailure || currentCleanupFailure ? 'partial' : 'complete';
|
|
1200
|
+
view.last_sync = new Date().toISOString();
|
|
1201
|
+
// Scan statistics belong in source settings, not in the user's memory.
|
|
1202
|
+
enter('on_invalidate');
|
|
1203
|
+
if (record.observation) {
|
|
1204
|
+
await this.#options.onInvalidate?.(view.id);
|
|
1205
|
+
record.observation = '';
|
|
1206
|
+
await this.#save();
|
|
1207
|
+
}
|
|
1208
|
+
enter('on_change');
|
|
1209
|
+
await this.#options.onChange?.(false);
|
|
1210
|
+
enter('observe');
|
|
1211
|
+
for (const file of balanced(record.files.filter(file => file.valid && !file.observed && !!file.excerpt && representativeDocument(file.path) && (view.scope === 'computer' || observationPaths.has(file.path))), view.path)
|
|
1212
|
+
.filter(file => (file.observe_retry_at ?? 0) <= Date.now()).slice(0, 8)) {
|
|
1213
|
+
signal.throwIfAborted();
|
|
1214
|
+
if (file.observed || !file.excerpt || !this.#options.onObserve)
|
|
1215
|
+
continue;
|
|
1216
|
+
if ((file.observe_retry_at ?? 0) > Date.now()) {
|
|
1217
|
+
currentObserveFailure = true;
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
if (!file.observation_ref) {
|
|
1221
|
+
file.observation_ref = randomUUID();
|
|
1222
|
+
await this.#save();
|
|
1223
|
+
}
|
|
1224
|
+
const document = relative(view.path, file.path), project = dirname(document) === '.' ? basename(view.path) : dirname(document);
|
|
1225
|
+
const context = `文档 ${basename(view.path)}/${document}`.slice(0, 100) + '(资料摘录;作者与当前承诺未确认):';
|
|
1226
|
+
try {
|
|
1227
|
+
await this.#options.onObserve({ source_ref: { type: 'file', ref: file.observation_ref, observed_at: view.last_sync },
|
|
1228
|
+
...(record.processing_consent ? { processing_consent: record.processing_consent } : {}), content: context + file.excerpt.slice(0, 500 - context.length), topic: project.slice(0, 80), ...(file.evidence_ids ? { evidence_ids: file.evidence_ids } : {}) });
|
|
1229
|
+
}
|
|
1230
|
+
catch (error) {
|
|
1231
|
+
const attempts = (file.observe_attempts ?? 0) + 1, base = Math.max(1, this.#options.observationRetryMs ?? 30_000);
|
|
1232
|
+
file.observe_attempts = attempts;
|
|
1233
|
+
file.observe_retry_at = Date.now() + Math.min(6 * 60 * 60_000, base * 2 ** Math.min(attempts - 1, 10));
|
|
1234
|
+
file.observe_error = errorCode(error);
|
|
1235
|
+
currentObserveFailure = true;
|
|
1236
|
+
if (view.failures.length < 50)
|
|
1237
|
+
view.failures.push({ path: relative(view.path, file.path), code: file.observe_error, stage: 'observe' });
|
|
1238
|
+
await this.#save();
|
|
1239
|
+
continue;
|
|
1240
|
+
}
|
|
1241
|
+
file.observed = true;
|
|
1242
|
+
delete file.observe_attempts;
|
|
1243
|
+
delete file.observe_retry_at;
|
|
1244
|
+
delete file.observe_error;
|
|
1245
|
+
await this.#save();
|
|
1246
|
+
}
|
|
1247
|
+
if (currentObserveFailure) {
|
|
1248
|
+
view.health = 'degraded';
|
|
1249
|
+
view.coverage = 'partial';
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
catch (error) {
|
|
1253
|
+
if (!signal.aborted) {
|
|
1254
|
+
view.state = 'error';
|
|
1255
|
+
view.health = 'error';
|
|
1256
|
+
view.coverage = 'partial';
|
|
1257
|
+
view.failures.splice(0, Math.max(0, view.failures.length - 49));
|
|
1258
|
+
view.failures.push({ path: '', code: errorCode(error), stage });
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
view.indexed = record.files.filter(f => f.valid).length;
|
|
1262
|
+
const observationPending = !!this.#options.onObserve && record.files.some(f => f.valid && !f.observed && f.excerpt && representativeDocument(f.path) && (view.scope === 'computer' || observationPaths.has(f.path)));
|
|
1263
|
+
const cleanupPending = view.scope === 'computer' && record.files.some(file => isComputerExcludedPath(view, file.path));
|
|
1264
|
+
if (record.walk) {
|
|
1265
|
+
view.scan_pending = !!(record.walk.queue.length || record.walk.pending.length || record.walk.deferred.length || record.walk.ledger.some(item => item.status === 'partial') || observationPending || cleanupPending);
|
|
1266
|
+
if (!view.scan_pending && view.scope !== 'computer')
|
|
1267
|
+
record.walk = null;
|
|
1268
|
+
}
|
|
1269
|
+
else
|
|
1270
|
+
view.scan_pending = observationPending;
|
|
1271
|
+
enter('finalize');
|
|
1272
|
+
await this.#save();
|
|
1273
|
+
enter('on_change_final');
|
|
1274
|
+
try {
|
|
1275
|
+
await this.#options.onChange?.(beforeEvidence !== record.files.filter(file => file.valid).map(refFor).sort().join() || beforeObservation !== record.observation);
|
|
1276
|
+
}
|
|
1277
|
+
catch (error) {
|
|
1278
|
+
view.failures.splice(0, Math.max(0, view.failures.length - 49));
|
|
1279
|
+
view.failures.push({ path: '', code: errorCode(error), stage });
|
|
1280
|
+
await this.#save();
|
|
1281
|
+
throw error;
|
|
1282
|
+
}
|
|
1283
|
+
finally {
|
|
1284
|
+
enter(stage);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
async #recoverPending(record) {
|
|
1288
|
+
const pending = record.pending;
|
|
1289
|
+
if (!pending)
|
|
1290
|
+
return;
|
|
1291
|
+
const indexed = (await this.#options.knowledge.listSources()).filter(item => item.locator === pending.path)
|
|
1292
|
+
.sort((a, b) => b.updated_at - a.updated_at)[0];
|
|
1293
|
+
if (indexed && indexed.updated_at !== pending.previous_updated_at) {
|
|
1294
|
+
const previous = record.files.find(item => item.path === pending.path);
|
|
1295
|
+
if (previous && previous.fingerprint !== indexed.fingerprint) {
|
|
1296
|
+
await this.#invalidateFile(previous);
|
|
1297
|
+
}
|
|
1298
|
+
if (previous && previous.id !== indexed.id)
|
|
1299
|
+
await this.#options.knowledge.handle('knowledge.remove', { id: previous.id });
|
|
1300
|
+
record.files = record.files.filter(item => item.path !== pending.path);
|
|
1301
|
+
record.files.push({ path: pending.path, size: pending.size, mtime: pending.mtime, owned: pending.owned, id: indexed.id, fingerprint: indexed.fingerprint, valid: true, excerpt: null, observed: false, observation_ref: randomUUID() });
|
|
1302
|
+
}
|
|
1303
|
+
record.pending = null;
|
|
1304
|
+
await this.#save();
|
|
1305
|
+
}
|
|
1306
|
+
async #invalidateFile(file) {
|
|
1307
|
+
for (const ref of new Set([refFor(file), file.id, ...(file.observation_ref ? [file.observation_ref] : [])]))
|
|
1308
|
+
await this.#options.onInvalidate?.(ref);
|
|
1309
|
+
}
|
|
1310
|
+
async #cleanupExcludedFiles(record, signal) {
|
|
1311
|
+
const excluded = record.files.filter(file => isComputerExcludedPath(record.view, file.path));
|
|
1312
|
+
if (!excluded.length)
|
|
1313
|
+
return false;
|
|
1314
|
+
// Remove all legacy hidden entries from source context before any expensive
|
|
1315
|
+
// memory or knowledge cleanup. Invalid records are the durable retry queue.
|
|
1316
|
+
if (excluded.some(file => file.valid)) {
|
|
1317
|
+
for (const file of excluded)
|
|
1318
|
+
file.valid = false;
|
|
1319
|
+
await this.#save();
|
|
1320
|
+
}
|
|
1321
|
+
const refs = (files) => [...new Set(files.flatMap(file => [refFor(file), file.id, ...(file.observation_ref ? [file.observation_ref] : [])]))];
|
|
1322
|
+
const markFailure = (file, error) => {
|
|
1323
|
+
const attempts = (file.cleanup_attempts ?? 0) + 1;
|
|
1324
|
+
file.cleanup_attempts = attempts;
|
|
1325
|
+
file.cleanup_retry_at = Date.now() + Math.min(6 * 60 * 60_000, 30_000 * 2 ** Math.min(attempts - 1, 8));
|
|
1326
|
+
const path = relative(record.view.path, file.path), code = errorCode(error);
|
|
1327
|
+
const prior = record.view.failures.findIndex(item => item.path === path && item.stage === 'cleanup');
|
|
1328
|
+
if (prior >= 0)
|
|
1329
|
+
record.view.failures[prior] = { path, code, stage: 'cleanup' };
|
|
1330
|
+
else {
|
|
1331
|
+
record.view.failures.splice(0, Math.max(0, record.view.failures.length - 49));
|
|
1332
|
+
record.view.failures.push({ path, code, stage: 'cleanup' });
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
const removeKnowledge = async (file) => {
|
|
1336
|
+
signal.throwIfAborted();
|
|
1337
|
+
if (file.owned)
|
|
1338
|
+
await this.#options.knowledge.handle('knowledge.remove', { id: file.id });
|
|
1339
|
+
record.files = record.files.filter(item => item !== file);
|
|
1340
|
+
};
|
|
1341
|
+
// Mark legacy entries hidden once and persist that fence. This includes
|
|
1342
|
+
// already-invalid entries recovered after restart, without recloning every
|
|
1343
|
+
// reference into the suggestion host on every cleanup turn.
|
|
1344
|
+
const needsHide = excluded.filter(file => !file.cleanup_hidden && (file.cleanup_retry_at ?? 0) <= Date.now());
|
|
1345
|
+
if (needsHide.length) {
|
|
1346
|
+
try {
|
|
1347
|
+
await this.#options.onHideEvidenceMany?.(refs(needsHide));
|
|
1348
|
+
for (const file of needsHide)
|
|
1349
|
+
file.cleanup_hidden = true;
|
|
1350
|
+
}
|
|
1351
|
+
catch (batchError) {
|
|
1352
|
+
if (signal.aborted)
|
|
1353
|
+
signal.throwIfAborted();
|
|
1354
|
+
for (const file of needsHide) {
|
|
1355
|
+
try {
|
|
1356
|
+
await this.#options.onHideEvidenceMany?.(refs([file]));
|
|
1357
|
+
file.cleanup_hidden = true;
|
|
1358
|
+
}
|
|
1359
|
+
catch (error) {
|
|
1360
|
+
if (signal.aborted)
|
|
1361
|
+
signal.throwIfAborted();
|
|
1362
|
+
markFailure(file, error ?? batchError);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
await this.#save();
|
|
1367
|
+
}
|
|
1368
|
+
const now = Date.now(), eligible = excluded.filter(file => file.cleanup_hidden && (file.cleanup_retry_at ?? 0) <= now);
|
|
1369
|
+
if (!eligible.length)
|
|
1370
|
+
return true;
|
|
1371
|
+
const prior = record.cleanup_cursor ? eligible.findIndex(file => file.id === record.cleanup_cursor) : -1;
|
|
1372
|
+
const start = prior >= 0 ? prior : 0, count = Math.min(8, eligible.length);
|
|
1373
|
+
const chunk = Array.from({ length: count }, (_, offset) => eligible[(start + offset) % eligible.length]);
|
|
1374
|
+
// Persist the next stable file before side effects. A restart after a crash
|
|
1375
|
+
// resumes after this batch; failed files remain invalid and retryable.
|
|
1376
|
+
record.cleanup_cursor = eligible[(start + count) % eligible.length]?.id ?? null;
|
|
1377
|
+
await this.#save();
|
|
1378
|
+
let batchInvalidated = false;
|
|
1379
|
+
try {
|
|
1380
|
+
if (this.#options.onInvalidateMany) {
|
|
1381
|
+
await this.#options.onInvalidateMany(refs(chunk));
|
|
1382
|
+
batchInvalidated = true;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
catch {
|
|
1386
|
+
if (signal.aborted)
|
|
1387
|
+
signal.throwIfAborted();
|
|
1388
|
+
// A single malformed/stale ref must not pin every other file in the
|
|
1389
|
+
// batch. Retry invalidation and deletion one file at a time on this path.
|
|
1390
|
+
for (const file of chunk) {
|
|
1391
|
+
try {
|
|
1392
|
+
signal.throwIfAborted();
|
|
1393
|
+
await this.#invalidateFile(file);
|
|
1394
|
+
await removeKnowledge(file);
|
|
1395
|
+
delete file.cleanup_attempts;
|
|
1396
|
+
delete file.cleanup_retry_at;
|
|
1397
|
+
}
|
|
1398
|
+
catch (fileError) {
|
|
1399
|
+
if (signal.aborted)
|
|
1400
|
+
signal.throwIfAborted();
|
|
1401
|
+
markFailure(file, fileError);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
await this.#save();
|
|
1405
|
+
return record.files.some(file => isComputerExcludedPath(record.view, file.path));
|
|
1406
|
+
}
|
|
1407
|
+
let failed = false;
|
|
1408
|
+
for (const file of chunk) {
|
|
1409
|
+
try {
|
|
1410
|
+
if (!batchInvalidated)
|
|
1411
|
+
await this.#invalidateFile(file);
|
|
1412
|
+
await removeKnowledge(file);
|
|
1413
|
+
delete file.cleanup_attempts;
|
|
1414
|
+
delete file.cleanup_retry_at;
|
|
1415
|
+
}
|
|
1416
|
+
catch (error) {
|
|
1417
|
+
if (signal.aborted)
|
|
1418
|
+
signal.throwIfAborted();
|
|
1419
|
+
markFailure(file, error);
|
|
1420
|
+
failed = true;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
await this.#save();
|
|
1424
|
+
return failed || record.files.some(file => isComputerExcludedPath(record.view, file.path));
|
|
1425
|
+
}
|
|
1426
|
+
async #removeFile(record, file) {
|
|
1427
|
+
await this.#invalidateFile(file);
|
|
1428
|
+
if (file.owned)
|
|
1429
|
+
await this.#options.knowledge.handle('knowledge.remove', { id: file.id });
|
|
1430
|
+
record.files = record.files.filter(item => item.id !== file.id);
|
|
1431
|
+
await this.#save();
|
|
1432
|
+
}
|
|
1433
|
+
async #delete(record) {
|
|
1434
|
+
record.deleting = true;
|
|
1435
|
+
record.view.state = 'disconnected';
|
|
1436
|
+
await this.#save();
|
|
1437
|
+
for (const file of [...record.files])
|
|
1438
|
+
await this.#removeFile(record, file);
|
|
1439
|
+
await this.#options.onInvalidate?.(record.view.id);
|
|
1440
|
+
this.#records = this.#records.filter(item => item !== record);
|
|
1441
|
+
await this.#save();
|
|
1442
|
+
await this.#options.onChange?.(false);
|
|
1443
|
+
}
|
|
1444
|
+
#save() {
|
|
1445
|
+
for (const record of this.#records)
|
|
1446
|
+
record.view.failures = record.view.failures.slice(-50);
|
|
1447
|
+
const data = JSON.stringify({ version: 1, sources: this.#records });
|
|
1448
|
+
if (Buffer.byteLength(data) > 32 * 1024 * 1024)
|
|
1449
|
+
return Promise.reject(new Error('sources_state_too_large'));
|
|
1450
|
+
const write = this.#writes.then(async () => {
|
|
1451
|
+
const temporary = join(dirname(this.#path), `.sources-${randomUUID()}.tmp`);
|
|
1452
|
+
try {
|
|
1453
|
+
await writeFile(temporary, data, { mode: 0o600, flag: 'wx' });
|
|
1454
|
+
const file = await open(temporary, 'r+');
|
|
1455
|
+
try {
|
|
1456
|
+
await file.sync();
|
|
1457
|
+
}
|
|
1458
|
+
finally {
|
|
1459
|
+
await file.close();
|
|
1460
|
+
}
|
|
1461
|
+
await rename(temporary, this.#path);
|
|
1462
|
+
if (process.platform !== 'win32') {
|
|
1463
|
+
const directory = await open(dirname(this.#path), 'r');
|
|
1464
|
+
try {
|
|
1465
|
+
await directory.sync();
|
|
1466
|
+
}
|
|
1467
|
+
finally {
|
|
1468
|
+
await directory.close();
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
finally {
|
|
1473
|
+
await rm(temporary, { force: true });
|
|
1474
|
+
}
|
|
1475
|
+
});
|
|
1476
|
+
this.#writes = write.catch(() => undefined);
|
|
1477
|
+
return write;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
function within(root, path) {
|
|
1481
|
+
const child = relative(root, path);
|
|
1482
|
+
return child === '' || (child !== '..' && !child.startsWith('../') && !child.startsWith('..\\') && !isAbsolute(child));
|
|
1483
|
+
}
|
|
1484
|
+
//# sourceMappingURL=sources.js.map
|