somora 2026.930.1
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 +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Persistent scheduler state for dream workers.
|
|
2
|
+
//
|
|
3
|
+
// Before this module existed, `LucidWorker` and `DeepWorker` used
|
|
4
|
+
// `setInterval(intervalMs)` from worker-start, so the first auto-fire
|
|
5
|
+
// happened only after one full interval from server boot. Restart-
|
|
6
|
+
// starvation: any deployment that restarts more often than
|
|
7
|
+
// `wiki.lucid.intervalDays` (7d) or `wiki.deep.intervalHours` (12h)
|
|
8
|
+
// could go indefinitely without an automatic run.
|
|
9
|
+
//
|
|
10
|
+
// Fix: every fire writes `lastCompletedAt` / `lastFailedAt` to disk;
|
|
11
|
+
// every start reads it and schedules `setTimeout(nextDueAt - now)`
|
|
12
|
+
// with `nextDueAt = lastRelevantRunAt + intervalMs`. If due (or
|
|
13
|
+
// overdue) at startup, fire after a short grace window so MCP children
|
|
14
|
+
// and indexes can warm before the worker does heavy LLM I/O.
|
|
15
|
+
//
|
|
16
|
+
// File layout:
|
|
17
|
+
// ~/.somora/dream-state/lucid.json
|
|
18
|
+
// ~/.somora/dream-state/deep.json
|
|
19
|
+
//
|
|
20
|
+
// Shape:
|
|
21
|
+
// { lastStartedAt, lastCompletedAt, lastFailedAt, lastStatus }
|
|
22
|
+
//
|
|
23
|
+
// All fields are unix-ms timestamps or null. Missing file is treated
|
|
24
|
+
// as "never run" — the worker bootstraps with lastCompletedAt = now
|
|
25
|
+
// so a fresh install does not immediately fire a heavy LLM consolidation
|
|
26
|
+
// during boot.
|
|
27
|
+
|
|
28
|
+
import { promises as fs } from 'node:fs';
|
|
29
|
+
import { join } from 'node:path';
|
|
30
|
+
import { SOMORA_HOME_DIR } from '../server/logger.ts';
|
|
31
|
+
|
|
32
|
+
export interface SchedulerState {
|
|
33
|
+
lastStartedAt: number | null;
|
|
34
|
+
lastCompletedAt: number | null;
|
|
35
|
+
lastFailedAt: number | null;
|
|
36
|
+
lastStatus: 'completed' | 'failed' | null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const STATE_DIR = join(SOMORA_HOME_DIR, 'dream-state');
|
|
40
|
+
|
|
41
|
+
function statePath(worker: 'lucid' | 'deep'): string {
|
|
42
|
+
return join(STATE_DIR, `${worker}.json`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const EMPTY: SchedulerState = {
|
|
46
|
+
lastStartedAt: null,
|
|
47
|
+
lastCompletedAt: null,
|
|
48
|
+
lastFailedAt: null,
|
|
49
|
+
lastStatus: null,
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export async function readSchedulerState(
|
|
53
|
+
worker: 'lucid' | 'deep',
|
|
54
|
+
): Promise<SchedulerState> {
|
|
55
|
+
try {
|
|
56
|
+
const raw = await fs.readFile(statePath(worker), 'utf8');
|
|
57
|
+
const parsed = JSON.parse(raw) as Partial<SchedulerState>;
|
|
58
|
+
return {
|
|
59
|
+
lastStartedAt: typeof parsed.lastStartedAt === 'number' ? parsed.lastStartedAt : null,
|
|
60
|
+
lastCompletedAt: typeof parsed.lastCompletedAt === 'number' ? parsed.lastCompletedAt : null,
|
|
61
|
+
lastFailedAt: typeof parsed.lastFailedAt === 'number' ? parsed.lastFailedAt : null,
|
|
62
|
+
lastStatus:
|
|
63
|
+
parsed.lastStatus === 'completed' || parsed.lastStatus === 'failed'
|
|
64
|
+
? parsed.lastStatus
|
|
65
|
+
: null,
|
|
66
|
+
};
|
|
67
|
+
} catch {
|
|
68
|
+
return { ...EMPTY };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function writeSchedulerState(
|
|
73
|
+
worker: 'lucid' | 'deep',
|
|
74
|
+
state: SchedulerState,
|
|
75
|
+
): Promise<void> {
|
|
76
|
+
await fs.mkdir(STATE_DIR, { recursive: true });
|
|
77
|
+
const tmp = `${statePath(worker)}.tmp`;
|
|
78
|
+
await fs.writeFile(tmp, JSON.stringify(state, null, 2), 'utf8');
|
|
79
|
+
await fs.rename(tmp, statePath(worker));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The reference timestamp used for `nextDueAt` computation: the most
|
|
83
|
+
* recent run event (attempt or completion), whichever is latest.
|
|
84
|
+
*
|
|
85
|
+
* This must be the MAX, not a completed-first priority chain. On a
|
|
86
|
+
* failed run the worker records `lastFailedAt` (and `lastStartedAt`)
|
|
87
|
+
* but keeps the older `lastCompletedAt`; a completed-first anchor would
|
|
88
|
+
* resolve to that stale completion, `nextDelayMs` would read it as
|
|
89
|
+
* "overdue", and the heavy-LLM run would re-fire after only
|
|
90
|
+
* STARTUP_GRACE_MS — every ~60s, forever. Anchoring on the latest event
|
|
91
|
+
* instead spaces the retry after a failure by a full interval, and a
|
|
92
|
+
* worker that crashed mid-run (only `lastStartedAt`) still doesn't
|
|
93
|
+
* loop-fire on restart (Juni-Audit 2026-06). */
|
|
94
|
+
export function lastRelevantRunAt(state: SchedulerState): number | null {
|
|
95
|
+
const candidates = [
|
|
96
|
+
state.lastCompletedAt,
|
|
97
|
+
state.lastStartedAt,
|
|
98
|
+
state.lastFailedAt,
|
|
99
|
+
].filter((t): t is number => typeof t === 'number');
|
|
100
|
+
return candidates.length > 0 ? Math.max(...candidates) : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Pick the actual delay for the next scheduler firing.
|
|
104
|
+
*
|
|
105
|
+
* - First-ever start (no state): return `intervalMs` so a fresh
|
|
106
|
+
* install behaves like the pre-fix world — no surprise consolidation
|
|
107
|
+
* during the first server-boot.
|
|
108
|
+
* - State present, due now or overdue: return `STARTUP_GRACE_MS`
|
|
109
|
+
* instead of 0 so MCP children + indexes have time to warm.
|
|
110
|
+
* - State present, not yet due: return the remaining wait until
|
|
111
|
+
* `nextDueAt`.
|
|
112
|
+
*/
|
|
113
|
+
export const STARTUP_GRACE_MS = 60_000;
|
|
114
|
+
|
|
115
|
+
export function nextDelayMs(
|
|
116
|
+
state: SchedulerState,
|
|
117
|
+
intervalMs: number,
|
|
118
|
+
now: number = Date.now(),
|
|
119
|
+
): { delayMs: number; nextDueAt: number; reason: 'fresh' | 'overdue' | 'wait' } {
|
|
120
|
+
const last = lastRelevantRunAt(state);
|
|
121
|
+
if (last === null) {
|
|
122
|
+
return { delayMs: intervalMs, nextDueAt: now + intervalMs, reason: 'fresh' };
|
|
123
|
+
}
|
|
124
|
+
const nextDueAt = last + intervalMs;
|
|
125
|
+
if (nextDueAt <= now) {
|
|
126
|
+
return { delayMs: STARTUP_GRACE_MS, nextDueAt, reason: 'overdue' };
|
|
127
|
+
}
|
|
128
|
+
return { delayMs: nextDueAt - now, nextDueAt, reason: 'wait' };
|
|
129
|
+
}
|
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// Dream file storage. Layout under each agent's memory directory:
|
|
2
|
+
//
|
|
3
|
+
// ~/.somora/agents/<agent>/memory/.dreams/
|
|
4
|
+
// <id>.dream.running.md ← extraction in flight
|
|
5
|
+
// <id>.dream.paused.md ← extraction interrupted, will resume
|
|
6
|
+
// <id>.dream.failed.md ← extraction errored unrecoverably
|
|
7
|
+
// <id>.dream.md ← extraction completed, findings pending review
|
|
8
|
+
// ~/.somora/agents/<agent>/memory/.dreams/processed/
|
|
9
|
+
// <id>.dream.md ← all findings resolved; archived for audit
|
|
10
|
+
//
|
|
11
|
+
// Filename suffix = current status. Atomic-rename on transitions.
|
|
12
|
+
// Each file is self-contained: YAML frontmatter (DreamMeta) + Markdown body.
|
|
13
|
+
//
|
|
14
|
+
// Why dotfile dir: chokidar's watcher (memory/manager.ts) skips dot-prefixed
|
|
15
|
+
// components, so .dreams/ files don't end up in the memory recall index.
|
|
16
|
+
|
|
17
|
+
import { mkdir, readFile, readdir, rename, writeFile, unlink } from 'node:fs/promises';
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import { dirname, join } from 'node:path';
|
|
20
|
+
import matter from 'gray-matter';
|
|
21
|
+
import { logger } from '../server/logger.ts';
|
|
22
|
+
import type { DreamFile, DreamMeta, DreamStatus, Finding, FindingStatus } from './types.ts';
|
|
23
|
+
|
|
24
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
25
|
+
|
|
26
|
+
const STATUS_SUFFIX: Record<DreamStatus, string> = {
|
|
27
|
+
running: '.dream.running.md',
|
|
28
|
+
paused: '.dream.paused.md',
|
|
29
|
+
failed: '.dream.failed.md',
|
|
30
|
+
completed: '.dream.md',
|
|
31
|
+
processed: '.dream.md', // lives in processed/ subdir, suffix same
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function dreamsDir(agent: string): string {
|
|
35
|
+
return join(SOMORA_HOME, 'agents', agent, 'memory', '.dreams');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function processedDir(agent: string): string {
|
|
39
|
+
return join(dreamsDir(agent), 'processed');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function dreamFilePath(agent: string, id: string, status: DreamStatus): string {
|
|
43
|
+
const suffix = STATUS_SUFFIX[status];
|
|
44
|
+
return status === 'processed'
|
|
45
|
+
? join(processedDir(agent), `${id}${suffix}`)
|
|
46
|
+
: join(dreamsDir(agent), `${id}${suffix}`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function ensureDreamDirs(agent: string): Promise<void> {
|
|
50
|
+
await mkdir(processedDir(agent), { recursive: true });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Atomically write a DreamFile to its current-status path. Writes to
|
|
55
|
+
* `<path>.tmp` then renames; ensures readers never see a half-written
|
|
56
|
+
* file. Caller is responsible for the previous-status file's removal
|
|
57
|
+
* (see transitionDreamStatus).
|
|
58
|
+
*/
|
|
59
|
+
export async function writeDreamFile(
|
|
60
|
+
agent: string,
|
|
61
|
+
file: DreamFile,
|
|
62
|
+
): Promise<{ path: string }> {
|
|
63
|
+
await ensureDreamDirs(agent);
|
|
64
|
+
const path = dreamFilePath(agent, file.meta.id, file.meta.status);
|
|
65
|
+
// Per-call unique tmp so parallel writes to the same dream (e.g.
|
|
66
|
+
// a `dream_apply` flight + a status transition triggered by REM)
|
|
67
|
+
// don't race on a shared `<path>.tmp` and ENOENT each other.
|
|
68
|
+
// Audit 2026-05-16.
|
|
69
|
+
const tmp = `${path}.tmp.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}`;
|
|
70
|
+
const yaml = matter.stringify(file.body, file.meta as unknown as Record<string, unknown>);
|
|
71
|
+
await writeFile(tmp, yaml, 'utf8');
|
|
72
|
+
await rename(tmp, path);
|
|
73
|
+
return { path };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Read a dream file by id, scanning both the active .dreams/ dir and
|
|
78
|
+
* the processed/ subdir. Returns null if not found in any state.
|
|
79
|
+
*/
|
|
80
|
+
export async function readDreamById(agent: string, id: string): Promise<DreamFile | null> {
|
|
81
|
+
// Try each possible status — most likely first for the typical UI flow
|
|
82
|
+
// (completed when user reviews; running/paused/failed for diagnostics).
|
|
83
|
+
for (const status of ['completed', 'running', 'paused', 'failed', 'processed'] as const) {
|
|
84
|
+
const path = dreamFilePath(agent, id, status);
|
|
85
|
+
try {
|
|
86
|
+
const raw = await readFile(path, 'utf8');
|
|
87
|
+
const parsed = matter(raw);
|
|
88
|
+
const meta = parsed.data as unknown as DreamMeta;
|
|
89
|
+
// Defensive: trust the file's own status field, not the suffix
|
|
90
|
+
return { meta, body: parsed.content };
|
|
91
|
+
} catch (err) {
|
|
92
|
+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* List dreams for an agent. By default returns active (non-processed)
|
|
100
|
+
* dreams sorted oldest-first (so users naturally process them in order).
|
|
101
|
+
*/
|
|
102
|
+
export async function listDreams(
|
|
103
|
+
agent: string,
|
|
104
|
+
opts: { includeProcessed?: boolean } = {},
|
|
105
|
+
): Promise<DreamFile[]> {
|
|
106
|
+
await ensureDreamDirs(agent);
|
|
107
|
+
const out: DreamFile[] = [];
|
|
108
|
+
|
|
109
|
+
const scan = async (dir: string): Promise<void> => {
|
|
110
|
+
let entries: string[];
|
|
111
|
+
try {
|
|
112
|
+
entries = await readdir(dir);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return;
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
for (const name of entries) {
|
|
118
|
+
if (!name.endsWith('.md')) continue;
|
|
119
|
+
const path = join(dir, name);
|
|
120
|
+
try {
|
|
121
|
+
const raw = await readFile(path, 'utf8');
|
|
122
|
+
const parsed = matter(raw);
|
|
123
|
+
out.push({ meta: parsed.data as unknown as DreamMeta, body: parsed.content });
|
|
124
|
+
} catch (err) {
|
|
125
|
+
logger.warn({
|
|
126
|
+
msg: 'dream.read_failed',
|
|
127
|
+
agent,
|
|
128
|
+
path,
|
|
129
|
+
err: (err as Error).message,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
await scan(dreamsDir(agent));
|
|
136
|
+
if (opts.includeProcessed) await scan(processedDir(agent));
|
|
137
|
+
|
|
138
|
+
out.sort((a, b) => a.meta.created_at.localeCompare(b.meta.created_at));
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Transition a dream's status. Writes the file at the new path and
|
|
144
|
+
* removes the old. If the old file is missing (already moved or
|
|
145
|
+
* crash-recovered), proceed silently — idempotent.
|
|
146
|
+
*
|
|
147
|
+
* On status='processed' the file moves into the processed/ subdir.
|
|
148
|
+
*/
|
|
149
|
+
export async function transitionDreamStatus(
|
|
150
|
+
agent: string,
|
|
151
|
+
file: DreamFile,
|
|
152
|
+
newStatus: DreamStatus,
|
|
153
|
+
patches?: Partial<DreamMeta>,
|
|
154
|
+
): Promise<{ path: string }> {
|
|
155
|
+
const oldPath = dreamFilePath(agent, file.meta.id, file.meta.status);
|
|
156
|
+
const updated: DreamFile = {
|
|
157
|
+
meta: {
|
|
158
|
+
...file.meta,
|
|
159
|
+
...patches,
|
|
160
|
+
status: newStatus,
|
|
161
|
+
},
|
|
162
|
+
body: file.body,
|
|
163
|
+
};
|
|
164
|
+
const result = await writeDreamFile(agent, updated);
|
|
165
|
+
if (oldPath !== result.path) {
|
|
166
|
+
try {
|
|
167
|
+
await unlink(oldPath);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
170
|
+
logger.warn({
|
|
171
|
+
msg: 'dream.unlink_old_failed',
|
|
172
|
+
agent,
|
|
173
|
+
oldPath,
|
|
174
|
+
err: (err as Error).message,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Update a single finding's status (applied / dismissed). Re-checks
|
|
184
|
+
* whether all findings are now resolved; if so, transitions the dream
|
|
185
|
+
* to 'processed' (moves to processed/ dir).
|
|
186
|
+
*
|
|
187
|
+
* `note` (optional) is a free-text reason recorded on the finding —
|
|
188
|
+
* used by dream_dismiss so "manually applied elsewhere" is
|
|
189
|
+
* distinguishable from "content rejected" in the audit trail.
|
|
190
|
+
*/
|
|
191
|
+
export async function updateFindingStatus(
|
|
192
|
+
agent: string,
|
|
193
|
+
dreamId: string,
|
|
194
|
+
findingId: number,
|
|
195
|
+
newStatus: FindingStatus,
|
|
196
|
+
note?: string,
|
|
197
|
+
): Promise<{ dream: DreamFile; allResolved: boolean }> {
|
|
198
|
+
const file = await readDreamById(agent, dreamId);
|
|
199
|
+
if (!file) throw new Error(`dream '${dreamId}' not found`);
|
|
200
|
+
const finding = file.meta.findings.find((f) => f.id === findingId);
|
|
201
|
+
if (!finding) throw new Error(`finding ${findingId} not in dream '${dreamId}'`);
|
|
202
|
+
if (finding.status !== 'pending') {
|
|
203
|
+
throw new Error(`finding ${findingId} is already ${finding.status}, can't transition again`);
|
|
204
|
+
}
|
|
205
|
+
finding.status = newStatus;
|
|
206
|
+
finding.resolved_at = new Date().toISOString();
|
|
207
|
+
if (note && note.trim().length > 0) {
|
|
208
|
+
finding.resolution_note = note.trim();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const allResolved = file.meta.findings.every((f) => f.status !== 'pending');
|
|
212
|
+
if (allResolved && file.meta.status === 'completed') {
|
|
213
|
+
const result = await transitionDreamStatus(agent, file, 'processed', {
|
|
214
|
+
processed_at: new Date().toISOString(),
|
|
215
|
+
});
|
|
216
|
+
return { dream: { ...file, meta: { ...file.meta, status: 'processed' } }, allResolved: true };
|
|
217
|
+
}
|
|
218
|
+
await writeDreamFile(agent, file);
|
|
219
|
+
return { dream: file, allResolved: false };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Bulk-dismiss every still-pending finding in a dream (the "throw the
|
|
224
|
+
* whole dream out" path). Transitions the dream to processed.
|
|
225
|
+
*/
|
|
226
|
+
export async function dismissEntireDream(
|
|
227
|
+
agent: string,
|
|
228
|
+
dreamId: string,
|
|
229
|
+
note?: string,
|
|
230
|
+
finalStatus: FindingStatus = 'dismissed',
|
|
231
|
+
): Promise<{ dream: DreamFile; dismissedCount: number }> {
|
|
232
|
+
const file = await readDreamById(agent, dreamId);
|
|
233
|
+
if (!file) throw new Error(`dream '${dreamId}' not found`);
|
|
234
|
+
const now = new Date().toISOString();
|
|
235
|
+
const trimmedNote = note?.trim();
|
|
236
|
+
let dismissedCount = 0;
|
|
237
|
+
for (const f of file.meta.findings) {
|
|
238
|
+
if (f.status === 'pending') {
|
|
239
|
+
f.status = finalStatus;
|
|
240
|
+
f.resolved_at = now;
|
|
241
|
+
if (trimmedNote) f.resolution_note = trimmedNote;
|
|
242
|
+
dismissedCount++;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const result = await transitionDreamStatus(agent, file, 'processed', {
|
|
246
|
+
processed_at: now,
|
|
247
|
+
});
|
|
248
|
+
return {
|
|
249
|
+
dream: { ...file, meta: { ...file.meta, status: 'processed' } },
|
|
250
|
+
dismissedCount,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* One-shot housekeeping: any `completed`-status dreams whose findings
|
|
256
|
+
* array is empty get moved to processed/. They have nothing for the user
|
|
257
|
+
* to review or dismiss — without this, they would sit in the active
|
|
258
|
+
* .dreams/ dir forever. Run at server start, idempotent.
|
|
259
|
+
*/
|
|
260
|
+
export async function archiveEmptyCompletedDreams(agents: string[]): Promise<number> {
|
|
261
|
+
let moved = 0;
|
|
262
|
+
for (const agent of agents) {
|
|
263
|
+
const dir = dreamsDir(agent);
|
|
264
|
+
let entries: string[];
|
|
265
|
+
try {
|
|
266
|
+
entries = await readdir(dir);
|
|
267
|
+
} catch (err) {
|
|
268
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;
|
|
269
|
+
throw err;
|
|
270
|
+
}
|
|
271
|
+
for (const name of entries) {
|
|
272
|
+
// We only auto-archive completed dreams (.dream.md, no other suffix
|
|
273
|
+
// marker). running/paused/failed/processed dreams must stay where
|
|
274
|
+
// they are.
|
|
275
|
+
if (!name.endsWith('.dream.md')) continue;
|
|
276
|
+
const path = join(dir, name);
|
|
277
|
+
try {
|
|
278
|
+
const raw = await readFile(path, 'utf8');
|
|
279
|
+
const parsed = matter(raw);
|
|
280
|
+
const meta = parsed.data as unknown as DreamMeta;
|
|
281
|
+
if (meta.status !== 'completed') continue;
|
|
282
|
+
if (Array.isArray(meta.findings) && meta.findings.length > 0) continue;
|
|
283
|
+
// Empty completed → process.
|
|
284
|
+
await transitionDreamStatus(
|
|
285
|
+
agent,
|
|
286
|
+
{ meta, body: parsed.content },
|
|
287
|
+
'processed',
|
|
288
|
+
{ processed_at: new Date().toISOString() },
|
|
289
|
+
);
|
|
290
|
+
moved++;
|
|
291
|
+
} catch (err) {
|
|
292
|
+
logger.warn({
|
|
293
|
+
msg: 'dream.empty_archive_failed',
|
|
294
|
+
agent,
|
|
295
|
+
path,
|
|
296
|
+
err: (err as Error).message,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (moved > 0) {
|
|
302
|
+
logger.info({ msg: 'dream.empty_archived', count: moved, agents });
|
|
303
|
+
}
|
|
304
|
+
return moved;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Server-start housekeeping: when multiple paused dreams exist for the
|
|
309
|
+
* SAME source-session (a sign that resume cycles failed to clean up
|
|
310
|
+
* after themselves — see bug report 2026-05-05), keep only the newest
|
|
311
|
+
* paused per source-session and unlink the rest. The newest captures
|
|
312
|
+
* the most recent state; older ones are stale by-products of the bug
|
|
313
|
+
* that's fixed in resumeDream().
|
|
314
|
+
*
|
|
315
|
+
* Single-paused-per-source-session is the steady state going forward:
|
|
316
|
+
* resumeDream() now unlinks the old paused before kicking off the new
|
|
317
|
+
* run, so accumulation can't recur.
|
|
318
|
+
*
|
|
319
|
+
* Idempotent. No-op when each source-session has at most one paused.
|
|
320
|
+
* Runs alongside archiveEmptyCompletedDreams + recoverOrphanRunningDreams
|
|
321
|
+
* at server boot in src/server/index.ts.
|
|
322
|
+
*/
|
|
323
|
+
export async function consolidateStalePausedDreams(agents: string[]): Promise<number> {
|
|
324
|
+
let removed = 0;
|
|
325
|
+
for (const agent of agents) {
|
|
326
|
+
const all = await listDreams(agent);
|
|
327
|
+
const pausedBySession = new Map<string, DreamFile[]>();
|
|
328
|
+
for (const d of all) {
|
|
329
|
+
if (d.meta.status !== 'paused') continue;
|
|
330
|
+
const list = pausedBySession.get(d.meta.source_session) ?? [];
|
|
331
|
+
list.push(d);
|
|
332
|
+
pausedBySession.set(d.meta.source_session, list);
|
|
333
|
+
}
|
|
334
|
+
for (const [source, group] of pausedBySession) {
|
|
335
|
+
if (group.length <= 1) continue;
|
|
336
|
+
// Sort newest-first by id (ids are timestamp-prefixed → lexicographic
|
|
337
|
+
// = chronological). Keep [0], unlink the rest.
|
|
338
|
+
group.sort((a, b) => b.meta.id.localeCompare(a.meta.id));
|
|
339
|
+
const keep = group[0]!;
|
|
340
|
+
const drop = group.slice(1);
|
|
341
|
+
for (const d of drop) {
|
|
342
|
+
const path = dreamFilePath(agent, d.meta.id, 'paused');
|
|
343
|
+
try {
|
|
344
|
+
await unlink(path);
|
|
345
|
+
removed++;
|
|
346
|
+
logger.info({
|
|
347
|
+
msg: 'dream.consolidate_stale_paused',
|
|
348
|
+
agent,
|
|
349
|
+
id: d.meta.id,
|
|
350
|
+
source_session: source,
|
|
351
|
+
kept: keep.meta.id,
|
|
352
|
+
findings_in_dropped: d.meta.findings.length,
|
|
353
|
+
});
|
|
354
|
+
} catch (err) {
|
|
355
|
+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
356
|
+
logger.warn({
|
|
357
|
+
msg: 'dream.consolidate_unlink_failed',
|
|
358
|
+
agent,
|
|
359
|
+
path,
|
|
360
|
+
err: (err as Error).message,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (removed > 0) {
|
|
368
|
+
logger.info({ msg: 'dream.consolidate_done', removed_count: removed, agents });
|
|
369
|
+
}
|
|
370
|
+
return removed;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Remove failed dreams for a source-session, optionally keeping one id.
|
|
375
|
+
*
|
|
376
|
+
* Called by the runner (a) right after writing a NEW failed dream —
|
|
377
|
+
* keeping only the newest failure per session — and (b) after a
|
|
378
|
+
* successful run over the same session, which supersedes any earlier
|
|
379
|
+
* failures entirely. Without this, the failed-≠-empty handling
|
|
380
|
+
* (2026-07-24 report) would accumulate one .dream.failed.md per retry:
|
|
381
|
+
* the range is retried on every idle cycle until the backend recovers,
|
|
382
|
+
* so a multi-day outage would pile up dozens of files.
|
|
383
|
+
*/
|
|
384
|
+
export async function pruneFailedDreams(
|
|
385
|
+
agent: string,
|
|
386
|
+
sourceSession: string,
|
|
387
|
+
opts: { keepId?: string; coveredThroughTs?: number } = {},
|
|
388
|
+
): Promise<number> {
|
|
389
|
+
let removed = 0;
|
|
390
|
+
const all = await listDreams(agent);
|
|
391
|
+
for (const d of all) {
|
|
392
|
+
if (d.meta.status !== 'failed') continue;
|
|
393
|
+
if (d.meta.source_session !== sourceSession) continue;
|
|
394
|
+
if (opts.keepId && d.meta.id === opts.keepId) continue;
|
|
395
|
+
// A successful run only supersedes what it actually read. Passing
|
|
396
|
+
// the range it covered keeps the evidence for a failure that reached
|
|
397
|
+
// further — otherwise a short manual run over the same session would
|
|
398
|
+
// quietly delete the record of an uncovered gap, and nobody would
|
|
399
|
+
// ever learn that part of a conversation never made it into memory.
|
|
400
|
+
if (opts.coveredThroughTs !== undefined && d.meta.range_through_ts > opts.coveredThroughTs) {
|
|
401
|
+
logger.info({
|
|
402
|
+
msg: 'dream.prune_failed_skipped',
|
|
403
|
+
agent,
|
|
404
|
+
id: d.meta.id,
|
|
405
|
+
source_session: sourceSession,
|
|
406
|
+
failed_through_ts: d.meta.range_through_ts,
|
|
407
|
+
covered_through_ts: opts.coveredThroughTs,
|
|
408
|
+
reason: 'the successful run did not cover this range',
|
|
409
|
+
});
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
const path = dreamFilePath(agent, d.meta.id, 'failed');
|
|
413
|
+
try {
|
|
414
|
+
await unlink(path);
|
|
415
|
+
removed++;
|
|
416
|
+
logger.info({
|
|
417
|
+
msg: 'dream.prune_failed',
|
|
418
|
+
agent,
|
|
419
|
+
id: d.meta.id,
|
|
420
|
+
source_session: sourceSession,
|
|
421
|
+
kept: opts.keepId ?? '(none — superseded by successful run)',
|
|
422
|
+
});
|
|
423
|
+
} catch (err) {
|
|
424
|
+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
425
|
+
logger.warn({
|
|
426
|
+
msg: 'dream.prune_failed_unlink_failed',
|
|
427
|
+
agent,
|
|
428
|
+
path,
|
|
429
|
+
err: (err as Error).message,
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return removed;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Crash-recovery: scan all agents on server start, rename any
|
|
439
|
+
* `*.dream.running.md` to `.paused.md`. Findings already extracted are
|
|
440
|
+
* preserved; the next idle-trigger continues from chunks_done + 1.
|
|
441
|
+
*/
|
|
442
|
+
export async function recoverOrphanRunningDreams(agents: string[]): Promise<number> {
|
|
443
|
+
let recovered = 0;
|
|
444
|
+
for (const agent of agents) {
|
|
445
|
+
const dir = dreamsDir(agent);
|
|
446
|
+
let entries: string[];
|
|
447
|
+
try {
|
|
448
|
+
entries = await readdir(dir);
|
|
449
|
+
} catch (err) {
|
|
450
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;
|
|
451
|
+
throw err;
|
|
452
|
+
}
|
|
453
|
+
for (const name of entries) {
|
|
454
|
+
if (!name.endsWith('.dream.running.md')) continue;
|
|
455
|
+
const path = join(dir, name);
|
|
456
|
+
try {
|
|
457
|
+
const raw = await readFile(path, 'utf8');
|
|
458
|
+
const parsed = matter(raw);
|
|
459
|
+
const meta = parsed.data as unknown as DreamMeta;
|
|
460
|
+
if (meta.trigger === 'manual') {
|
|
461
|
+
// Manual dreams don't pause — but if the server crashed, mark
|
|
462
|
+
// as failed so the user can decide whether to retry. Don't try
|
|
463
|
+
// to auto-resume manual dreams (they had a specific scope tied
|
|
464
|
+
// to a /reset action; hidden auto-resume would be confusing).
|
|
465
|
+
await transitionDreamStatus(
|
|
466
|
+
agent,
|
|
467
|
+
{ meta, body: parsed.content },
|
|
468
|
+
'failed',
|
|
469
|
+
{ error: 'server crashed during manual extraction; partial findings preserved' },
|
|
470
|
+
);
|
|
471
|
+
} else {
|
|
472
|
+
await transitionDreamStatus(agent, { meta, body: parsed.content }, 'paused');
|
|
473
|
+
}
|
|
474
|
+
recovered++;
|
|
475
|
+
} catch (err) {
|
|
476
|
+
logger.warn({
|
|
477
|
+
msg: 'dream.orphan_recovery_failed',
|
|
478
|
+
agent,
|
|
479
|
+
path,
|
|
480
|
+
err: (err as Error).message,
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
if (recovered > 0) {
|
|
486
|
+
logger.info({ msg: 'dream.orphans_recovered', count: recovered, agents });
|
|
487
|
+
}
|
|
488
|
+
return recovered;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
export function dreamIdFor(agent: string, sourceSession: string, trigger: 'auto' | 'manual', date = new Date()): string {
|
|
492
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
493
|
+
const ts =
|
|
494
|
+
`${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}` +
|
|
495
|
+
`-${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`;
|
|
496
|
+
return `${ts}_${trigger}_${sourceSession}`;
|
|
497
|
+
}
|