@cortex-agent/server 2026.5.19-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/defaults/.claude/settings.json +13 -0
- package/defaults/CORTEX.md +15 -0
- package/defaults/config/budget.json +4 -0
- package/defaults/config/session-hooks.json +7 -0
- package/defaults/config/thread-templates.json +528 -0
- package/defaults/context/CORTEX.md +40 -0
- package/defaults/context/decisions/DR-0012.md +54 -0
- package/defaults/context/ideas/CORTEX.md +10 -0
- package/defaults/context/projects/CORTEX.md +25 -0
- package/defaults/context/scans/CORTEX.md +13 -0
- package/defaults/context/user/CORTEX.md +21 -0
- package/defaults/data/schedules.json +52 -0
- package/defaults/gitignore +44 -0
- package/defaults/hooks/ask-user-question-hook.mjs +66 -0
- package/defaults/hooks/cortex-md-injector.mjs +237 -0
- package/defaults/hooks/exit-plan-mode-hook.mjs +84 -0
- package/defaults/hooks/memory-ref-tracker.mjs +154 -0
- package/defaults/hooks/new-session-hook.mjs +83 -0
- package/defaults/hooks/post-task-hook.mjs +63 -0
- package/defaults/hooks/rules-loader.mjs +212 -0
- package/defaults/hooks/sensitive-file-edit.mjs +84 -0
- package/defaults/hooks/session-activity-tracker.mjs +254 -0
- package/defaults/hooks/task-status-check.mjs +218 -0
- package/defaults/hooks/tasks-yaml-guard.mjs +230 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +208 -0
- package/defaults/plugins/cortex-coder/skills/code-standards/SKILL.md +146 -0
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +164 -0
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-common/skills/compound/SKILL.md +349 -0
- package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +104 -0
- package/defaults/plugins/cortex-common/skills/critique/SKILL.md +88 -0
- package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +508 -0
- package/defaults/plugins/cortex-common/skills/diagnose/SKILL.md +169 -0
- package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +135 -0
- package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +183 -0
- package/defaults/plugins/cortex-common/skills/synthesize/SKILL.md +120 -0
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +89 -0
- package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +163 -0
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +425 -0
- package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-system/skills/approval/SKILL.md +84 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +199 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/CORTEX.md +8 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/SKILL.md +201 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/CORTEX.md +8 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/extract_session.py +165 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/scan_logs.py +402 -0
- package/defaults/plugins/cortex-system/skills/evolve/SKILL.md +115 -0
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +262 -0
- package/defaults/plugins/cortex-system/skills/gravity/SKILL.md +125 -0
- package/defaults/plugins/cortex-system/skills/orient/SKILL.md +310 -0
- package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +85 -0
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +167 -0
- package/defaults/plugins/cortex-system/skills/refresh-skills/SKILL.md +153 -0
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +209 -0
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +478 -0
- package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +95 -0
- package/defaults/prompts/directives/coder-reviewer.md +106 -0
- package/defaults/prompts/directives/coder.md +90 -0
- package/defaults/prompts/directives/director.md +97 -0
- package/defaults/prompts/directives/doc-reviewer.md +93 -0
- package/defaults/prompts/directives/doc-writer.md +85 -0
- package/defaults/prompts/directives/executor-reviewer.md +96 -0
- package/defaults/prompts/directives/executor.md +85 -0
- package/defaults/prompts/directives/milestone-executor.md +119 -0
- package/defaults/prompts/directives/milestone-reviewer.md +108 -0
- package/defaults/prompts/directives/plan-executor.md +121 -0
- package/defaults/prompts/directives/plan-reviewer.md +99 -0
- package/defaults/prompts/systemPrompts/coder.md +64 -0
- package/defaults/prompts/systemPrompts/direct.md +92 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +68 -0
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +76 -0
- package/defaults/prompts/systemPrompts/web.md +50 -0
- package/defaults/prompts/systemPrompts/worker.md +67 -0
- package/defaults/rules/correction-propagation.md +31 -0
- package/defaults/rules/decision-records.md +49 -0
- package/defaults/rules/experiment-format.md +165 -0
- package/defaults/rules/issues-md.md +37 -0
- package/defaults/rules/meta-conventions.md +45 -0
- package/defaults/rules/mission-md.md +47 -0
- package/defaults/rules/overview-md.md +41 -0
- package/defaults/rules/roadmap-md.md +55 -0
- package/defaults/rules/status-md.md +49 -0
- package/defaults/rules/task-system.md +53 -0
- package/dist/agent-adapter/capabilities.d.ts +12 -0
- package/dist/agent-adapter/capabilities.js +52 -0
- package/dist/agent-adapter/claude/adapter-tui.d.ts +140 -0
- package/dist/agent-adapter/claude/adapter-tui.js +422 -0
- package/dist/agent-adapter/claude/adapter.d.ts +85 -0
- package/dist/agent-adapter/claude/adapter.js +771 -0
- package/dist/agent-adapter/claude/cost-from-usage.d.ts +62 -0
- package/dist/agent-adapter/claude/cost-from-usage.js +97 -0
- package/dist/agent-adapter/claude/defaults.d.ts +30 -0
- package/dist/agent-adapter/claude/defaults.js +49 -0
- package/dist/agent-adapter/claude/event-parser.d.ts +28 -0
- package/dist/agent-adapter/claude/event-parser.js +173 -0
- package/dist/agent-adapter/claude/hooks-builder.d.ts +36 -0
- package/dist/agent-adapter/claude/hooks-builder.js +57 -0
- package/dist/agent-adapter/claude/jsonl-tail.d.ts +68 -0
- package/dist/agent-adapter/claude/jsonl-tail.js +344 -0
- package/dist/agent-adapter/claude/spawn-args.d.ts +38 -0
- package/dist/agent-adapter/claude/spawn-args.js +83 -0
- package/dist/agent-adapter/claude/tmux-control.d.ts +69 -0
- package/dist/agent-adapter/claude/tmux-control.js +127 -0
- package/dist/agent-adapter/claude/tool-summarizers.d.ts +2 -0
- package/dist/agent-adapter/claude/tool-summarizers.js +24 -0
- package/dist/agent-adapter/codex/adapter.d.ts +42 -0
- package/dist/agent-adapter/codex/adapter.js +916 -0
- package/dist/agent-adapter/codex/event-parser.d.ts +17 -0
- package/dist/agent-adapter/codex/event-parser.js +41 -0
- package/dist/agent-adapter/codex/spawn-args.d.ts +6 -0
- package/dist/agent-adapter/codex/spawn-args.js +30 -0
- package/dist/agent-adapter/index.d.ts +8 -0
- package/dist/agent-adapter/index.js +33 -0
- package/dist/agent-adapter/normalize/event-stream.d.ts +6 -0
- package/dist/agent-adapter/normalize/event-stream.js +47 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +58 -0
- package/dist/agent-adapter/normalize/event-types.js +5 -0
- package/dist/agent-adapter/normalize/hooks.d.ts +26 -0
- package/dist/agent-adapter/normalize/hooks.js +5 -0
- package/dist/agent-adapter/normalize/prompt-builder.d.ts +6 -0
- package/dist/agent-adapter/normalize/prompt-builder.js +23 -0
- package/dist/agent-adapter/normalize/tool-names.d.ts +6 -0
- package/dist/agent-adapter/normalize/tool-names.js +73 -0
- package/dist/agent-adapter/pi/adapter.d.ts +60 -0
- package/dist/agent-adapter/pi/adapter.js +626 -0
- package/dist/agent-adapter/pi/agent-dir.d.ts +11 -0
- package/dist/agent-adapter/pi/agent-dir.js +34 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +26 -0
- package/dist/agent-adapter/pi/event-parser.js +313 -0
- package/dist/agent-adapter/pi/framing.d.ts +6 -0
- package/dist/agent-adapter/pi/framing.js +35 -0
- package/dist/agent-adapter/pi/hook-bridge.d.ts +59 -0
- package/dist/agent-adapter/pi/hook-bridge.js +233 -0
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +26 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +140 -0
- package/dist/agent-adapter/pi/pi-ext-types.d.ts +90 -0
- package/dist/agent-adapter/pi/pi-ext-types.js +5 -0
- package/dist/agent-adapter/pi/spawn-args.d.ts +20 -0
- package/dist/agent-adapter/pi/spawn-args.js +54 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +2 -0
- package/dist/agent-adapter/pi/tool-shims.js +181 -0
- package/dist/agent-adapter/types.d.ts +94 -0
- package/dist/agent-adapter/types.js +5 -0
- package/dist/core/async-mutex.d.ts +6 -0
- package/dist/core/async-mutex.js +36 -0
- package/dist/core/cli-utils.d.ts +37 -0
- package/dist/core/cli-utils.js +69 -0
- package/dist/core/config-generator.d.ts +9 -0
- package/dist/core/config-generator.js +58 -0
- package/dist/core/gateway-generator.d.ts +46 -0
- package/dist/core/gateway-generator.js +336 -0
- package/dist/core/log.d.ts +7 -0
- package/dist/core/log.js +103 -0
- package/dist/core/paths.d.ts +32 -0
- package/dist/core/paths.js +49 -0
- package/dist/core/profile-generator.d.ts +65 -0
- package/dist/core/profile-generator.js +310 -0
- package/dist/core/running-executions.d.ts +88 -0
- package/dist/core/running-executions.js +186 -0
- package/dist/core/status-format.d.ts +18 -0
- package/dist/core/status-format.js +31 -0
- package/dist/core/task-parser.d.ts +69 -0
- package/dist/core/task-parser.js +423 -0
- package/dist/core/types/agent-types.d.ts +31 -0
- package/dist/core/types/agent-types.js +5 -0
- package/dist/core/types/thread-types.d.ts +261 -0
- package/dist/core/types/thread-types.js +5 -0
- package/dist/core/utils.d.ts +29 -0
- package/dist/core/utils.js +98 -0
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +12 -0
- package/dist/domain/agents/config.d.ts +58 -0
- package/dist/domain/agents/config.js +313 -0
- package/dist/domain/agents/facade.d.ts +52 -0
- package/dist/domain/agents/facade.js +264 -0
- package/dist/domain/agents/index.d.ts +2 -0
- package/dist/domain/agents/index.js +4 -0
- package/dist/domain/agents/profile-manager.d.ts +54 -0
- package/dist/domain/agents/profile-manager.js +161 -0
- package/dist/domain/costs/codex-event-format.d.ts +4 -0
- package/dist/domain/costs/codex-event-format.js +66 -0
- package/dist/domain/costs/codex-usage-monitor.d.ts +7 -0
- package/dist/domain/costs/codex-usage-monitor.js +72 -0
- package/dist/domain/costs/cost-tracker.d.ts +115 -0
- package/dist/domain/costs/cost-tracker.js +327 -0
- package/dist/domain/costs/gateway-manager.d.ts +6 -0
- package/dist/domain/costs/gateway-manager.js +228 -0
- package/dist/domain/costs/rate-limit-parser.d.ts +11 -0
- package/dist/domain/costs/rate-limit-parser.js +87 -0
- package/dist/domain/costs/rate-limit-throttle.d.ts +32 -0
- package/dist/domain/costs/rate-limit-throttle.js +129 -0
- package/dist/domain/executions/registry.d.ts +20 -0
- package/dist/domain/executions/registry.js +124 -0
- package/dist/domain/mcp/core-server.d.ts +2 -0
- package/dist/domain/mcp/core-server.js +34 -0
- package/dist/domain/mcp/server.d.ts +3 -0
- package/dist/domain/mcp/server.js +78 -0
- package/dist/domain/mcp/tools/context.d.ts +23 -0
- package/dist/domain/mcp/tools/context.js +51 -0
- package/dist/domain/mcp/tools/cortex-md.d.ts +17 -0
- package/dist/domain/mcp/tools/cortex-md.js +36 -0
- package/dist/domain/mcp/tools/cost.d.ts +2 -0
- package/dist/domain/mcp/tools/cost.js +54 -0
- package/dist/domain/mcp/tools/executions.d.ts +2 -0
- package/dist/domain/mcp/tools/executions.js +94 -0
- package/dist/domain/mcp/tools/schedule.d.ts +23 -0
- package/dist/domain/mcp/tools/schedule.js +245 -0
- package/dist/domain/mcp/tools/slack.d.ts +21 -0
- package/dist/domain/mcp/tools/slack.js +124 -0
- package/dist/domain/mcp/tools/task-ops.d.ts +2 -0
- package/dist/domain/mcp/tools/task-ops.js +509 -0
- package/dist/domain/mcp/tools/tui-ask.d.ts +31 -0
- package/dist/domain/mcp/tools/tui-ask.js +108 -0
- package/dist/domain/mcp/tools/tui-plan.d.ts +28 -0
- package/dist/domain/mcp/tools/tui-plan.js +118 -0
- package/dist/domain/mcp/tui-server.d.ts +2 -0
- package/dist/domain/mcp/tui-server.js +69 -0
- package/dist/domain/memory/consolidate.d.ts +55 -0
- package/dist/domain/memory/consolidate.js +471 -0
- package/dist/domain/memory/cortex-md-injector.d.ts +30 -0
- package/dist/domain/memory/cortex-md-injector.js +123 -0
- package/dist/domain/memory/cortex-md-scanner.d.ts +9 -0
- package/dist/domain/memory/cortex-md-scanner.js +67 -0
- package/dist/domain/memory/index-regen.d.ts +19 -0
- package/dist/domain/memory/index-regen.js +398 -0
- package/dist/domain/memory/rules-loader.d.ts +27 -0
- package/dist/domain/memory/rules-loader.js +97 -0
- package/dist/domain/memory/skill-scanner.d.ts +5 -0
- package/dist/domain/memory/skill-scanner.js +132 -0
- package/dist/domain/memory/user-context.d.ts +5 -0
- package/dist/domain/memory/user-context.js +34 -0
- package/dist/domain/memory/watcher.d.ts +2 -0
- package/dist/domain/memory/watcher.js +81 -0
- package/dist/domain/monitor/disk-monitor.d.ts +20 -0
- package/dist/domain/monitor/disk-monitor.js +97 -0
- package/dist/domain/monitor/gpu-monitor.d.ts +26 -0
- package/dist/domain/monitor/gpu-monitor.js +135 -0
- package/dist/domain/remote/client-bootstrap.d.ts +1 -0
- package/dist/domain/remote/client-bootstrap.js +139 -0
- package/dist/domain/remote/client-hot-reload.d.ts +18 -0
- package/dist/domain/remote/client-hot-reload.js +142 -0
- package/dist/domain/remote/client-manager.d.ts +50 -0
- package/dist/domain/remote/client-manager.js +452 -0
- package/dist/domain/remote/cortex-client.d.ts +1 -0
- package/dist/domain/remote/cortex-client.js +704 -0
- package/dist/domain/scheduling/job-registry.d.ts +31 -0
- package/dist/domain/scheduling/job-registry.js +34 -0
- package/dist/domain/scheduling/jobs/_shared.d.ts +14 -0
- package/dist/domain/scheduling/jobs/_shared.js +45 -0
- package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +1 -0
- package/dist/domain/scheduling/jobs/memory-index-regen.js +16 -0
- package/dist/domain/scheduling/jobs/scheduled-task.d.ts +11 -0
- package/dist/domain/scheduling/jobs/scheduled-task.js +186 -0
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +41 -0
- package/dist/domain/scheduling/jobs/target-dispatch.js +48 -0
- package/dist/domain/scheduling/jobs/task-archive.d.ts +1 -0
- package/dist/domain/scheduling/jobs/task-archive.js +19 -0
- package/dist/domain/scheduling/jobs/task-dispatch.d.ts +12 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +214 -0
- package/dist/domain/scheduling/runner.d.ts +13 -0
- package/dist/domain/scheduling/runner.js +24 -0
- package/dist/domain/scheduling/schedule-cli.d.ts +16 -0
- package/dist/domain/scheduling/schedule-cli.js +268 -0
- package/dist/domain/scheduling/schedule-command.d.ts +4 -0
- package/dist/domain/scheduling/schedule-command.js +274 -0
- package/dist/domain/scheduling/scheduler.d.ts +86 -0
- package/dist/domain/scheduling/scheduler.js +544 -0
- package/dist/domain/sessions/session-backup.d.ts +49 -0
- package/dist/domain/sessions/session-backup.js +217 -0
- package/dist/domain/sessions/session-hooks.d.ts +103 -0
- package/dist/domain/sessions/session-hooks.js +311 -0
- package/dist/domain/sessions/session-registry.d.ts +21 -0
- package/dist/domain/sessions/session-registry.js +31 -0
- package/dist/domain/sessions/session.d.ts +3 -0
- package/dist/domain/sessions/session.js +14 -0
- package/dist/domain/tasks/archiver.d.ts +9 -0
- package/dist/domain/tasks/archiver.js +123 -0
- package/dist/domain/tasks/dispatch-utils.d.ts +37 -0
- package/dist/domain/tasks/dispatch-utils.js +143 -0
- package/dist/domain/tasks/dispatcher.d.ts +48 -0
- package/dist/domain/tasks/dispatcher.js +285 -0
- package/dist/domain/tasks/lint.d.ts +12 -0
- package/dist/domain/tasks/lint.js +102 -0
- package/dist/domain/tasks/mutator.d.ts +21 -0
- package/dist/domain/tasks/mutator.js +208 -0
- package/dist/domain/tasks/parser.d.ts +1 -0
- package/dist/domain/tasks/parser.js +6 -0
- package/dist/domain/tasks/pending-tracker.d.ts +67 -0
- package/dist/domain/tasks/pending-tracker.js +163 -0
- package/dist/domain/tasks/recommendation/extractor.d.ts +12 -0
- package/dist/domain/tasks/recommendation/extractor.js +563 -0
- package/dist/domain/tasks/recommendation/patterns.d.ts +11 -0
- package/dist/domain/tasks/recommendation/patterns.js +99 -0
- package/dist/domain/tasks/recommendation/types.d.ts +67 -0
- package/dist/domain/tasks/recommendation/types.js +5 -0
- package/dist/domain/tasks/store.d.ts +1 -0
- package/dist/domain/tasks/store.js +3 -0
- package/dist/domain/tasks/system/cortex-run.d.ts +24 -0
- package/dist/domain/tasks/system/cortex-run.js +342 -0
- package/dist/domain/tasks/system/task-cli.d.ts +49 -0
- package/dist/domain/tasks/system/task-cli.js +664 -0
- package/dist/domain/tasks/system/task-completion.d.ts +22 -0
- package/dist/domain/tasks/system/task-completion.js +89 -0
- package/dist/domain/tasks/system/task-id-utils.d.ts +24 -0
- package/dist/domain/tasks/system/task-id-utils.js +84 -0
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +34 -0
- package/dist/domain/tasks/system/task-lifecycle-edit.js +208 -0
- package/dist/domain/tasks/system/task-lock.d.ts +25 -0
- package/dist/domain/tasks/system/task-lock.js +139 -0
- package/dist/domain/tasks/system/task-mutations.d.ts +31 -0
- package/dist/domain/tasks/system/task-mutations.js +110 -0
- package/dist/domain/tasks/system/task-process.d.ts +37 -0
- package/dist/domain/tasks/system/task-process.js +119 -0
- package/dist/domain/tasks/system/task-state.d.ts +70 -0
- package/dist/domain/tasks/system/task-state.js +176 -0
- package/dist/domain/threads/artifact-io.d.ts +18 -0
- package/dist/domain/threads/artifact-io.js +182 -0
- package/dist/domain/threads/auto-thread.d.ts +3 -0
- package/dist/domain/threads/auto-thread.js +19 -0
- package/dist/domain/threads/hook-runner.d.ts +4 -0
- package/dist/domain/threads/hook-runner.js +250 -0
- package/dist/domain/threads/index.d.ts +5 -0
- package/dist/domain/threads/index.js +7 -0
- package/dist/domain/threads/prompt-builder.d.ts +25 -0
- package/dist/domain/threads/prompt-builder.js +176 -0
- package/dist/domain/threads/runner.d.ts +83 -0
- package/dist/domain/threads/runner.js +434 -0
- package/dist/domain/threads/state-machine.d.ts +61 -0
- package/dist/domain/threads/state-machine.js +440 -0
- package/dist/domain/threads/template-loader.d.ts +20 -0
- package/dist/domain/threads/template-loader.js +189 -0
- package/dist/domain/threads/template-resolver.d.ts +1 -0
- package/dist/domain/threads/template-resolver.js +95 -0
- package/dist/domain/threads/utils.d.ts +19 -0
- package/dist/domain/threads/utils.js +49 -0
- package/dist/entry/app.d.ts +1 -0
- package/dist/entry/app.js +234 -0
- package/dist/entry/cli.d.ts +12 -0
- package/dist/entry/cli.js +254 -0
- package/dist/entry/daemon.d.ts +11 -0
- package/dist/entry/daemon.js +521 -0
- package/dist/entry/init.d.ts +93 -0
- package/dist/entry/init.js +1299 -0
- package/dist/entry/startup-helpers.d.ts +2 -0
- package/dist/entry/startup-helpers.js +56 -0
- package/dist/entry/startup-notify.d.ts +10 -0
- package/dist/entry/startup-notify.js +20 -0
- package/dist/events/event-bus.d.ts +42 -0
- package/dist/events/event-bus.js +84 -0
- package/dist/events/event-logger.d.ts +12 -0
- package/dist/events/event-logger.js +135 -0
- package/dist/events/event-replay.d.ts +1 -0
- package/dist/events/event-replay.js +51 -0
- package/dist/events/event-types.d.ts +145 -0
- package/dist/events/event-types.js +5 -0
- package/dist/events/index.d.ts +5 -0
- package/dist/events/index.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +66 -0
- package/dist/hooks/cortex-md-injector.mjs +237 -0
- package/dist/hooks/exit-plan-mode-hook.mjs +84 -0
- package/dist/hooks/memory-ref-tracker.mjs +154 -0
- package/dist/hooks/new-session-hook.mjs +83 -0
- package/dist/hooks/post-task-hook.mjs +63 -0
- package/dist/hooks/rules-loader.mjs +212 -0
- package/dist/hooks/sensitive-file-edit.mjs +84 -0
- package/dist/hooks/session-activity-tracker.mjs +254 -0
- package/dist/hooks/task-status-check.mjs +218 -0
- package/dist/hooks/tasks-yaml-guard.mjs +230 -0
- package/dist/orchestration/agent-runner.d.ts +72 -0
- package/dist/orchestration/agent-runner.js +289 -0
- package/dist/orchestration/busy-tracker.d.ts +12 -0
- package/dist/orchestration/busy-tracker.js +35 -0
- package/dist/orchestration/channel-queue.d.ts +18 -0
- package/dist/orchestration/channel-queue.js +32 -0
- package/dist/orchestration/dispatch-reconciler.d.ts +1 -0
- package/dist/orchestration/dispatch-reconciler.js +16 -0
- package/dist/orchestration/durable-helpers.d.ts +4 -0
- package/dist/orchestration/durable-helpers.js +42 -0
- package/dist/orchestration/interactions/ask-user-question.d.ts +32 -0
- package/dist/orchestration/interactions/ask-user-question.js +182 -0
- package/dist/orchestration/interactions/command-action-router.d.ts +47 -0
- package/dist/orchestration/interactions/command-action-router.js +91 -0
- package/dist/orchestration/interactions/interaction-handlers.d.ts +5 -0
- package/dist/orchestration/interactions/interaction-handlers.js +279 -0
- package/dist/orchestration/interactions/plan-approvals.d.ts +47 -0
- package/dist/orchestration/interactions/plan-approvals.js +77 -0
- package/dist/orchestration/interactions/plan-handler.d.ts +6 -0
- package/dist/orchestration/interactions/plan-handler.js +12 -0
- package/dist/orchestration/lifecycle.d.ts +50 -0
- package/dist/orchestration/lifecycle.js +308 -0
- package/dist/orchestration/orchestrator.d.ts +29 -0
- package/dist/orchestration/orchestrator.js +25 -0
- package/dist/orchestration/routing/commands/cancel.d.ts +10 -0
- package/dist/orchestration/routing/commands/cancel.js +136 -0
- package/dist/orchestration/routing/commands/channel.d.ts +11 -0
- package/dist/orchestration/routing/commands/channel.js +219 -0
- package/dist/orchestration/routing/commands/command-context.d.ts +29 -0
- package/dist/orchestration/routing/commands/command-context.js +4 -0
- package/dist/orchestration/routing/commands/cost.d.ts +3 -0
- package/dist/orchestration/routing/commands/cost.js +22 -0
- package/dist/orchestration/routing/commands/device.d.ts +6 -0
- package/dist/orchestration/routing/commands/device.js +83 -0
- package/dist/orchestration/routing/commands/dispatch.d.ts +2 -0
- package/dist/orchestration/routing/commands/dispatch.js +49 -0
- package/dist/orchestration/routing/commands/index.d.ts +15 -0
- package/dist/orchestration/routing/commands/index.js +130 -0
- package/dist/orchestration/routing/commands/mode.d.ts +13 -0
- package/dist/orchestration/routing/commands/mode.js +290 -0
- package/dist/orchestration/routing/commands/nvtop.d.ts +3 -0
- package/dist/orchestration/routing/commands/nvtop.js +103 -0
- package/dist/orchestration/routing/commands/orient.d.ts +2 -0
- package/dist/orchestration/routing/commands/orient.js +3 -0
- package/dist/orchestration/routing/commands/schedule.d.ts +4 -0
- package/dist/orchestration/routing/commands/schedule.js +132 -0
- package/dist/orchestration/routing/commands/sendfile.d.ts +2 -0
- package/dist/orchestration/routing/commands/sendfile.js +92 -0
- package/dist/orchestration/routing/commands/session.d.ts +9 -0
- package/dist/orchestration/routing/commands/session.js +153 -0
- package/dist/orchestration/routing/commands/status.d.ts +7 -0
- package/dist/orchestration/routing/commands/status.js +180 -0
- package/dist/orchestration/routing/commands/tail.d.ts +2 -0
- package/dist/orchestration/routing/commands/tail.js +73 -0
- package/dist/orchestration/routing/commands/task.d.ts +6 -0
- package/dist/orchestration/routing/commands/task.js +142 -0
- package/dist/orchestration/routing/commands/thread-handlers.d.ts +2 -0
- package/dist/orchestration/routing/commands/thread-handlers.js +138 -0
- package/dist/orchestration/routing/commands/thread.d.ts +2 -0
- package/dist/orchestration/routing/commands/thread.js +2 -0
- package/dist/orchestration/routing/edit-handler.d.ts +24 -0
- package/dist/orchestration/routing/edit-handler.js +161 -0
- package/dist/orchestration/routing/file-handler.d.ts +6 -0
- package/dist/orchestration/routing/file-handler.js +23 -0
- package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -0
- package/dist/orchestration/routing/hook-bridge-subscribers.js +79 -0
- package/dist/orchestration/routing/hook-bridge.d.ts +30 -0
- package/dist/orchestration/routing/hook-bridge.js +112 -0
- package/dist/orchestration/routing/message-router.d.ts +6 -0
- package/dist/orchestration/routing/message-router.js +70 -0
- package/dist/orchestration/routing/webhook.d.ts +10 -0
- package/dist/orchestration/routing/webhook.js +239 -0
- package/dist/orchestration/status-helpers.d.ts +66 -0
- package/dist/orchestration/status-helpers.js +222 -0
- package/dist/orchestration/superseded-edits.d.ts +22 -0
- package/dist/orchestration/superseded-edits.js +31 -0
- package/dist/orchestration/thread-executor.d.ts +31 -0
- package/dist/orchestration/thread-executor.js +234 -0
- package/dist/platform/adapter.d.ts +28 -0
- package/dist/platform/adapter.js +5 -0
- package/dist/platform/adapters/feishu.d.ts +66 -0
- package/dist/platform/adapters/feishu.js +558 -0
- package/dist/platform/adapters/index.d.ts +16 -0
- package/dist/platform/adapters/index.js +65 -0
- package/dist/platform/adapters/slack.d.ts +90 -0
- package/dist/platform/adapters/slack.js +630 -0
- package/dist/platform/index.d.ts +12 -0
- package/dist/platform/index.js +10 -0
- package/dist/platform/interactive-builder.d.ts +27 -0
- package/dist/platform/interactive-builder.js +120 -0
- package/dist/platform/testing.d.ts +100 -0
- package/dist/platform/testing.js +190 -0
- package/dist/platform/tool-trace.d.ts +33 -0
- package/dist/platform/tool-trace.js +165 -0
- package/dist/platform/types.d.ts +176 -0
- package/dist/platform/types.js +5 -0
- package/dist/platform/utils/rate-limiter.d.ts +92 -0
- package/dist/platform/utils/rate-limiter.js +213 -0
- package/dist/platform/virtual-message.d.ts +68 -0
- package/dist/platform/virtual-message.js +464 -0
- package/dist/store/atomic-write.d.ts +6 -0
- package/dist/store/atomic-write.js +18 -0
- package/dist/store/channel-repo.d.ts +21 -0
- package/dist/store/channel-repo.js +55 -0
- package/dist/store/conversation-ledger-repo.d.ts +86 -0
- package/dist/store/conversation-ledger-repo.js +220 -0
- package/dist/store/cost-repo.d.ts +57 -0
- package/dist/store/cost-repo.js +135 -0
- package/dist/store/execution-repo.d.ts +172 -0
- package/dist/store/execution-repo.js +343 -0
- package/dist/store/in-memory-repository.d.ts +14 -0
- package/dist/store/in-memory-repository.js +31 -0
- package/dist/store/json-repository.d.ts +51 -0
- package/dist/store/json-repository.js +118 -0
- package/dist/store/outbound-queue.d.ts +65 -0
- package/dist/store/outbound-queue.js +269 -0
- package/dist/store/profile-repo.d.ts +36 -0
- package/dist/store/profile-repo.js +144 -0
- package/dist/store/project-dir-repo.d.ts +22 -0
- package/dist/store/project-dir-repo.js +60 -0
- package/dist/store/schedule-repo.d.ts +92 -0
- package/dist/store/schedule-repo.js +88 -0
- package/dist/store/session-registry-repo.d.ts +38 -0
- package/dist/store/session-registry-repo.js +96 -0
- package/dist/store/session-repo.d.ts +14 -0
- package/dist/store/session-repo.js +56 -0
- package/dist/store/task-repo.d.ts +41 -0
- package/dist/store/task-repo.js +137 -0
- package/dist/store/thread-repo.d.ts +50 -0
- package/dist/store/thread-repo.js +190 -0
- package/package.json +58 -0
- package/scripts/postinstall-restart-trigger.mjs +39 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// input: executions.json (Record<string, ExecutionRecord>)
|
|
2
|
+
// output: { executionRepo } — ExecutionRepo singleton with sync read + async persist (Pattern B)
|
|
3
|
+
// stale methods (markMissingRunningExecutionsStale / reconcileStaleDispatches) return affected IDs for lock-release side effect
|
|
4
|
+
// pos: Execution truth layer persistence layer. Based on JsonRepository abstraction, reads/writes executions.json
|
|
5
|
+
// >>> If I am updated, update my header comment and CORTEX.md <<<
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import { readFileSync } from 'fs';
|
|
8
|
+
import { JsonRepository } from './json-repository.js';
|
|
9
|
+
import { createLogger } from '../core/log.js';
|
|
10
|
+
import { AsyncMutex } from '../core/async-mutex.js';
|
|
11
|
+
import { STORE_DIR } from '../core/paths.js';
|
|
12
|
+
const log = createLogger('execution-repo');
|
|
13
|
+
export const TERMINAL_STATUSES = new Set(['completed', 'failed', 'stale', 'cancelled']);
|
|
14
|
+
function getExecutionsFile(override) {
|
|
15
|
+
return override || process.env.CORTEX_EXECUTIONS_FILE || path.join(STORE_DIR, 'executions.json');
|
|
16
|
+
}
|
|
17
|
+
function nowIso() {
|
|
18
|
+
return new Date().toISOString();
|
|
19
|
+
}
|
|
20
|
+
function buildExecutionId(kind) {
|
|
21
|
+
const stamp = Date.now().toString(36);
|
|
22
|
+
const rand = Math.random().toString(36).slice(2, 6);
|
|
23
|
+
return `exec_${kind}_${stamp}_${rand}`;
|
|
24
|
+
}
|
|
25
|
+
function createBaseRecord({ kind, channel, project, trigger, backend, billingMode, sessionId, label, scheduleTaskId, threadId, agentSlotId }) {
|
|
26
|
+
const timestamp = nowIso();
|
|
27
|
+
return {
|
|
28
|
+
id: buildExecutionId(kind),
|
|
29
|
+
kind,
|
|
30
|
+
status: 'running',
|
|
31
|
+
channel: channel || null,
|
|
32
|
+
project: project || 'general',
|
|
33
|
+
source: { trigger: trigger || kind },
|
|
34
|
+
backend: backend || 'claude',
|
|
35
|
+
billingMode: billingMode || 'api',
|
|
36
|
+
session: { sessionId: sessionId || null },
|
|
37
|
+
thread: (threadId || agentSlotId) ? { threadId: threadId || null, agentSlotId: agentSlotId || null } : null,
|
|
38
|
+
dispatch: null,
|
|
39
|
+
scheduleTaskId: scheduleTaskId || null,
|
|
40
|
+
runtime: {
|
|
41
|
+
startedAt: timestamp,
|
|
42
|
+
updatedAt: timestamp,
|
|
43
|
+
endedAt: null,
|
|
44
|
+
},
|
|
45
|
+
metrics: {
|
|
46
|
+
costUsd: null,
|
|
47
|
+
numTurns: null,
|
|
48
|
+
durationS: null,
|
|
49
|
+
},
|
|
50
|
+
text: {
|
|
51
|
+
label: label || null,
|
|
52
|
+
finalOutput: null,
|
|
53
|
+
error: null,
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function finalizeExecution(record, status, { costUsd, numTurns, durationS, finalOutput, error } = {}) {
|
|
58
|
+
const timestamp = nowIso();
|
|
59
|
+
return {
|
|
60
|
+
...record,
|
|
61
|
+
status,
|
|
62
|
+
runtime: {
|
|
63
|
+
...record.runtime,
|
|
64
|
+
updatedAt: timestamp,
|
|
65
|
+
endedAt: timestamp,
|
|
66
|
+
},
|
|
67
|
+
metrics: {
|
|
68
|
+
costUsd: costUsd ?? record.metrics.costUsd,
|
|
69
|
+
numTurns: numTurns ?? record.metrics.numTurns,
|
|
70
|
+
durationS: durationS ?? record.metrics.durationS,
|
|
71
|
+
},
|
|
72
|
+
text: {
|
|
73
|
+
...record.text,
|
|
74
|
+
finalOutput: finalOutput ?? record.text.finalOutput,
|
|
75
|
+
error: error ?? record.text.error,
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
class ExecutionRepo {
|
|
80
|
+
/** In-memory source of truth for all execution records. All sync reads come from here. */
|
|
81
|
+
map = new Map();
|
|
82
|
+
repo;
|
|
83
|
+
filePath;
|
|
84
|
+
mutex = new AsyncMutex();
|
|
85
|
+
/** Promise chain for fire-and-forget persists, guarded by this.mutex. */
|
|
86
|
+
_pendingPersist = Promise.resolve();
|
|
87
|
+
constructor(opts) {
|
|
88
|
+
this.filePath = getExecutionsFile(opts?.filePath);
|
|
89
|
+
this.repo = new JsonRepository({
|
|
90
|
+
filePath: this.filePath,
|
|
91
|
+
defaultValue: () => ({}),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
// --- Lifecycle ---
|
|
95
|
+
/** Load executions from disk into memory. Populates the Map from executions.json. */
|
|
96
|
+
load() {
|
|
97
|
+
try {
|
|
98
|
+
const data = JSON.parse(readFileSync(this.filePath, 'utf8'));
|
|
99
|
+
this.map.clear();
|
|
100
|
+
for (const [id, record] of Object.entries(data)) {
|
|
101
|
+
this.map.set(id, record);
|
|
102
|
+
}
|
|
103
|
+
log.info(`Loaded ${this.map.size} executions`);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
this.map.clear();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// --- Sync reads (fast path, no await) ---
|
|
110
|
+
getExecution(id) {
|
|
111
|
+
return this.map.get(id) || null;
|
|
112
|
+
}
|
|
113
|
+
getExecutionByTaskId(taskId) {
|
|
114
|
+
if (!taskId)
|
|
115
|
+
return null;
|
|
116
|
+
const matches = [];
|
|
117
|
+
for (const record of this.map.values()) {
|
|
118
|
+
if (record.dispatch?.taskId === taskId)
|
|
119
|
+
matches.push(record);
|
|
120
|
+
}
|
|
121
|
+
// Prefer non-terminal record (running) over terminal ones when a task is re-dispatched
|
|
122
|
+
return matches.find((r) => !TERMINAL_STATUSES.has(r.status)) || matches[0] || null;
|
|
123
|
+
}
|
|
124
|
+
getRunningExecutions() {
|
|
125
|
+
const results = [];
|
|
126
|
+
for (const record of this.map.values()) {
|
|
127
|
+
if (record.status === 'running')
|
|
128
|
+
results.push(record);
|
|
129
|
+
}
|
|
130
|
+
return results;
|
|
131
|
+
}
|
|
132
|
+
getAllExecutions() {
|
|
133
|
+
return Array.from(this.map.values());
|
|
134
|
+
}
|
|
135
|
+
findRunningDispatchMatch({ scheduleTaskId, taskHash, project, taskText }) {
|
|
136
|
+
const running = this.getRunningExecutions();
|
|
137
|
+
return running.find((record) => {
|
|
138
|
+
if (record.kind !== 'dispatch')
|
|
139
|
+
return false;
|
|
140
|
+
if (scheduleTaskId && record.scheduleTaskId !== scheduleTaskId)
|
|
141
|
+
return false;
|
|
142
|
+
if (taskHash && record.dispatch?.taskHash)
|
|
143
|
+
return record.dispatch.taskHash === taskHash;
|
|
144
|
+
return record.project === project && record.text?.label === taskText;
|
|
145
|
+
}) || null;
|
|
146
|
+
}
|
|
147
|
+
getAll() {
|
|
148
|
+
return Array.from(this.map.values())
|
|
149
|
+
.sort((a, b) => b.runtime.startedAt.localeCompare(a.runtime.startedAt));
|
|
150
|
+
}
|
|
151
|
+
// --- Sync create/mutate + fire-and-forget persist ---
|
|
152
|
+
/** Internal: update a record in-place if not terminal, return updated or original. */
|
|
153
|
+
updateRecordInternal(id, updater) {
|
|
154
|
+
const current = this.map.get(id);
|
|
155
|
+
if (!current)
|
|
156
|
+
return null;
|
|
157
|
+
if (TERMINAL_STATUSES.has(current.status))
|
|
158
|
+
return current;
|
|
159
|
+
const next = updater({ ...current });
|
|
160
|
+
next.runtime = {
|
|
161
|
+
...current.runtime,
|
|
162
|
+
...next.runtime,
|
|
163
|
+
updatedAt: nowIso(),
|
|
164
|
+
};
|
|
165
|
+
this.map.set(id, next);
|
|
166
|
+
this.queuePersist();
|
|
167
|
+
return next;
|
|
168
|
+
}
|
|
169
|
+
startLocalExecution({ kind = 'local', channel, project, trigger, backend, billingMode, sessionId, label, scheduleTaskId, threadId = null, agentSlotId = null }) {
|
|
170
|
+
const record = createBaseRecord({ kind, channel, project, trigger, backend, billingMode, sessionId, label, scheduleTaskId, threadId, agentSlotId });
|
|
171
|
+
this.map.set(record.id, record);
|
|
172
|
+
this.queuePersist();
|
|
173
|
+
return record;
|
|
174
|
+
}
|
|
175
|
+
registerDispatchExecution({ taskId, machine, channel, project, scheduleTaskId, taskText, taskHash, sessionName, tmuxName, pid, backend, billingMode }) {
|
|
176
|
+
const existing = this.getExecutionByTaskId(taskId);
|
|
177
|
+
if (existing && !TERMINAL_STATUSES.has(existing.status)) {
|
|
178
|
+
return this.updateRecordInternal(existing.id, (record) => ({
|
|
179
|
+
...record,
|
|
180
|
+
status: 'running',
|
|
181
|
+
channel: channel || record.channel,
|
|
182
|
+
project: project || record.project,
|
|
183
|
+
backend: backend || record.backend,
|
|
184
|
+
billingMode: billingMode || record.billingMode,
|
|
185
|
+
scheduleTaskId: scheduleTaskId || record.scheduleTaskId,
|
|
186
|
+
text: { ...record.text, label: taskText || record.text.label },
|
|
187
|
+
dispatch: {
|
|
188
|
+
taskId,
|
|
189
|
+
taskHash: taskHash || record.dispatch?.taskHash || null,
|
|
190
|
+
machine: machine || record.dispatch?.machine || null,
|
|
191
|
+
scheduleTaskId: scheduleTaskId || record.dispatch?.scheduleTaskId || null,
|
|
192
|
+
sessionName: sessionName || record.dispatch?.sessionName || null,
|
|
193
|
+
tmuxName: tmuxName || record.dispatch?.tmuxName || null,
|
|
194
|
+
pid: pid || record.dispatch?.pid || null,
|
|
195
|
+
},
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
const record = createBaseRecord({
|
|
199
|
+
kind: 'dispatch',
|
|
200
|
+
channel,
|
|
201
|
+
project,
|
|
202
|
+
trigger: 'dispatch',
|
|
203
|
+
backend,
|
|
204
|
+
billingMode,
|
|
205
|
+
label: taskText,
|
|
206
|
+
scheduleTaskId,
|
|
207
|
+
});
|
|
208
|
+
record.dispatch = {
|
|
209
|
+
taskId,
|
|
210
|
+
taskHash: taskHash || null,
|
|
211
|
+
machine: machine || null,
|
|
212
|
+
scheduleTaskId: scheduleTaskId || null,
|
|
213
|
+
sessionName: sessionName || null,
|
|
214
|
+
tmuxName: tmuxName || null,
|
|
215
|
+
pid: pid || null,
|
|
216
|
+
};
|
|
217
|
+
this.map.set(record.id, record);
|
|
218
|
+
this.queuePersist();
|
|
219
|
+
return record;
|
|
220
|
+
}
|
|
221
|
+
touchExecution(id, patch = {}) {
|
|
222
|
+
return this.updateRecordInternal(id, (record) => ({
|
|
223
|
+
...record,
|
|
224
|
+
...patch,
|
|
225
|
+
metrics: { ...record.metrics, ...(patch.metrics || {}) },
|
|
226
|
+
text: { ...record.text, ...(patch.text || {}) },
|
|
227
|
+
dispatch: patch.dispatch ? { ...(record.dispatch || {}), ...patch.dispatch } : record.dispatch,
|
|
228
|
+
session: patch.session ? { ...record.session, ...patch.session } : record.session,
|
|
229
|
+
}));
|
|
230
|
+
}
|
|
231
|
+
completeExecution(id, metrics = {}) {
|
|
232
|
+
return this.updateRecordInternal(id, (record) => finalizeExecution(record, 'completed', metrics));
|
|
233
|
+
}
|
|
234
|
+
completeExecutionByTaskId(taskId, metrics) {
|
|
235
|
+
const record = this.getExecutionByTaskId(taskId);
|
|
236
|
+
if (!record)
|
|
237
|
+
return null;
|
|
238
|
+
return this.completeExecution(record.id, metrics);
|
|
239
|
+
}
|
|
240
|
+
failExecution(id, metrics = {}) {
|
|
241
|
+
return this.updateRecordInternal(id, (record) => finalizeExecution(record, 'failed', metrics));
|
|
242
|
+
}
|
|
243
|
+
failExecutionByTaskId(taskId, metrics) {
|
|
244
|
+
const record = this.getExecutionByTaskId(taskId);
|
|
245
|
+
if (!record)
|
|
246
|
+
return null;
|
|
247
|
+
return this.failExecution(record.id, metrics);
|
|
248
|
+
}
|
|
249
|
+
cancelExecution(id, metrics = {}) {
|
|
250
|
+
return this.updateRecordInternal(id, (record) => finalizeExecution(record, 'cancelled', metrics));
|
|
251
|
+
}
|
|
252
|
+
cancelExecutionByTaskId(taskId, metrics) {
|
|
253
|
+
const record = this.getExecutionByTaskId(taskId);
|
|
254
|
+
if (!record)
|
|
255
|
+
return null;
|
|
256
|
+
return this.cancelExecution(record.id, metrics);
|
|
257
|
+
}
|
|
258
|
+
/** Insert or replace a record by ID (used by tests for backdating). */
|
|
259
|
+
set(id, record) {
|
|
260
|
+
this.map.set(id, record);
|
|
261
|
+
this.queuePersist();
|
|
262
|
+
}
|
|
263
|
+
// --- Async operations (need mutex for serialized access) ---
|
|
264
|
+
/** Mark running executions not matching `keepRunning` as stale. Returns IDs of staled executions. */
|
|
265
|
+
async markMissingRunningExecutionsStale(keepRunning) {
|
|
266
|
+
await this._pendingPersist;
|
|
267
|
+
const staled = [];
|
|
268
|
+
await this.mutex.run(async () => {
|
|
269
|
+
const timestamp = nowIso();
|
|
270
|
+
for (const record of this.map.values()) {
|
|
271
|
+
if (record.status !== 'running')
|
|
272
|
+
continue;
|
|
273
|
+
if (keepRunning && keepRunning(record))
|
|
274
|
+
continue;
|
|
275
|
+
record.status = 'stale';
|
|
276
|
+
record.runtime.updatedAt = timestamp;
|
|
277
|
+
record.runtime.endedAt = timestamp;
|
|
278
|
+
staled.push(record.id);
|
|
279
|
+
}
|
|
280
|
+
if (staled.length > 0)
|
|
281
|
+
await this.persist();
|
|
282
|
+
});
|
|
283
|
+
return staled;
|
|
284
|
+
}
|
|
285
|
+
/** Reconcile stale dispatch executions: mark dispatches that are no longer pending and too old as stale.
|
|
286
|
+
* Returns { count, staled } where count is reconciled count and staled is the list of affected IDs. */
|
|
287
|
+
async reconcileStaleDispatches({ isTaskPending, maxAgeMs }) {
|
|
288
|
+
await this._pendingPersist;
|
|
289
|
+
return this.mutex.run(async () => {
|
|
290
|
+
const now = Date.now();
|
|
291
|
+
const timestamp = nowIso();
|
|
292
|
+
let reconciled = 0;
|
|
293
|
+
const staled = [];
|
|
294
|
+
for (const record of this.map.values()) {
|
|
295
|
+
if (record.status !== 'running')
|
|
296
|
+
continue;
|
|
297
|
+
if (record.kind !== 'dispatch')
|
|
298
|
+
continue;
|
|
299
|
+
const taskId = record.dispatch?.taskId;
|
|
300
|
+
if (taskId && isTaskPending(taskId))
|
|
301
|
+
continue;
|
|
302
|
+
const startedAt = record.runtime?.startedAt ? new Date(record.runtime.startedAt).getTime() : 0;
|
|
303
|
+
if (now - startedAt < maxAgeMs)
|
|
304
|
+
continue;
|
|
305
|
+
record.status = 'stale';
|
|
306
|
+
record.runtime.updatedAt = timestamp;
|
|
307
|
+
record.runtime.endedAt = timestamp;
|
|
308
|
+
reconciled++;
|
|
309
|
+
staled.push(record.id);
|
|
310
|
+
}
|
|
311
|
+
if (reconciled > 0) {
|
|
312
|
+
await this.persist();
|
|
313
|
+
log.info(`Reconciled ${reconciled} stale dispatch execution(s)`);
|
|
314
|
+
}
|
|
315
|
+
return { count: reconciled, staled };
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
// --- Flush & persist ---
|
|
319
|
+
/** Await all pending fire-and-forget disk writes AND any in-flight async operations. */
|
|
320
|
+
async flush() {
|
|
321
|
+
await this._pendingPersist;
|
|
322
|
+
await this.mutex.run(async () => { });
|
|
323
|
+
}
|
|
324
|
+
/** Return the current _pendingPersist promise (for tests that want to await a specific persist batch). */
|
|
325
|
+
queuePersist() {
|
|
326
|
+
this._pendingPersist = this._pendingPersist
|
|
327
|
+
.catch(() => { })
|
|
328
|
+
.then(() => this.mutex.run(() => this.persist()))
|
|
329
|
+
.catch((err) => { log.error('persist failed:', err); });
|
|
330
|
+
return this._pendingPersist;
|
|
331
|
+
}
|
|
332
|
+
/** Atomically persist the entire Map to disk. */
|
|
333
|
+
async persist() {
|
|
334
|
+
const obj = {};
|
|
335
|
+
for (const [id, record] of this.map) {
|
|
336
|
+
obj[id] = record;
|
|
337
|
+
}
|
|
338
|
+
await this.repo.write(obj);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
// ── Singleton ──────────────────────────────────────────────────────
|
|
342
|
+
export const executionRepo = new ExecutionRepo();
|
|
343
|
+
export { ExecutionRepo };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare class InMemoryRepository<T> {
|
|
2
|
+
private readonly defaultFactory;
|
|
3
|
+
private data;
|
|
4
|
+
private readonly mutex;
|
|
5
|
+
constructor(defaultFactory: () => T);
|
|
6
|
+
read(): Promise<T>;
|
|
7
|
+
write(next: T): Promise<void>;
|
|
8
|
+
mutate<R>(fn: (cur: T) => {
|
|
9
|
+
next: T;
|
|
10
|
+
result: R;
|
|
11
|
+
}): Promise<R>;
|
|
12
|
+
/** No-op: there is no external state to invalidate. */
|
|
13
|
+
invalidate(): void;
|
|
14
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// input: defaultValue factory
|
|
2
|
+
// output: InMemoryRepository<T> — same interface as JsonRepository, all-in-memory
|
|
3
|
+
// pos: test double; use wherever JsonRepository is accepted to avoid disk I/O in tests
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { AsyncMutex } from '../core/async-mutex.js';
|
|
6
|
+
export class InMemoryRepository {
|
|
7
|
+
defaultFactory;
|
|
8
|
+
data;
|
|
9
|
+
mutex = new AsyncMutex();
|
|
10
|
+
constructor(defaultFactory) {
|
|
11
|
+
this.defaultFactory = defaultFactory;
|
|
12
|
+
this.data = defaultFactory();
|
|
13
|
+
}
|
|
14
|
+
async read() {
|
|
15
|
+
return this.data;
|
|
16
|
+
}
|
|
17
|
+
async write(next) {
|
|
18
|
+
this.data = next;
|
|
19
|
+
}
|
|
20
|
+
async mutate(fn) {
|
|
21
|
+
return this.mutex.run(async () => {
|
|
22
|
+
const { next, result } = fn(this.data);
|
|
23
|
+
this.data = next;
|
|
24
|
+
return result;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/** No-op: there is no external state to invalidate. */
|
|
28
|
+
invalidate() {
|
|
29
|
+
// intentional no-op
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export interface JsonRepoOptions<T> {
|
|
2
|
+
filePath: string;
|
|
3
|
+
defaultValue: () => T;
|
|
4
|
+
/** Optional migration function. Called on every disk read; use to normalise legacy shapes without zod. */
|
|
5
|
+
migrate?: (raw: unknown) => T;
|
|
6
|
+
}
|
|
7
|
+
export declare class JsonRepository<T> {
|
|
8
|
+
private readonly opts;
|
|
9
|
+
private cache;
|
|
10
|
+
private readonly mutex;
|
|
11
|
+
/** Fires the first-call orphan sweep exactly once per instance, on the first I/O op. */
|
|
12
|
+
private sweepPromise;
|
|
13
|
+
constructor(opts: JsonRepoOptions<T>);
|
|
14
|
+
/**
|
|
15
|
+
* Delete any `<basename>.tmp.*` siblings of filePath.
|
|
16
|
+
* `atomicWrite` (tmp → rename) can orphan its tmp when the process is SIGTERM'd mid-write
|
|
17
|
+
* (e.g., daemon hot-reload landing during a long write). On next boot this sweeper clears them.
|
|
18
|
+
* Runs lazily on the first read/mutate so repos that are constructed but never used pay nothing.
|
|
19
|
+
*/
|
|
20
|
+
private sweepOrphans;
|
|
21
|
+
private ensureSwept;
|
|
22
|
+
/**
|
|
23
|
+
* Return the current value.
|
|
24
|
+
* Cache hit: zero I/O. Cache miss: reads file, parses JSON, applies migrate if present.
|
|
25
|
+
* Missing file returns and caches defaultValue().
|
|
26
|
+
*/
|
|
27
|
+
read(): Promise<T>;
|
|
28
|
+
/**
|
|
29
|
+
* Atomically persist `next` and update the in-memory cache.
|
|
30
|
+
* Does not hold the mutex — callers that need serialization should use mutate().
|
|
31
|
+
*/
|
|
32
|
+
write(next: T): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Wait until any in-flight `mutate()` has fully completed (tmp written + rename landed).
|
|
35
|
+
* Acquire-release the mutex without doing any work; FIFO ordering guarantees that once this
|
|
36
|
+
* resolves, every operation enqueued before flush() has finished.
|
|
37
|
+
* Intended for graceful SIGTERM handlers to drain writes before `process.exit(0)`.
|
|
38
|
+
*/
|
|
39
|
+
flush(): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Mutex-serialized read-modify-write.
|
|
42
|
+
* `fn` receives the current value and must return `{ next, result }`.
|
|
43
|
+
* Returns the `result` value from `fn`.
|
|
44
|
+
*/
|
|
45
|
+
mutate<R>(fn: (cur: T) => {
|
|
46
|
+
next: T;
|
|
47
|
+
result: R;
|
|
48
|
+
}): Promise<R>;
|
|
49
|
+
/** Drop the in-memory cache so the next read() fetches from disk. */
|
|
50
|
+
invalidate(): void;
|
|
51
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// input: JsonRepoOptions<T> (filePath, defaultValue, optional migrate)
|
|
2
|
+
// output: JsonRepository<T> — read / write / mutate / invalidate
|
|
3
|
+
// pos: unified file-backed JSON store with in-memory cache and AsyncMutex serialization
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import fs from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { createLogger } from '../core/log.js';
|
|
8
|
+
import { AsyncMutex } from '../core/async-mutex.js';
|
|
9
|
+
import { atomicWrite } from './atomic-write.js';
|
|
10
|
+
const log = createLogger('json-repository');
|
|
11
|
+
export class JsonRepository {
|
|
12
|
+
opts;
|
|
13
|
+
cache = null;
|
|
14
|
+
mutex = new AsyncMutex();
|
|
15
|
+
/** Fires the first-call orphan sweep exactly once per instance, on the first I/O op. */
|
|
16
|
+
sweepPromise = null;
|
|
17
|
+
constructor(opts) {
|
|
18
|
+
this.opts = opts;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Delete any `<basename>.tmp.*` siblings of filePath.
|
|
22
|
+
* `atomicWrite` (tmp → rename) can orphan its tmp when the process is SIGTERM'd mid-write
|
|
23
|
+
* (e.g., daemon hot-reload landing during a long write). On next boot this sweeper clears them.
|
|
24
|
+
* Runs lazily on the first read/mutate so repos that are constructed but never used pay nothing.
|
|
25
|
+
*/
|
|
26
|
+
async sweepOrphans() {
|
|
27
|
+
try {
|
|
28
|
+
const dir = path.dirname(this.opts.filePath);
|
|
29
|
+
const base = path.basename(this.opts.filePath);
|
|
30
|
+
const prefix = `${base}.tmp.`;
|
|
31
|
+
const entries = await fs.readdir(dir);
|
|
32
|
+
await Promise.all(entries
|
|
33
|
+
.filter((e) => e.startsWith(prefix))
|
|
34
|
+
.map((e) => fs.unlink(path.join(dir, e)).catch(() => { })));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// Best-effort. Missing directory / permission errors must not break startup.
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
ensureSwept() {
|
|
41
|
+
if (!this.sweepPromise)
|
|
42
|
+
this.sweepPromise = this.sweepOrphans();
|
|
43
|
+
return this.sweepPromise;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Return the current value.
|
|
47
|
+
* Cache hit: zero I/O. Cache miss: reads file, parses JSON, applies migrate if present.
|
|
48
|
+
* Missing file returns and caches defaultValue().
|
|
49
|
+
*/
|
|
50
|
+
async read() {
|
|
51
|
+
if (this.cache !== null)
|
|
52
|
+
return this.cache;
|
|
53
|
+
await this.ensureSwept();
|
|
54
|
+
try {
|
|
55
|
+
const raw = await fs.readFile(this.opts.filePath, 'utf8');
|
|
56
|
+
const parsed = JSON.parse(raw);
|
|
57
|
+
this.cache = this.opts.migrate ? this.opts.migrate(parsed) : parsed;
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
if (err.code === 'ENOENT') {
|
|
61
|
+
this.cache = this.opts.defaultValue();
|
|
62
|
+
}
|
|
63
|
+
else if (err instanceof SyntaxError) {
|
|
64
|
+
// Corrupt JSON — preserve the original bytes under a .corrupt.<ts> sibling
|
|
65
|
+
// so they remain recoverable, warn loudly, then fall back to defaults.
|
|
66
|
+
// Subsequent writes will atomically replace filePath; the .corrupt.* file stays put.
|
|
67
|
+
const backupPath = `${this.opts.filePath}.corrupt.${Date.now()}`;
|
|
68
|
+
try {
|
|
69
|
+
await fs.copyFile(this.opts.filePath, backupPath);
|
|
70
|
+
log.warn(`Corrupt JSON in ${this.opts.filePath} (${err.message}); backed up to ${backupPath}, resetting to defaults.`);
|
|
71
|
+
}
|
|
72
|
+
catch (copyErr) {
|
|
73
|
+
log.warn(`Corrupt JSON in ${this.opts.filePath} (${err.message}); failed to back up (${copyErr?.message ?? copyErr}); resetting to defaults.`);
|
|
74
|
+
}
|
|
75
|
+
this.cache = this.opts.defaultValue();
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
throw err;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return this.cache;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Atomically persist `next` and update the in-memory cache.
|
|
85
|
+
* Does not hold the mutex — callers that need serialization should use mutate().
|
|
86
|
+
*/
|
|
87
|
+
async write(next) {
|
|
88
|
+
await this.ensureSwept();
|
|
89
|
+
await atomicWrite(this.opts.filePath, JSON.stringify(next, null, 2));
|
|
90
|
+
this.cache = next;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Wait until any in-flight `mutate()` has fully completed (tmp written + rename landed).
|
|
94
|
+
* Acquire-release the mutex without doing any work; FIFO ordering guarantees that once this
|
|
95
|
+
* resolves, every operation enqueued before flush() has finished.
|
|
96
|
+
* Intended for graceful SIGTERM handlers to drain writes before `process.exit(0)`.
|
|
97
|
+
*/
|
|
98
|
+
async flush() {
|
|
99
|
+
await this.mutex.run(async () => { });
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Mutex-serialized read-modify-write.
|
|
103
|
+
* `fn` receives the current value and must return `{ next, result }`.
|
|
104
|
+
* Returns the `result` value from `fn`.
|
|
105
|
+
*/
|
|
106
|
+
async mutate(fn) {
|
|
107
|
+
return this.mutex.run(async () => {
|
|
108
|
+
const cur = await this.read();
|
|
109
|
+
const { next, result } = fn(cur);
|
|
110
|
+
await this.write(next);
|
|
111
|
+
return result;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/** Drop the in-memory cache so the next read() fetches from disk. */
|
|
115
|
+
invalidate() {
|
|
116
|
+
this.cache = null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { RichBlock, MessageRef, MessageContent, PostMessageOpts } from '../platform/types.js';
|
|
2
|
+
interface MessageSender {
|
|
3
|
+
postMessage(channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
|
|
4
|
+
updateMessage(ref: MessageRef, content: MessageContent): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export interface OutboundQueueOpts {
|
|
7
|
+
walPath?: string;
|
|
8
|
+
adapter: MessageSender;
|
|
9
|
+
ttlMs?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface EnqueueInput {
|
|
12
|
+
type: 'post' | 'update';
|
|
13
|
+
channel: string;
|
|
14
|
+
text: string;
|
|
15
|
+
richBlocks?: RichBlock[];
|
|
16
|
+
threadId?: string;
|
|
17
|
+
messageId?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare class OutboundQueue {
|
|
20
|
+
private walPath;
|
|
21
|
+
private adapter;
|
|
22
|
+
private ttlMs;
|
|
23
|
+
private mutex;
|
|
24
|
+
private pending;
|
|
25
|
+
private sentIds;
|
|
26
|
+
/**
|
|
27
|
+
* IDs currently being processed by the inline send path (VirtualMessage /
|
|
28
|
+
* durablePost). drain() skips these to prevent double-sends. Entries are
|
|
29
|
+
* claimed by buildDurableHooks.beforePost/beforeUpdate and released by
|
|
30
|
+
* afterSent (on success) or onSendFailed (on permanent failure).
|
|
31
|
+
* On restart, inFlight is empty — unfinished entries fall back to drain().
|
|
32
|
+
*/
|
|
33
|
+
private inFlight;
|
|
34
|
+
private opCount;
|
|
35
|
+
private drainTimer;
|
|
36
|
+
private stopped;
|
|
37
|
+
constructor(opts: OutboundQueueOpts);
|
|
38
|
+
enqueue(input: EnqueueInput): Promise<string>;
|
|
39
|
+
/** Mark an entry as "being sent by the inline path" so drain() skips it. */
|
|
40
|
+
claim(id: string): void;
|
|
41
|
+
/** Release an in-flight claim (after success or permanent failure). */
|
|
42
|
+
release(id: string): void;
|
|
43
|
+
markSent(id: string, slackTs?: string): Promise<void>;
|
|
44
|
+
recover(): Promise<number>;
|
|
45
|
+
drain(): Promise<void>;
|
|
46
|
+
compact(): Promise<void>;
|
|
47
|
+
startDrainLoop(intervalMs?: number): void;
|
|
48
|
+
stop(): Promise<void>;
|
|
49
|
+
flush(): Promise<void>;
|
|
50
|
+
getPendingCount(): number;
|
|
51
|
+
private _coalesce;
|
|
52
|
+
private _appendOp;
|
|
53
|
+
private _readWAL;
|
|
54
|
+
}
|
|
55
|
+
export declare const outboundQueue: {
|
|
56
|
+
instance: OutboundQueue | null;
|
|
57
|
+
};
|
|
58
|
+
export declare function initOutboundQueue(adapter: MessageSender, opts?: {
|
|
59
|
+
walPath?: string;
|
|
60
|
+
ttlMs?: number;
|
|
61
|
+
}): OutboundQueue;
|
|
62
|
+
export declare function getOutboundQueue(): OutboundQueue | null;
|
|
63
|
+
export declare function durablePost(queue: OutboundQueue, sender: MessageSender, channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
|
|
64
|
+
export declare function durableUpdate(queue: OutboundQueue, sender: MessageSender, ref: MessageRef, content: MessageContent): Promise<void>;
|
|
65
|
+
export {};
|