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,324 @@
|
|
|
1
|
+
// Deep file actions — write wiki page, delete source memory file,
|
|
2
|
+
// merge updates back into a wiki page.
|
|
3
|
+
//
|
|
4
|
+
// As of v2.2 the stub-pattern is gone. After successful promote/merge
|
|
5
|
+
// the source memory file gets DELETED, not stubbed. Wiki is the
|
|
6
|
+
// single source of truth.
|
|
7
|
+
//
|
|
8
|
+
// All wiki writes go through the mtime-conflict helpers from
|
|
9
|
+
// `../wiki/conflict.ts`: if a wiki page changed since we last read it,
|
|
10
|
+
// we abort and let the next run pick it up. Memory-file delete is
|
|
11
|
+
// best-effort and logs on failure but doesn't roll back the wiki write
|
|
12
|
+
// (Deep is idempotent on collision — next run sees the wiki page
|
|
13
|
+
// exists and routes to merge).
|
|
14
|
+
//
|
|
15
|
+
// See `private/dream-system-v2.md`.
|
|
16
|
+
|
|
17
|
+
import { DEFAULT_WIKI_SCHEMA, type WikiSchema } from '../wiki/language.ts';
|
|
18
|
+
import { mkdir, stat, unlink } from 'node:fs/promises';
|
|
19
|
+
import { dirname, join } from 'node:path';
|
|
20
|
+
|
|
21
|
+
import matter from 'gray-matter';
|
|
22
|
+
|
|
23
|
+
import { logger } from '../server/logger.ts';
|
|
24
|
+
import { readWithMtime, writeIfMtimeUnchanged, writeIfNotExists } from '../wiki/conflict.ts';
|
|
25
|
+
import {
|
|
26
|
+
buildInitialWikiPage,
|
|
27
|
+
buildWikiPage,
|
|
28
|
+
parseWikiPage,
|
|
29
|
+
} from '../wiki/templates.ts';
|
|
30
|
+
|
|
31
|
+
/** Defensive guard: strip a leading YAML frontmatter block if the LLM
|
|
32
|
+
* worker accidentally serialized one into the body field. The Deep
|
|
33
|
+
* prompt asks for body-only; this is a safety net so any future model
|
|
34
|
+
* drift can't reproduce the 2026-05-09 Lucid double-frontmatter bug. */
|
|
35
|
+
function stripLeadingFrontmatter(body: string): string {
|
|
36
|
+
const trimmed = body.replace(/^[\s]+/, '');
|
|
37
|
+
if (!trimmed.startsWith('---')) return body;
|
|
38
|
+
const parsed = matter(trimmed);
|
|
39
|
+
if (Object.keys(parsed.data).length === 0) return body;
|
|
40
|
+
return parsed.content.startsWith('\n') ? parsed.content : `\n${parsed.content}`;
|
|
41
|
+
}
|
|
42
|
+
import type { WikiMergeShrinkGuard } from '../config/types.ts';
|
|
43
|
+
import type {
|
|
44
|
+
CandidateOutcome,
|
|
45
|
+
MemoryFateDecision,
|
|
46
|
+
PromotionCandidate,
|
|
47
|
+
} from '../wiki/types.ts';
|
|
48
|
+
|
|
49
|
+
export interface ActionContext {
|
|
50
|
+
/** Absolute path to the wiki root (<vault>/<wiki-subfolder>). */
|
|
51
|
+
wikiAbs: string;
|
|
52
|
+
/** Anti-clobber guard for the merge path. Optional so callers that
|
|
53
|
+
* predate it still compile; when absent the built-in default below
|
|
54
|
+
* applies — the guard must never be OFF just because a caller forgot
|
|
55
|
+
* to thread config through. */
|
|
56
|
+
mergeShrinkGuard?: WikiMergeShrinkGuard;
|
|
57
|
+
/** Wiki language set — wording of generated log lines. Optional so
|
|
58
|
+
* older callers compile; defaults to German like the config does. */
|
|
59
|
+
schema?: WikiSchema;
|
|
60
|
+
/** `wiki.deep.maxPageChars`: above this a page gets sub-pages instead
|
|
61
|
+
* of more content. Optional; absent = no limit (older callers). */
|
|
62
|
+
maxPageChars?: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Fallback when no config was threaded in. Mirrors the Zod defaults in
|
|
66
|
+
* `config/types.ts` — deliberately guard-ON, see the note above. */
|
|
67
|
+
const DEFAULT_MERGE_SHRINK_GUARD: WikiMergeShrinkGuard = {
|
|
68
|
+
enabled: true,
|
|
69
|
+
minRatio: 0.5,
|
|
70
|
+
minExistingBytes: 2000,
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Apply a "promote" decision: create the wiki page, then delete the
|
|
75
|
+
* source memory file.
|
|
76
|
+
*
|
|
77
|
+
* Failure modes:
|
|
78
|
+
* - wiki page already exists at the target path → caller should have
|
|
79
|
+
* routed via decideMerge instead. We defer to writeIfNotExists and
|
|
80
|
+
* return `failed` (the runner can retry on next pass — wiki content
|
|
81
|
+
* will then be visible to Opus and decision will route to merge).
|
|
82
|
+
* - memory file delete fails (e.g. EBUSY): log warn, return promoted
|
|
83
|
+
* anyway; next Deep run sees the un-deleted memory plus the now-
|
|
84
|
+
* existing wiki page and will route to merge (idempotent).
|
|
85
|
+
*/
|
|
86
|
+
export async function applyPromote(args: {
|
|
87
|
+
candidate: PromotionCandidate;
|
|
88
|
+
decision: Extract<MemoryFateDecision, { kind: 'promote' }>;
|
|
89
|
+
ctx: ActionContext;
|
|
90
|
+
}): Promise<CandidateOutcome> {
|
|
91
|
+
const { candidate, decision, ctx } = args;
|
|
92
|
+
const wikiPath = decision.slug; // e.g. "personen/luca"
|
|
93
|
+
const wikiFileAbs = join(ctx.wikiAbs, `${wikiPath}.md`);
|
|
94
|
+
|
|
95
|
+
// Build the new wiki page content.
|
|
96
|
+
const wikiPageContent = buildInitialWikiPage({
|
|
97
|
+
slug: wikiPath,
|
|
98
|
+
type: decision.type,
|
|
99
|
+
title: decision.title,
|
|
100
|
+
body: stripLeadingFrontmatter(decision.body),
|
|
101
|
+
sources: [`${candidate.agent}/${candidate.slug}`],
|
|
102
|
+
related: decision.related,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Step 1: create wiki page (must NOT exist yet).
|
|
106
|
+
await mkdir(dirname(wikiFileAbs), { recursive: true });
|
|
107
|
+
const writeWiki = await writeIfNotExists(wikiFileAbs, wikiPageContent);
|
|
108
|
+
if (writeWiki.kind !== 'written') {
|
|
109
|
+
// Wiki page already exists — collision. Idempotent recovery: leave
|
|
110
|
+
// memory file alone, next Deep run sees the wiki page exists and
|
|
111
|
+
// will route this candidate via merge instead.
|
|
112
|
+
logger.info({
|
|
113
|
+
msg: 'dream.deep.promote_collision_left_for_next_run',
|
|
114
|
+
agent: candidate.agent,
|
|
115
|
+
memorySlug: candidate.slug,
|
|
116
|
+
wikiPath,
|
|
117
|
+
});
|
|
118
|
+
return {
|
|
119
|
+
kind: 'failed',
|
|
120
|
+
agent: candidate.agent,
|
|
121
|
+
memorySlug: candidate.slug,
|
|
122
|
+
error: `wiki page ${wikiPath} already exists; next Deep run will treat as merge candidate`,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Step 2: delete source memory file. Best-effort.
|
|
127
|
+
await deleteSourceMemory(candidate, 'promote');
|
|
128
|
+
|
|
129
|
+
return {
|
|
130
|
+
kind: 'promoted',
|
|
131
|
+
agent: candidate.agent,
|
|
132
|
+
memorySlug: candidate.slug,
|
|
133
|
+
wikiPath,
|
|
134
|
+
logSummary: (ctx.schema ?? DEFAULT_WIKI_SCHEMA).text.promoted(wikiPath, `${candidate.agent}/${candidate.slug}`),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Apply a "merge" decision: rewrite the existing wiki page with the
|
|
140
|
+
* updated body, preserve frontmatter (refresh `updated`, append source
|
|
141
|
+
* pointer if new, merge `related`), then delete the source memory file.
|
|
142
|
+
*
|
|
143
|
+
* Wiki write is mtime-aware. If the wiki page changed since we read
|
|
144
|
+
* it, abort the merge — the memory file stays untouched and gets
|
|
145
|
+
* re-evaluated next run.
|
|
146
|
+
*/
|
|
147
|
+
export async function applyMerge(args: {
|
|
148
|
+
candidate: PromotionCandidate;
|
|
149
|
+
decision: Extract<MemoryFateDecision, { kind: 'merge' }>;
|
|
150
|
+
ctx: ActionContext;
|
|
151
|
+
wikiPageMtimeMs: number;
|
|
152
|
+
}): Promise<CandidateOutcome> {
|
|
153
|
+
const { candidate, decision, ctx, wikiPageMtimeMs } = args;
|
|
154
|
+
const wikiPath = decision.wikiPath;
|
|
155
|
+
const wikiFileAbs = join(ctx.wikiAbs, `${wikiPath}.md`);
|
|
156
|
+
|
|
157
|
+
// Re-read wiki page to get current content + parse fm. We don't
|
|
158
|
+
// trust the caller's snapshot — we need the latest-known fm.
|
|
159
|
+
const existing = await readWithMtime(wikiFileAbs);
|
|
160
|
+
if (!existing) {
|
|
161
|
+
return {
|
|
162
|
+
kind: 'failed',
|
|
163
|
+
agent: candidate.agent,
|
|
164
|
+
memorySlug: candidate.slug,
|
|
165
|
+
error: `wiki page ${wikiPath} no longer exists`,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
if (existing.mtimeMs !== wikiPageMtimeMs) {
|
|
169
|
+
// Snapshot drifted. Bail — memory file stays for next run.
|
|
170
|
+
return {
|
|
171
|
+
kind: 'skipped',
|
|
172
|
+
agent: candidate.agent,
|
|
173
|
+
memorySlug: candidate.slug,
|
|
174
|
+
reason: `wiki page ${wikiPath} edited externally between read and write; will retry next run`,
|
|
175
|
+
transient: true,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
const parsed = parseWikiPage(existing.text);
|
|
179
|
+
|
|
180
|
+
// Refresh frontmatter: `updated` to today; merge `related`; append source.
|
|
181
|
+
const today = isoDate();
|
|
182
|
+
const sourcesSet = new Set<string>(
|
|
183
|
+
Array.isArray(parsed.frontmatter.sources) ? parsed.frontmatter.sources : [],
|
|
184
|
+
);
|
|
185
|
+
sourcesSet.add(`${candidate.agent}/${candidate.slug}`);
|
|
186
|
+
const relatedSet = new Set<string>(
|
|
187
|
+
Array.isArray(parsed.frontmatter.related) ? parsed.frontmatter.related : [],
|
|
188
|
+
);
|
|
189
|
+
if (decision.related) {
|
|
190
|
+
for (const r of decision.related) relatedSet.add(r);
|
|
191
|
+
}
|
|
192
|
+
const cleanBody = stripLeadingFrontmatter(decision.body);
|
|
193
|
+
|
|
194
|
+
// ── Anti-clobber guard ──────────────────────────────────────────
|
|
195
|
+
// The prompt asks for the FULL integrated body. When the model
|
|
196
|
+
// summarizes instead (realistic on large pages), writing the result
|
|
197
|
+
// destroys the page. Compare body sizes and refuse rather than write.
|
|
198
|
+
//
|
|
199
|
+
// On a trip we return BEFORE deleteSourceMemory — that is the whole
|
|
200
|
+
// point: the memory file survives, so the content still exists in two
|
|
201
|
+
// places (wiki page untouched + memory) instead of zero. `transient`
|
|
202
|
+
// keeps it out of the skip-cache so the next Deep run retries; a
|
|
203
|
+
// retry is a fresh LLM call and may well produce a proper merge.
|
|
204
|
+
const guard = ctx.mergeShrinkGuard ?? DEFAULT_MERGE_SHRINK_GUARD;
|
|
205
|
+
if (guard.enabled) {
|
|
206
|
+
const existingLen = parsed.body.trim().length;
|
|
207
|
+
const newLen = cleanBody.trim().length;
|
|
208
|
+
if (existingLen >= guard.minExistingBytes && newLen < existingLen * guard.minRatio) {
|
|
209
|
+
logger.warn({
|
|
210
|
+
msg: 'dream.deep.merge_shrink_blocked',
|
|
211
|
+
agent: candidate.agent,
|
|
212
|
+
memorySlug: candidate.slug,
|
|
213
|
+
wikiPath,
|
|
214
|
+
existingBodyChars: existingLen,
|
|
215
|
+
newBodyChars: newLen,
|
|
216
|
+
ratio: Number((newLen / existingLen).toFixed(3)),
|
|
217
|
+
minRatio: guard.minRatio,
|
|
218
|
+
hint:
|
|
219
|
+
'worker returned a much shorter body than the existing page — refusing the write to ' +
|
|
220
|
+
'prevent content loss. Wiki page and source memory are both untouched; next Deep run ' +
|
|
221
|
+
'retries. Tune via config.yaml wiki.deep.mergeShrinkGuard.',
|
|
222
|
+
});
|
|
223
|
+
return {
|
|
224
|
+
kind: 'skipped',
|
|
225
|
+
agent: candidate.agent,
|
|
226
|
+
memorySlug: candidate.slug,
|
|
227
|
+
reason:
|
|
228
|
+
`merge into ${wikiPath} refused: worker body ${newLen} chars vs existing ` +
|
|
229
|
+
`${existingLen} chars (below ${guard.minRatio}× guard) — would have destroyed content`,
|
|
230
|
+
transient: true,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const newPage = buildWikiPage({
|
|
236
|
+
frontmatter: {
|
|
237
|
+
...parsed.frontmatter,
|
|
238
|
+
slug: parsed.frontmatter.slug || wikiPath,
|
|
239
|
+
type: parsed.frontmatter.type,
|
|
240
|
+
created: parsed.frontmatter.created || today,
|
|
241
|
+
updated: today,
|
|
242
|
+
sources: [...sourcesSet],
|
|
243
|
+
...(relatedSet.size > 0 ? { related: [...relatedSet] } : {}),
|
|
244
|
+
},
|
|
245
|
+
body: cleanBody.startsWith('\n') ? cleanBody : `\n${cleanBody}`,
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
// Step 1: write wiki page (mtime check)
|
|
249
|
+
const writeWiki = await writeIfMtimeUnchanged(wikiFileAbs, newPage, existing.mtimeMs);
|
|
250
|
+
if (writeWiki.kind !== 'written') {
|
|
251
|
+
return {
|
|
252
|
+
kind: 'skipped',
|
|
253
|
+
agent: candidate.agent,
|
|
254
|
+
memorySlug: candidate.slug,
|
|
255
|
+
reason: `wiki page ${wikiPath} write failed: ${writeWiki.kind}`,
|
|
256
|
+
transient: true,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Step 2: delete source memory file. Best-effort.
|
|
261
|
+
await deleteSourceMemory(candidate, 'merge');
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
kind: 'merged',
|
|
265
|
+
agent: candidate.agent,
|
|
266
|
+
memorySlug: candidate.slug,
|
|
267
|
+
wikiPath,
|
|
268
|
+
logSummary: decision.logSummary,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ─── Helpers ────────────────────────────────────────────────────────
|
|
273
|
+
|
|
274
|
+
/** Delete the source memory file after successful wiki-write. Best-
|
|
275
|
+
* effort: a failure here doesn't roll back the wiki — Deep is
|
|
276
|
+
* idempotent (next run sees memory file + wiki page, routes to
|
|
277
|
+
* merge). Log loudly so it's visible. */
|
|
278
|
+
async function deleteSourceMemory(
|
|
279
|
+
candidate: PromotionCandidate,
|
|
280
|
+
via: 'promote' | 'merge',
|
|
281
|
+
): Promise<void> {
|
|
282
|
+
try {
|
|
283
|
+
// Only delete the file we actually read. Candidates are collected
|
|
284
|
+
// at the start of a run and worked through one LLM call at a time —
|
|
285
|
+
// with 30 of them, minutes pass. A memory_edit in that window means
|
|
286
|
+
// the wiki got the OLD text; deleting now would throw the edit away
|
|
287
|
+
// unread. Keep it: the next run sees the newer note and merges it.
|
|
288
|
+
const st = await stat(candidate.path);
|
|
289
|
+
if (st.mtimeMs !== candidate.mtimeMs) {
|
|
290
|
+
logger.warn({
|
|
291
|
+
msg: 'dream.deep.memory_changed_not_deleted',
|
|
292
|
+
agent: candidate.agent,
|
|
293
|
+
slug: candidate.slug,
|
|
294
|
+
via,
|
|
295
|
+
hint: 'memory file was edited after Deep read it — kept for the next run',
|
|
296
|
+
});
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
await unlink(candidate.path);
|
|
300
|
+
logger.debug({
|
|
301
|
+
msg: 'dream.deep.memory_unlinked',
|
|
302
|
+
agent: candidate.agent,
|
|
303
|
+
slug: candidate.slug,
|
|
304
|
+
via,
|
|
305
|
+
});
|
|
306
|
+
} catch (err) {
|
|
307
|
+
logger.warn({
|
|
308
|
+
msg: 'dream.deep.memory_unlink_failed',
|
|
309
|
+
agent: candidate.agent,
|
|
310
|
+
slug: candidate.slug,
|
|
311
|
+
path: candidate.path,
|
|
312
|
+
err: (err as Error).message,
|
|
313
|
+
hint: 'wiki was written; next Deep run will see the wiki page exists and route as merge',
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function isoDate(): string {
|
|
319
|
+
const d = new Date();
|
|
320
|
+
const y = d.getUTCFullYear();
|
|
321
|
+
const m = String(d.getUTCMonth() + 1).padStart(2, '0');
|
|
322
|
+
const day = String(d.getUTCDate()).padStart(2, '0');
|
|
323
|
+
return `${y}-${m}-${day}`;
|
|
324
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// Default LLM dispatcher for Deep. Multi-engine since Stufe 4.5 —
|
|
2
|
+
// supports openai-compatible, claude-cli (subscription via SDK), and
|
|
3
|
+
// codex-cli (subprocess) as worker. The actual LLM call lives in
|
|
4
|
+
// `deep-llm.ts`; this module owns prompt-shaping and response-parsing.
|
|
5
|
+
//
|
|
6
|
+
// As of v2.3 there's a single `decideMemoryFate` per candidate — one
|
|
7
|
+
// LLM call returns Skip/Promote/Merge in one shot.
|
|
8
|
+
//
|
|
9
|
+
// Robust JSON parsing: strips markdown fences if the model emits them
|
|
10
|
+
// despite the prompt, and validates required fields per kind. On
|
|
11
|
+
// parse failure or invalid shape, returns a `skip` outcome with the
|
|
12
|
+
// failure reason — never throws on a single bad LLM response.
|
|
13
|
+
|
|
14
|
+
import { logger } from '../server/logger.ts';
|
|
15
|
+
import type {
|
|
16
|
+
MemoryFateDecision,
|
|
17
|
+
PromotionCandidate,
|
|
18
|
+
PromotionDispatcher,
|
|
19
|
+
} from '../wiki/types.ts';
|
|
20
|
+
import type { ThinkingLevel } from '../config/types.ts';
|
|
21
|
+
import { buildDeepSystemPrompt } from './deep-prompts.ts';
|
|
22
|
+
import { callOneShotLLM } from './deep-llm.ts';
|
|
23
|
+
import { DEFAULT_WIKI_SCHEMA, type WikiSchema } from '../wiki/language.ts';
|
|
24
|
+
|
|
25
|
+
export class DefaultPromotionDispatcher implements PromotionDispatcher {
|
|
26
|
+
private readonly systemPrompt: string;
|
|
27
|
+
|
|
28
|
+
/** `schema` = the wiki language set (config `wiki.language`); the
|
|
29
|
+
* prompt names its headings, types, subfolders and prose language. */
|
|
30
|
+
constructor(schema: WikiSchema = DEFAULT_WIKI_SCHEMA) {
|
|
31
|
+
this.systemPrompt = buildDeepSystemPrompt(schema);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async decideMemoryFate(args: {
|
|
35
|
+
candidate: PromotionCandidate;
|
|
36
|
+
wikiMap: string;
|
|
37
|
+
relevantPages: Array<{ slug: string; markdown: string }>;
|
|
38
|
+
workerModel: import('../config/types.ts').ResolvedModel;
|
|
39
|
+
timeoutMs: number;
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
thinking?: ThinkingLevel;
|
|
42
|
+
}): Promise<MemoryFateDecision> {
|
|
43
|
+
const userMsg = buildDeepUserMessage(
|
|
44
|
+
args.candidate,
|
|
45
|
+
args.wikiMap,
|
|
46
|
+
args.relevantPages,
|
|
47
|
+
);
|
|
48
|
+
let text: string;
|
|
49
|
+
try {
|
|
50
|
+
text = await callOneShotLLM({
|
|
51
|
+
workerModel: args.workerModel,
|
|
52
|
+
systemPrompt: this.systemPrompt,
|
|
53
|
+
userMessage: userMsg,
|
|
54
|
+
timeoutMs: args.timeoutMs,
|
|
55
|
+
...(args.signal ? { signal: args.signal } : {}),
|
|
56
|
+
...(args.thinking ? { thinking: args.thinking } : {}),
|
|
57
|
+
logCtx: { agent: args.candidate.agent, op: 'deep', slug: args.candidate.slug },
|
|
58
|
+
});
|
|
59
|
+
} catch (err) {
|
|
60
|
+
logger.warn({
|
|
61
|
+
msg: 'dream.deep.llm_call_failed',
|
|
62
|
+
agent: args.candidate.agent,
|
|
63
|
+
slug: args.candidate.slug,
|
|
64
|
+
err: (err as Error).message,
|
|
65
|
+
});
|
|
66
|
+
return { kind: 'skip', reason: `LLM call failed: ${(err as Error).message}`, transient: true };
|
|
67
|
+
}
|
|
68
|
+
return parseDeepDecision(text, args.candidate.slug);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `newFolder: {path, purpose}` on a promote — the path defaults to the
|
|
73
|
+
* chosen subfolder when the model gave only the purpose; a string is
|
|
74
|
+
* read as the purpose. Exported for tests. */
|
|
75
|
+
export function parseNewFolder(v: unknown, subfolder: string): { path: string; purpose: string } | undefined {
|
|
76
|
+
if (!v) return undefined;
|
|
77
|
+
if (typeof v === 'string') {
|
|
78
|
+
const purpose = v.trim();
|
|
79
|
+
return purpose ? { path: subfolder, purpose } : undefined;
|
|
80
|
+
}
|
|
81
|
+
if (typeof v !== 'object') return undefined;
|
|
82
|
+
const o = v as Record<string, unknown>;
|
|
83
|
+
const purpose = typeof o.purpose === 'string' ? o.purpose.trim() : '';
|
|
84
|
+
const path = (typeof o.path === 'string' ? o.path.trim() : '').replace(/^\/+|\/+$/g, '') || subfolder;
|
|
85
|
+
return purpose ? { path, purpose } : undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ─── User-message builder ───────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
function buildDeepUserMessage(
|
|
91
|
+
c: PromotionCandidate,
|
|
92
|
+
wikiMap: string,
|
|
93
|
+
relevantPages: Array<{ slug: string; markdown: string }>,
|
|
94
|
+
): string {
|
|
95
|
+
const pageBlocks = relevantPages.length === 0
|
|
96
|
+
? '(no closely-matching wiki pages found by recall)'
|
|
97
|
+
: relevantPages
|
|
98
|
+
.map((p) => `<wiki_page slug="${p.slug}">\n${p.markdown.trim()}\n</wiki_page>`)
|
|
99
|
+
.join('\n\n');
|
|
100
|
+
return [
|
|
101
|
+
`Agent: ${c.agent}`,
|
|
102
|
+
`Memory slug: ${c.slug}`,
|
|
103
|
+
'',
|
|
104
|
+
'<wiki_map>',
|
|
105
|
+
wikiMap.trim() || '(empty)',
|
|
106
|
+
'</wiki_map>',
|
|
107
|
+
'',
|
|
108
|
+
'<relevant_wiki_pages>',
|
|
109
|
+
pageBlocks,
|
|
110
|
+
'</relevant_wiki_pages>',
|
|
111
|
+
'',
|
|
112
|
+
memoryDates(c),
|
|
113
|
+
'<memory_file>',
|
|
114
|
+
c.body.trim(),
|
|
115
|
+
'</memory_file>',
|
|
116
|
+
].join('\n');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* When the memory's content was stated, for the recency rule in the
|
|
121
|
+
* prompt. `stated_at` (set when a REM finding is applied: the end of
|
|
122
|
+
* the conversation it came from) beats `created`/`updated`, which only
|
|
123
|
+
* say when the note file was written. Exported for tests.
|
|
124
|
+
*/
|
|
125
|
+
export function memoryDates(c: { frontmatter?: Record<string, unknown> }, now: Date = new Date()): string {
|
|
126
|
+
const fm = c.frontmatter ?? {};
|
|
127
|
+
const day = (v: unknown): string | null => {
|
|
128
|
+
if (v instanceof Date) return v.toISOString().slice(0, 10);
|
|
129
|
+
if (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v)) return v.slice(0, 10);
|
|
130
|
+
return null;
|
|
131
|
+
};
|
|
132
|
+
const stated = day(fm.stated_at);
|
|
133
|
+
const written = day(fm.updated) ?? day(fm.created);
|
|
134
|
+
const lines = [`Today: ${now.toISOString().slice(0, 10)}`];
|
|
135
|
+
if (stated) lines.push(`Memory content was stated on: ${stated} (the conversation it came from)`);
|
|
136
|
+
if (written) lines.push(`Memory note was written on: ${written}${stated ? '' : ' — no statement date recorded; treat this as the best available date'}`);
|
|
137
|
+
if (!stated && !written) lines.push('Memory date: unknown');
|
|
138
|
+
return ['<memory_dates>', ...lines, '</memory_dates>', ''].join('\n');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ─── Parser ─────────────────────────────────────────────────────────
|
|
142
|
+
|
|
143
|
+
function stripFences(raw: string): string {
|
|
144
|
+
let text = raw.trim();
|
|
145
|
+
if (text.startsWith('```')) {
|
|
146
|
+
const fenceEnd = text.lastIndexOf('```');
|
|
147
|
+
if (fenceEnd > 0) {
|
|
148
|
+
text = text.slice(text.indexOf('\n') + 1, fenceEnd).trim();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return text;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Exported for tests. */
|
|
155
|
+
export function parseDeepDecision(raw: string, slug: string): MemoryFateDecision {
|
|
156
|
+
const text = stripFences(raw);
|
|
157
|
+
let parsed: unknown;
|
|
158
|
+
try {
|
|
159
|
+
parsed = JSON.parse(text);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
logger.warn({
|
|
162
|
+
msg: 'dream.deep.parse_failed',
|
|
163
|
+
slug,
|
|
164
|
+
err: (err as Error).message,
|
|
165
|
+
sample: text.slice(0, 200),
|
|
166
|
+
});
|
|
167
|
+
return { kind: 'skip', reason: 'LLM output unparseable as JSON', transient: true };
|
|
168
|
+
}
|
|
169
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
170
|
+
return { kind: 'skip', reason: 'LLM output not an object', transient: true };
|
|
171
|
+
}
|
|
172
|
+
const obj = parsed as Record<string, unknown>;
|
|
173
|
+
|
|
174
|
+
if (obj.kind === 'skip') {
|
|
175
|
+
return {
|
|
176
|
+
kind: 'skip',
|
|
177
|
+
reason: typeof obj.reason === 'string' ? obj.reason : 'LLM declined without reason',
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (obj.kind === 'promote') {
|
|
182
|
+
const subfolder = typeof obj.subfolder === 'string' ? obj.subfolder.trim() : '';
|
|
183
|
+
const slugOut = typeof obj.slug === 'string' ? obj.slug.trim() : '';
|
|
184
|
+
const type = typeof obj.type === 'string' ? obj.type.trim() : '';
|
|
185
|
+
const title = typeof obj.title === 'string' ? obj.title.trim() : '';
|
|
186
|
+
const body = typeof obj.body === 'string' ? obj.body : '';
|
|
187
|
+
if (!subfolder || !slugOut || !type || !title || !body) {
|
|
188
|
+
logger.warn({
|
|
189
|
+
msg: 'dream.deep.promote_missing_fields',
|
|
190
|
+
slug,
|
|
191
|
+
have: { subfolder, slugOut, type, title, body: body.length },
|
|
192
|
+
});
|
|
193
|
+
return { kind: 'skip', reason: 'LLM promote response missing required fields', transient: true };
|
|
194
|
+
}
|
|
195
|
+
const finalSlug = slugOut.startsWith(subfolder + '/') ? slugOut : `${subfolder}/${slugOut}`;
|
|
196
|
+
const related = Array.isArray(obj.related)
|
|
197
|
+
? obj.related.filter((r): r is string => typeof r === 'string')
|
|
198
|
+
: undefined;
|
|
199
|
+
const newFolder = parseNewFolder(obj.newFolder, subfolder);
|
|
200
|
+
return {
|
|
201
|
+
kind: 'promote',
|
|
202
|
+
subfolder,
|
|
203
|
+
slug: finalSlug,
|
|
204
|
+
type,
|
|
205
|
+
title,
|
|
206
|
+
body,
|
|
207
|
+
...(related && related.length > 0 ? { related } : {}),
|
|
208
|
+
...(newFolder ? { newFolder } : {}),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (obj.kind === 'merge') {
|
|
213
|
+
const wikiPath = typeof obj.wikiPath === 'string' ? obj.wikiPath.trim() : '';
|
|
214
|
+
const body = typeof obj.body === 'string' ? obj.body : '';
|
|
215
|
+
const logSummary = typeof obj.logSummary === 'string' ? obj.logSummary : '';
|
|
216
|
+
if (!wikiPath || !body || !logSummary) {
|
|
217
|
+
logger.warn({
|
|
218
|
+
msg: 'dream.deep.merge_missing_fields',
|
|
219
|
+
slug,
|
|
220
|
+
have: { wikiPath, body: body.length, logSummary },
|
|
221
|
+
});
|
|
222
|
+
return { kind: 'skip', reason: 'LLM merge response missing required fields', transient: true };
|
|
223
|
+
}
|
|
224
|
+
const related = Array.isArray(obj.related)
|
|
225
|
+
? obj.related.filter((r): r is string => typeof r === 'string')
|
|
226
|
+
: undefined;
|
|
227
|
+
return {
|
|
228
|
+
kind: 'merge',
|
|
229
|
+
wikiPath,
|
|
230
|
+
body,
|
|
231
|
+
logSummary,
|
|
232
|
+
...(related && related.length > 0 ? { related } : {}),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return { kind: 'skip', reason: `unknown decision kind: ${String(obj.kind)}`, transient: true };
|
|
237
|
+
}
|