@cortex-agent/server 2026.7.30 → 2026.8.3-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/defaults/CORTEX.md +1 -0
- package/defaults/config/CORTEX.md +2 -1
- package/defaults/config/hooks/13-status-md-guard.json +11 -0
- package/defaults/config/hooks/CORTEX.md +1 -0
- package/defaults/config/mcp-config-empty.json +3 -0
- package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
- package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
- package/defaults/config/thread-templates/agents/coder.json +4 -14
- package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
- package/defaults/config/thread-templates/templates/coder-review.json +3 -27
- package/defaults/context/projects/CORTEX.md +1 -1
- package/defaults/data/schedules.json +12 -0
- package/defaults/hooks/CORTEX.md +1 -0
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +193 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
- package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
- package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
- package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
- package/defaults/prompts/directives/coder-reviewer.md +24 -20
- package/defaults/prompts/directives/coder.md +4 -5
- package/defaults/prompts/directives/director.md +4 -10
- package/defaults/prompts/directives/manager.md +9 -10
- package/defaults/prompts/systemPrompts/worker.md +2 -2
- package/defaults/rules/cortex-md.md +31 -0
- package/defaults/rules/experiment-format.md +8 -1
- package/defaults/rules/issues-md.md +10 -9
- package/defaults/rules/meta-conventions.md +5 -4
- package/defaults/rules/mission-md.md +2 -1
- package/defaults/rules/status-md.md +39 -21
- package/dist/agent-adapter/bg-wait.d.ts +10 -12
- package/dist/agent-adapter/bg-wait.js +209 -129
- package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
- package/dist/agent-adapter/claude/adapter-tui.js +8 -5
- package/dist/agent-adapter/claude/adapter.d.ts +43 -14
- package/dist/agent-adapter/claude/adapter.js +276 -161
- package/dist/agent-adapter/claude/defaults.d.ts +2 -0
- package/dist/agent-adapter/claude/defaults.js +5 -5
- package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
- package/dist/agent-adapter/claude/event-parser.js +28 -31
- package/dist/agent-adapter/claude/hooks-builder.js +4 -3
- package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
- package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
- package/dist/agent-adapter/claude/spawn-args.js +44 -38
- package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
- package/dist/agent-adapter/claude/tmux-control.js +39 -32
- package/dist/agent-adapter/event-tee.d.ts +19 -0
- package/dist/agent-adapter/event-tee.js +145 -0
- package/dist/agent-adapter/index.d.ts +1 -0
- package/dist/agent-adapter/index.js +7 -3
- package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
- package/dist/agent-adapter/normalize/event-types.js +4 -4
- package/dist/agent-adapter/pi/adapter.d.ts +16 -4
- package/dist/agent-adapter/pi/adapter.js +69 -36
- package/dist/agent-adapter/pi/discovery.d.ts +19 -3
- package/dist/agent-adapter/pi/discovery.js +81 -43
- package/dist/agent-adapter/pi/event-parser.js +4 -2
- package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
- package/dist/agent-adapter/pi/spawn-args.js +6 -5
- package/dist/agent-adapter/types.d.ts +43 -2
- package/dist/agent-adapter/types.js +8 -4
- package/dist/core/atomic-write.d.ts +6 -1
- package/dist/core/atomic-write.js +183 -7
- package/dist/core/cli-utils.d.ts +15 -2
- package/dist/core/cli-utils.js +46 -41
- package/dist/core/config-generator.d.ts +4 -0
- package/dist/core/config-generator.js +34 -21
- package/dist/core/json-repository.d.ts +4 -0
- package/dist/core/json-repository.js +6 -3
- package/dist/core/locales/en.d.ts +94 -0
- package/dist/core/locales/slices/commands.d.ts +76 -0
- package/dist/core/locales/slices/commands.js +155 -1
- package/dist/core/locales/slices/status.d.ts +18 -0
- package/dist/core/locales/slices/status.js +43 -2
- package/dist/core/log.d.ts +5 -0
- package/dist/core/log.js +25 -23
- package/dist/core/pi-session-filename.d.ts +2 -0
- package/dist/core/pi-session-filename.js +18 -0
- package/dist/core/resume-reminder.d.ts +5 -0
- package/dist/core/resume-reminder.js +18 -0
- package/dist/core/runtime-env.d.ts +1 -0
- package/dist/core/runtime-env.js +15 -0
- package/dist/core/settings-migration.d.ts +5 -0
- package/dist/core/settings-migration.js +128 -0
- package/dist/core/settings-spec.d.ts +174 -0
- package/dist/core/settings-spec.js +150 -0
- package/dist/core/settings.d.ts +10 -0
- package/dist/core/settings.js +235 -0
- package/dist/core/task-parser.d.ts +11 -1
- package/dist/core/task-parser.js +34 -3
- package/dist/core/types/agent-types.d.ts +19 -0
- package/dist/core/types/agent-types.js +1 -1
- package/dist/core/types/thread-types.d.ts +48 -3
- package/dist/core/types/thread-types.js +2 -2
- package/dist/core/utils.d.ts +21 -1
- package/dist/core/utils.js +37 -1
- package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
- package/dist/domain/agent-run/access-probe-cli.js +139 -0
- package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
- package/dist/domain/agent-run/access-probe-policy.js +614 -0
- package/dist/domain/agent-run/access-probe.d.ts +21 -0
- package/dist/domain/agent-run/access-probe.js +194 -0
- package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
- package/dist/domain/agent-run/agent-run-cli.js +171 -0
- package/dist/domain/agent-run/atif.d.ts +54 -0
- package/dist/domain/agent-run/atif.js +211 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
- package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
- package/dist/domain/agent-run/identity.d.ts +62 -0
- package/dist/domain/agent-run/identity.js +118 -0
- package/dist/domain/agent-run/journal.d.ts +51 -0
- package/dist/domain/agent-run/journal.js +259 -0
- package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
- package/dist/domain/agent-run/manifest-contract.js +134 -0
- package/dist/domain/agent-run/manifest.d.ts +51 -0
- package/dist/domain/agent-run/manifest.js +801 -0
- package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
- package/dist/domain/agent-run/pinned-node-process.js +206 -0
- package/dist/domain/agent-run/role-surface.d.ts +4 -0
- package/dist/domain/agent-run/role-surface.js +99 -0
- package/dist/domain/agent-run/run-config.d.ts +22 -0
- package/dist/domain/agent-run/run-config.js +135 -0
- package/dist/domain/agent-run/runner.d.ts +7 -0
- package/dist/domain/agent-run/runner.js +518 -0
- package/dist/domain/agent-run/supervisor.d.ts +78 -0
- package/dist/domain/agent-run/supervisor.js +425 -0
- package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
- package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
- package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
- package/dist/domain/agent-run/trajectory-merge.js +505 -0
- package/dist/domain/agents/config.d.ts +10 -0
- package/dist/domain/agents/config.js +149 -44
- package/dist/domain/agents/facade.d.ts +42 -7
- package/dist/domain/agents/facade.js +174 -170
- package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
- package/dist/domain/agents/provider-run-lifecycle.js +60 -0
- package/dist/domain/auth/auth-events.d.ts +18 -0
- package/dist/domain/auth/auth-events.js +38 -0
- package/dist/domain/auth/auth-format.d.ts +2 -0
- package/dist/domain/auth/auth-format.js +58 -0
- package/dist/domain/auth/auth-status.d.ts +61 -0
- package/dist/domain/auth/auth-status.js +304 -0
- package/dist/domain/auth/auth-watch.d.ts +16 -0
- package/dist/domain/auth/auth-watch.js +125 -0
- package/dist/domain/auth/cc-login.d.ts +7 -0
- package/dist/domain/auth/cc-login.js +16 -0
- package/dist/domain/auth/cc-subscription.d.ts +38 -0
- package/dist/domain/auth/cc-subscription.js +204 -0
- package/dist/domain/auth/index.d.ts +12 -0
- package/dist/domain/auth/index.js +16 -0
- package/dist/domain/auth/login-flow.d.ts +120 -0
- package/dist/domain/auth/login-flow.js +253 -0
- package/dist/domain/auth/login-service.d.ts +32 -0
- package/dist/domain/auth/login-service.js +97 -0
- package/dist/domain/auth/logout.d.ts +32 -0
- package/dist/domain/auth/logout.js +123 -0
- package/dist/domain/auth/pi-login.d.ts +36 -0
- package/dist/domain/auth/pi-login.js +72 -0
- package/dist/domain/auth/pi-oauth.d.ts +36 -0
- package/dist/domain/auth/pi-oauth.js +84 -0
- package/dist/domain/auth/pi-runtime.d.ts +72 -0
- package/dist/domain/auth/pi-runtime.js +86 -0
- package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
- package/dist/domain/mcp/benchmark-thread-server.js +26 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
- package/dist/domain/memory/user-context.js +6 -8
- package/dist/domain/monitor/disk-monitor.js +47 -16
- package/dist/domain/projects/project-store.js +23 -6
- package/dist/domain/remote/client-hot-reload.d.ts +9 -1
- package/dist/domain/remote/client-hot-reload.js +60 -12
- package/dist/domain/remote/client-manager.js +12 -6
- package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
- package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
- package/dist/domain/scheduling/runner.d.ts +2 -0
- package/dist/domain/scheduling/runner.js +7 -4
- package/dist/domain/sessions/session-backup.d.ts +14 -20
- package/dist/domain/sessions/session-backup.js +57 -68
- package/dist/domain/system/doctor.d.ts +4 -0
- package/dist/domain/system/doctor.js +113 -28
- package/dist/domain/system/install-cli.js +8 -3
- package/dist/domain/system/server-update-check.js +7 -5
- package/dist/domain/system/system-notice.d.ts +3 -1
- package/dist/domain/system/system-notice.js +6 -11
- package/dist/domain/tasks/archiver.d.ts +1 -0
- package/dist/domain/tasks/archiver.js +13 -7
- package/dist/domain/tasks/claim-recovery.d.ts +3 -3
- package/dist/domain/tasks/claim-recovery.js +12 -8
- package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
- package/dist/domain/tasks/dispatch-utils.js +22 -18
- package/dist/domain/tasks/dispatcher.d.ts +1 -0
- package/dist/domain/tasks/dispatcher.js +9 -5
- package/dist/domain/tasks/mutator.d.ts +21 -11
- package/dist/domain/tasks/mutator.js +30 -24
- package/dist/domain/tasks/pending-tracker.d.ts +5 -2
- package/dist/domain/tasks/pending-tracker.js +11 -5
- package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
- package/dist/domain/tasks/system/cortex-run.js +24 -4
- package/dist/domain/tasks/system/task-cli.d.ts +1 -0
- package/dist/domain/tasks/system/task-cli.js +72 -22
- package/dist/domain/tasks/system/task-completion.d.ts +19 -2
- package/dist/domain/tasks/system/task-completion.js +31 -17
- package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
- package/dist/domain/tasks/system/task-file-input.js +57 -0
- package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
- package/dist/domain/tasks/system/task-id-utils.js +13 -4
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
- package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
- package/dist/domain/tasks/system/task-lock.js +19 -5
- package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
- package/dist/domain/tasks/system/task-mutations.js +28 -4
- package/dist/domain/tasks/system/task-process.js +10 -8
- package/dist/domain/tasks/system/task-state.d.ts +65 -11
- package/dist/domain/tasks/system/task-state.js +86 -13
- package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
- package/dist/domain/threads/local-runtime-deps.js +91 -0
- package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
- package/dist/domain/threads/local-runtime-scope.js +12 -0
- package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
- package/dist/domain/threads/pending-user-inputs.js +37 -0
- package/dist/domain/threads/prompt-builder.d.ts +12 -1
- package/dist/domain/threads/prompt-builder.js +73 -26
- package/dist/domain/threads/runner.d.ts +15 -3
- package/dist/domain/threads/runner.js +261 -105
- package/dist/domain/threads/state-machine.d.ts +1 -1
- package/dist/domain/threads/state-machine.js +17 -8
- package/dist/domain/ui-service/app-router.d.ts +86 -6
- package/dist/domain/ui-service/app-router.js +171 -133
- package/dist/domain/ui-service/input-schemas.d.ts +132 -10
- package/dist/domain/ui-service/input-schemas.js +59 -5
- package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
- package/dist/domain/ui-service/mutate/approvals.js +2 -1
- package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
- package/dist/domain/ui-service/mutate/auth.js +83 -0
- package/dist/domain/ui-service/mutate/config.js +11 -10
- package/dist/domain/ui-service/query/approvals.js +3 -0
- package/dist/domain/ui-service/query/auth.d.ts +6 -0
- package/dist/domain/ui-service/query/auth.js +12 -0
- package/dist/domain/ui-service/query/config.d.ts +5 -5
- package/dist/domain/ui-service/query/config.js +27 -17
- package/dist/domain/ui-service/query/tasks.d.ts +1 -1
- package/dist/domain/ui-service/query/tasks.js +69 -30
- package/dist/domain/ui-service/query/threads.js +3 -3
- package/dist/domain/ui-service/types.d.ts +67 -8
- package/dist/domain/ui-service/types.js +2 -2
- package/dist/domain/ui-service/ui-service.js +16 -2
- package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
- package/dist/entry/admin-channel-hot-reload.js +22 -0
- package/dist/entry/app.js +38 -38
- package/dist/entry/auth-cli.d.ts +10 -0
- package/dist/entry/auth-cli.js +52 -0
- package/dist/entry/cli-help.d.ts +5 -0
- package/dist/entry/cli-help.js +130 -0
- package/dist/entry/cli.d.ts +5 -5
- package/dist/entry/cli.js +174 -248
- package/dist/entry/daemon.d.ts +11 -0
- package/dist/entry/daemon.js +204 -103
- package/dist/entry/draft-attachments.d.ts +8 -0
- package/dist/entry/draft-attachments.js +83 -0
- package/dist/entry/feishu-login.d.ts +2 -6
- package/dist/entry/feishu-login.js +16 -21
- package/dist/entry/init.js +6 -4
- package/dist/entry/start-ui-http.d.ts +2 -8
- package/dist/entry/start-ui-http.js +7 -34
- package/dist/events/event-logger.js +11 -13
- package/dist/events/event-types.d.ts +19 -1
- package/dist/events/event-types.js +3 -3
- package/dist/events/index.d.ts +1 -1
- package/dist/events/index.js +3 -3
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +193 -0
- package/dist/orchestration/agent-file-send.js +44 -14
- package/dist/orchestration/agent-runner.d.ts +7 -3
- package/dist/orchestration/agent-runner.js +65 -41
- package/dist/orchestration/conversation-runner.d.ts +5 -1
- package/dist/orchestration/conversation-runner.js +16 -7
- package/dist/orchestration/lifecycle.d.ts +23 -1
- package/dist/orchestration/lifecycle.js +103 -40
- package/dist/orchestration/mid-turn-inject.d.ts +2 -0
- package/dist/orchestration/mid-turn-inject.js +29 -13
- package/dist/orchestration/resume-dispatcher.d.ts +3 -5
- package/dist/orchestration/resume-dispatcher.js +9 -17
- package/dist/orchestration/routing/commands/index.d.ts +4 -1
- package/dist/orchestration/routing/commands/index.js +83 -61
- package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
- package/dist/orchestration/routing/commands/login-notice.js +97 -0
- package/dist/orchestration/routing/commands/login.d.ts +12 -0
- package/dist/orchestration/routing/commands/login.js +555 -0
- package/dist/orchestration/routing/commands/status.js +45 -59
- package/dist/orchestration/routing/edit-handler.d.ts +5 -0
- package/dist/orchestration/routing/edit-handler.js +127 -73
- package/dist/orchestration/routing/webhook.js +5 -4
- package/dist/orchestration/session-rewind.d.ts +5 -1
- package/dist/orchestration/session-rewind.js +106 -62
- package/dist/orchestration/session-send.d.ts +2 -0
- package/dist/orchestration/session-send.js +5 -6
- package/dist/orchestration/status-helpers.d.ts +1 -2
- package/dist/orchestration/status-helpers.js +7 -10
- package/dist/orchestration/thread-callback.d.ts +19 -11
- package/dist/orchestration/thread-callback.js +132 -61
- package/dist/orchestration/thread-executor.js +37 -27
- package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
- package/dist/orchestration/turn-mutation-lock.js +36 -0
- package/dist/orchestration/turn-notify.d.ts +2 -5
- package/dist/orchestration/turn-notify.js +9 -21
- package/dist/platform/adapter.d.ts +1 -0
- package/dist/platform/adapter.js +2 -2
- package/dist/platform/adapters/composite-adapter.d.ts +2 -0
- package/dist/platform/adapters/composite-adapter.js +13 -3
- package/dist/platform/adapters/feishu.d.ts +2 -4
- package/dist/platform/adapters/feishu.js +38 -59
- package/dist/platform/adapters/index.d.ts +1 -1
- package/dist/platform/adapters/index.js +13 -12
- package/dist/platform/adapters/slack.d.ts +1 -1
- package/dist/platform/adapters/slack.js +12 -35
- package/dist/platform/index.d.ts +2 -1
- package/dist/platform/index.js +3 -3
- package/dist/platform/testing.d.ts +1 -0
- package/dist/platform/testing.js +13 -4
- package/dist/platform/tool-trace.js +6 -11
- package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
- package/dist/platform/ui-http/ui-http-server.js +6 -18
- package/dist/store/execution-repo.d.ts +17 -1
- package/dist/store/execution-repo.js +55 -4
- package/dist/store/prompt-migration-replacements.d.ts +4 -0
- package/dist/store/prompt-migration-replacements.js +149 -0
- package/dist/store/thread-repo.d.ts +15 -4
- package/dist/store/thread-repo.js +61 -24
- package/dist/store/version-migrations.js +36 -1
- package/native/cortex-supervisor/dist/build-manifest.json +22 -0
- package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
- package/package.json +5 -2
- package/web/dist/assets/index-XqBCYtkw.js +139 -0
- package/web/dist/assets/index-zpf3OSKC.css +1 -0
- package/web/dist/index.html +2 -2
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
- package/web/dist/assets/index-B19jLgji.js +0 -138
- package/web/dist/assets/index-BuFyPyRW.css +0 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// input: executions.json (Record<string, ExecutionRecord>)
|
|
2
|
-
// output: { executionRepo } — ExecutionRepo singleton with sync read + async persist (Pattern B)
|
|
3
|
-
//
|
|
2
|
+
// output: { executionRepo } — ExecutionRepo singleton with sync read + coalesced async persist (Pattern B)
|
|
3
|
+
// archiveTerminal moves week-old terminal records to data/archive/executions-archive.jsonl
|
|
4
4
|
// pos: Execution truth layer persistence layer. Based on JsonRepository abstraction, reads/writes executions.json
|
|
5
5
|
// >>> If I am updated, update my header comment and CORTEX.md <<<
|
|
6
6
|
import * as path from 'path';
|
|
7
7
|
import { readFileSync } from 'fs';
|
|
8
|
+
import { appendFile, mkdir } from 'fs/promises';
|
|
8
9
|
import { JsonRepository } from '../core/json-repository.js';
|
|
9
10
|
import { createLogger } from '../core/log.js';
|
|
10
11
|
import { AsyncMutex } from '../core/async-mutex.js';
|
|
@@ -85,11 +86,14 @@ class ExecutionRepo {
|
|
|
85
86
|
mutex = new AsyncMutex();
|
|
86
87
|
/** Promise chain for fire-and-forget persists, guarded by this.mutex. */
|
|
87
88
|
_pendingPersist = Promise.resolve();
|
|
89
|
+
/** True while a persist is queued but not yet snapshotting — lets queuePersist coalesce. */
|
|
90
|
+
_persistQueued = false;
|
|
88
91
|
constructor(opts) {
|
|
89
92
|
this.filePath = getExecutionsFile(opts?.filePath);
|
|
90
93
|
this.repo = new JsonRepository({
|
|
91
94
|
filePath: this.filePath,
|
|
92
95
|
defaultValue: () => ({}),
|
|
96
|
+
compact: true, // multi-MB store: pretty-printing costs ~40% extra sync stringify per write
|
|
93
97
|
});
|
|
94
98
|
}
|
|
95
99
|
// --- Lifecycle ---
|
|
@@ -342,17 +346,64 @@ class ExecutionRepo {
|
|
|
342
346
|
return { count: reconciled, staled };
|
|
343
347
|
});
|
|
344
348
|
}
|
|
349
|
+
// --- Terminal-record archival ---
|
|
350
|
+
/** Default archive sibling: <dir>/archive/<basename>-archive.jsonl */
|
|
351
|
+
defaultArchivePath() {
|
|
352
|
+
const base = path.basename(this.filePath).replace(/\.json$/, '');
|
|
353
|
+
return path.join(path.dirname(this.filePath), 'archive', `${base}-archive.jsonl`);
|
|
354
|
+
}
|
|
355
|
+
selectArchivable(cutoffIso) {
|
|
356
|
+
const eligible = [];
|
|
357
|
+
for (const record of this.map.values()) {
|
|
358
|
+
if (!TERMINAL_STATUSES.has(record.status))
|
|
359
|
+
continue;
|
|
360
|
+
const endedAt = record.runtime?.endedAt || record.runtime?.updatedAt || record.runtime?.startedAt;
|
|
361
|
+
if (endedAt && endedAt < cutoffIso)
|
|
362
|
+
eligible.push(record);
|
|
363
|
+
}
|
|
364
|
+
return eligible;
|
|
365
|
+
}
|
|
366
|
+
/** Move terminal records older than `olderThanMs` into an append-only JSONL archive.
|
|
367
|
+
* Append-then-delete ordering: a crash between the two steps can duplicate archive lines
|
|
368
|
+
* but never loses a record. Returns the number of archived records. */
|
|
369
|
+
async archiveTerminal({ olderThanMs = 7 * 24 * 60 * 60 * 1000, archivePath } = {}) {
|
|
370
|
+
await this._pendingPersist;
|
|
371
|
+
return this.mutex.run(async () => {
|
|
372
|
+
const cutoffIso = new Date(Date.now() - olderThanMs).toISOString();
|
|
373
|
+
const eligible = this.selectArchivable(cutoffIso);
|
|
374
|
+
if (eligible.length === 0)
|
|
375
|
+
return 0;
|
|
376
|
+
const target = archivePath || this.defaultArchivePath();
|
|
377
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
378
|
+
await appendFile(target, eligible.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
|
|
379
|
+
for (const r of eligible)
|
|
380
|
+
this.map.delete(r.id);
|
|
381
|
+
await this.persist();
|
|
382
|
+
log.info(`Archived ${eligible.length} terminal execution(s) to ${target}`);
|
|
383
|
+
return eligible.length;
|
|
384
|
+
});
|
|
385
|
+
}
|
|
345
386
|
// --- Flush & persist ---
|
|
346
387
|
/** Await all pending fire-and-forget disk writes AND any in-flight async operations. */
|
|
347
388
|
async flush() {
|
|
348
389
|
await this._pendingPersist;
|
|
349
390
|
await this.mutex.run(async () => { });
|
|
350
391
|
}
|
|
351
|
-
/** Return the current _pendingPersist promise (for tests that want to await a specific persist batch).
|
|
392
|
+
/** Return the current _pendingPersist promise (for tests that want to await a specific persist batch).
|
|
393
|
+
* Coalescing: map mutations are synchronous and persist() snapshots the whole map, so any
|
|
394
|
+
* mutation made before a queued persist STARTS is covered by it — a second queue entry would
|
|
395
|
+
* only re-write identical state. The flag resets right before the snapshot; mutations landing
|
|
396
|
+
* after that queue a fresh persist. Collapses sync bursts from N stringifies to 1. */
|
|
352
397
|
queuePersist() {
|
|
398
|
+
if (this._persistQueued)
|
|
399
|
+
return this._pendingPersist;
|
|
400
|
+
this._persistQueued = true;
|
|
353
401
|
this._pendingPersist = this._pendingPersist
|
|
354
402
|
.catch(() => { })
|
|
355
|
-
.then(() => this.mutex.run(() =>
|
|
403
|
+
.then(() => this.mutex.run(() => {
|
|
404
|
+
this._persistQueued = false;
|
|
405
|
+
return this.persist();
|
|
406
|
+
}))
|
|
356
407
|
.catch((err) => { log.error('persist failed:', err); });
|
|
357
408
|
return this._pendingPersist;
|
|
358
409
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const CODER_COMMIT_POLICY_REPLACEMENTS: ReadonlyArray<readonly [string, string]>;
|
|
2
|
+
export declare const MANAGER_TASK_FILE_REPLACEMENTS: ReadonlyArray<readonly [string, string]>;
|
|
3
|
+
export declare const STATUS_REGISTER_REPLACEMENTS: ReadonlyArray<readonly [string, string]>;
|
|
4
|
+
export declare const CODER_REVIEWER_COMMIT_POLICY_REPLACEMENTS: ReadonlyArray<readonly [string, string]>;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// input: Legacy coder, reviewer, manager, worker and director prompt text
|
|
2
|
+
// output: Commit-policy, task-input and STATUS-register replacement tables
|
|
3
|
+
// pos: Defines stock-text directive migrations
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
const REVIEWER_HANDOFF_BOUNDARY_BASE = '- Commits must land **before** the handoff boundary (before downstream consumers run it, before QA reviews, before the thread ends). Uncommitted changes at handoff are **Blockers**.';
|
|
6
|
+
const REVIEWER_HANDOFF_BOUNDARY = `${REVIEWER_HANDOFF_BOUNDARY_BASE} Your own fixes are held to the same rule: they are committed before you write the review artifact, and the artifact cites their SHAs.`;
|
|
7
|
+
const REVIEWER_COMMIT_RULES = [
|
|
8
|
+
"- Attribute the implementation from the summary/artifact's explicit SHA evidence and verify the commit and diff with Git. Missing or unverifiable attribution is a **Blocker**.",
|
|
9
|
+
'- Commit subjects should reference the spec identifier when repository policy permits; omission is a **Nice-to-have** in that case. When repository policy forbids internal or context identifiers, their omission is compliant, must not be treated as a Blocker, and must not require a metadata-only follow-up commit.',
|
|
10
|
+
].join('\n');
|
|
11
|
+
const REVIEWER_COMMIT_PROCEDURE = "Verify implementation attribution from the summary/artifact's explicit SHA evidence and Git history, then assess subject references under repository policy.";
|
|
12
|
+
const CODER_COMMIT_POLICY = 'Task/spec identifiers belong in commit subjects only when repository policy permits. Repository-local privacy rules take precedence; omission required by such a rule is compliant, and attribution must instead use the implementation SHA in the summary/artifact.';
|
|
13
|
+
export const CODER_COMMIT_POLICY_REPLACEMENTS = [
|
|
14
|
+
[
|
|
15
|
+
'- **Code commits**: your implementation committed to git with a clear message. Configuration is in-repo, not hardcoded at runtime. Commit message references the task / issue / ticket ID when available.',
|
|
16
|
+
`- **Code commits**: your implementation committed to git with a clear message. Configuration is in-repo, not hardcoded at runtime. ${CODER_COMMIT_POLICY}`,
|
|
17
|
+
],
|
|
18
|
+
[
|
|
19
|
+
'- Use clear commit messages that reference the spec identifier (task ID, issue reference, plan section).',
|
|
20
|
+
`- Use clear commit messages. ${CODER_COMMIT_POLICY}`,
|
|
21
|
+
],
|
|
22
|
+
[
|
|
23
|
+
'- Use clear commit messages that reference the spec identifier (EXP ID, task ID, issue reference).',
|
|
24
|
+
`- Use clear commit messages. ${CODER_COMMIT_POLICY}`,
|
|
25
|
+
],
|
|
26
|
+
[
|
|
27
|
+
'- Git commit messages: concise, reference the spec identifier, describe what was implemented. No decorative language.',
|
|
28
|
+
`- Git commit messages: concise and describe what was implemented. ${CODER_COMMIT_POLICY} No decorative language.`,
|
|
29
|
+
],
|
|
30
|
+
];
|
|
31
|
+
export const MANAGER_TASK_FILE_REPLACEMENTS = [
|
|
32
|
+
[
|
|
33
|
+
'3. **Decompose via /manager-method** — the method (map the seams before cutting, the Cut-at-the-Seam Iron Rules, one-criterion-one-task with explicit dependencies, template selection by residual reasoning, and the per-child self-audit quality gate) lives in the skill (pointer below). After the method yields your children, create them in ONE call (exact recipe — write the JSON to a temp file first):',
|
|
34
|
+
'3. **Decompose via /manager-method** — the method (map the seams before cutting, the Cut-at-the-Seam Iron Rules, one-criterion-one-task with explicit dependencies, template selection by residual reasoning, and the per-child self-audit quality gate) lives in the skill (pointer below). After the method yields your children, create them in ONE call. Use the Write tool—not shell redirection—to create `/tmp/subtasks-<your Task ID>.json` with this content:',
|
|
35
|
+
],
|
|
36
|
+
[
|
|
37
|
+
[
|
|
38
|
+
' ```bash',
|
|
39
|
+
" cat > /tmp/subtasks-<your Task ID>.json <<'JSON'",
|
|
40
|
+
' {"subtasks": [',
|
|
41
|
+
' {"key": "a", "text": "Create X", "done-when": "X exists and ...", "template": "execute-review"},',
|
|
42
|
+
' {"key": "b", "text": "Create Y", "done-when": "...", "template": "execute-review", "depends-on": ["a"]}',
|
|
43
|
+
' ]}',
|
|
44
|
+
' JSON',
|
|
45
|
+
' cortex-task decompose --project <project> --task-id <your Task ID> --keep-parent --auto-lock --subtasks-file /tmp/subtasks-<your Task ID>.json',
|
|
46
|
+
' ```',
|
|
47
|
+
].join('\n'),
|
|
48
|
+
[
|
|
49
|
+
' ```json',
|
|
50
|
+
' [',
|
|
51
|
+
' {"key": "a", "text": "Create X", "done-when": "X exists and ...", "template": "execute-review"},',
|
|
52
|
+
' {"key": "b", "text": "Create Y", "done-when": "...", "template": "execute-review", "depends-on": ["a"]}',
|
|
53
|
+
' ]',
|
|
54
|
+
' ```',
|
|
55
|
+
'',
|
|
56
|
+
' Then run `cortex-task decompose --project <project> --task-id <your Task ID> --keep-parent --auto-lock --subtasks-file /tmp/subtasks-<your Task ID>.json`.',
|
|
57
|
+
].join('\n'),
|
|
58
|
+
],
|
|
59
|
+
[
|
|
60
|
+
'1. Read the actual deliverable (code, files, experiment records) and check it against the child\'s done_when. Run tests where code is involved. Never accept a completion note as evidence. When the deliverable is substantial (files / code / a report / an experiment), prefer spawning an independent **verifier** child (`cortex-task spawn --text "Verify <deliverable> against: <done_when>" --template <review template>`) and consume only its verdict — an independent fresh-context check catches what your anchored read misses, and keeps large deliverables out of your own context.',
|
|
61
|
+
'1. Read the actual deliverable (code, files, experiment records) and check it against the child\'s done_when. Run tests where code is involved. Never accept a completion note as evidence. When the deliverable is substantial (files / code / a report / an experiment), prefer spawning an independent **verifier** child: use the Write tool to stage its task JSON at `/tmp/cortex-task-<your Task ID>-<child-id>.json`, run `cortex-task spawn --task-file /tmp/cortex-task-<your Task ID>-<child-id>.json`, and consume only its verdict. An independent fresh-context check catches what your anchored read misses and keeps large deliverables out of your own context.',
|
|
62
|
+
],
|
|
63
|
+
[
|
|
64
|
+
'- For a quick sub-call that doesn\'t merit a full decomposition (an independent verifier pass on a child\'s deliverable, a short research probe before deciding a split), create a single child with `cortex-task spawn --text "..." --template <name>` (it hangs under you and joins via `depends_on`, like decompose) and then call `thread_wait`. It flows through the dispatch queue like any child — there is no in-process thread spawn (`thread_start` was removed; tasks are the only delegation primitive).',
|
|
65
|
+
'- For a quick sub-call that doesn\'t merit a full decomposition (an independent verifier pass on a child\'s deliverable, a short research probe before deciding a split), use the Write tool to stage one child task JSON at `/tmp/cortex-task-<your Task ID>-<unique-id>.json`, run `cortex-task spawn --task-file /tmp/cortex-task-<your Task ID>-<unique-id>.json` (it hangs under you and joins via `depends_on`, like decompose), and then call `thread_wait`. It flows through the dispatch queue like any child — there is no in-process thread spawn (`thread_start` was removed; tasks are the only delegation primitive).',
|
|
66
|
+
],
|
|
67
|
+
[
|
|
68
|
+
'1. Read the actual deliverable (code, files, experiment records) and check it against the child\'s done_when. Run tests where code is involved. Never accept a completion note as evidence. When the deliverable is substantial (files / code / a report / an experiment), prefer spawning an independent **verifier** child: use the Write tool to stage its task JSON, run `cortex-task spawn --task-file <path>`, and consume only its verdict. An independent fresh-context check catches what your anchored read misses and keeps large deliverables out of your own context.',
|
|
69
|
+
'1. Read the actual deliverable (code, files, experiment records) and check it against the child\'s done_when. Run tests where code is involved. Never accept a completion note as evidence. When the deliverable is substantial (files / code / a report / an experiment), prefer spawning an independent **verifier** child: use the Write tool to stage its task JSON at `/tmp/cortex-task-<your Task ID>-<child-id>.json`, run `cortex-task spawn --task-file /tmp/cortex-task-<your Task ID>-<child-id>.json`, and consume only its verdict. An independent fresh-context check catches what your anchored read misses and keeps large deliverables out of your own context.',
|
|
70
|
+
],
|
|
71
|
+
[
|
|
72
|
+
'- For a quick sub-call that doesn\'t merit a full decomposition (an independent verifier pass on a child\'s deliverable, a short research probe before deciding a split), use the Write tool to stage one child task JSON, run `cortex-task spawn --task-file <path>` (it hangs under you and joins via `depends_on`, like decompose), and then call `thread_wait`. It flows through the dispatch queue like any child — there is no in-process thread spawn (`thread_start` was removed; tasks are the only delegation primitive).',
|
|
73
|
+
'- For a quick sub-call that doesn\'t merit a full decomposition (an independent verifier pass on a child\'s deliverable, a short research probe before deciding a split), use the Write tool to stage one child task JSON at `/tmp/cortex-task-<your Task ID>-<unique-id>.json`, run `cortex-task spawn --task-file /tmp/cortex-task-<your Task ID>-<unique-id>.json` (it hangs under you and joins via `depends_on`, like decompose), and then call `thread_wait`. It flows through the dispatch queue like any child — there is no in-process thread spawn (`thread_start` was removed; tasks are the only delegation primitive).',
|
|
74
|
+
],
|
|
75
|
+
];
|
|
76
|
+
// STATUS.md register semantics: stock prompts used to mandate unconditional
|
|
77
|
+
// STATUS.md updates and a `## Milestone Verdict` section; the register
|
|
78
|
+
// convention makes STATUS updates conditional on a situation change and moves
|
|
79
|
+
// verdict content into the gate artifact with a one-line pointer in STATUS.
|
|
80
|
+
// One shared table — pairs that don't match a given file are no-ops.
|
|
81
|
+
export const STATUS_REGISTER_REPLACEMENTS = [
|
|
82
|
+
[
|
|
83
|
+
"Record findings, decisions, and artifacts in files as you go — not in a final summary. Update STATUS.md, the directory's CORTEX.md index, and the role's designated output artifact(s) before exiting.",
|
|
84
|
+
"Record findings, decisions, and artifacts in files as you go — not in a final summary. Update the role's designated output artifact(s) and the directory's CORTEX.md index before exiting. Update STATUS.md only if your work changed the project's situation (unblocked something, introduced a blocker, changed the next step) — STATUS is a state register, not a changelog; one line + pointer per change (see rules/status-md.md).",
|
|
85
|
+
],
|
|
86
|
+
[
|
|
87
|
+
"Prefer editing the existing project artifacts (STATUS.md, knowledge entries, the role's artifact file) over creating parallel new files.",
|
|
88
|
+
"Prefer editing the existing project artifacts (the role's artifact file, knowledge entries, existing experiment records) over creating parallel new files.",
|
|
89
|
+
],
|
|
90
|
+
[
|
|
91
|
+
"7. Update the project's `STATUS.md`; record durable findings in the project knowledge files.",
|
|
92
|
+
"7. Record durable findings in the project knowledge files. Update `STATUS.md` only if the delivered work changed the project's situation (unblocked something, introduced a blocker, changed the next step) — one line + pointer, not a completion report (see rules/status-md.md).",
|
|
93
|
+
],
|
|
94
|
+
[
|
|
95
|
+
'- **STATUS.md update**: append or replace a `## Milestone Verdict` section summarizing the verdict and the top 3 reasons. Include a timestamp and the milestone being judged.',
|
|
96
|
+
'- **STATUS.md update**: one pointer line in the register (replacing any previous milestone line): `Milestone <N> gate (<ISO date>): <verdict> → <artifact path>`. The verdict, reasons, and analysis live only in the artifact — do not copy them into STATUS.md.',
|
|
97
|
+
],
|
|
98
|
+
[
|
|
99
|
+
'- Exactly one verdict in the artifact and in STATUS.md, and they match.',
|
|
100
|
+
'- Exactly one verdict is stated, in the artifact (final line). STATUS.md carries a matching one-line pointer to the artifact, nothing more.',
|
|
101
|
+
],
|
|
102
|
+
[
|
|
103
|
+
[
|
|
104
|
+
'- STATUS.md `## Milestone Verdict` section format:',
|
|
105
|
+
' ```',
|
|
106
|
+
' ## Milestone Verdict (<ISO date>, Milestone <N>: <name>)',
|
|
107
|
+
' Verdict: <one of four>',
|
|
108
|
+
' Top reasons:',
|
|
109
|
+
' - <reason 1 with citation>',
|
|
110
|
+
' - <reason 2 with citation>',
|
|
111
|
+
' - <reason 3 with citation>',
|
|
112
|
+
' Artifact: <relative path to artifact>',
|
|
113
|
+
' ```',
|
|
114
|
+
].join('\n'),
|
|
115
|
+
[
|
|
116
|
+
"- STATUS.md pointer line format (goes under the register's current-situation or blockers section, replacing any previous milestone line):",
|
|
117
|
+
' ```',
|
|
118
|
+
' Milestone <N> gate (<ISO date>): <verdict> → <artifact path>',
|
|
119
|
+
' ```',
|
|
120
|
+
].join('\n'),
|
|
121
|
+
],
|
|
122
|
+
];
|
|
123
|
+
export const CODER_REVIEWER_COMMIT_POLICY_REPLACEMENTS = [
|
|
124
|
+
[
|
|
125
|
+
'- `git log` shows at least one commit attributable to this invocation.',
|
|
126
|
+
'- The implementation summary/artifact identifies at least one commit attributable to this invocation, and Git can verify it.',
|
|
127
|
+
],
|
|
128
|
+
[
|
|
129
|
+
'- Commits must land **before** the handoff boundary (before Engineer launches, before QA reviews, before the thread ends). Uncommitted changes at handoff are **Blockers**.',
|
|
130
|
+
REVIEWER_HANDOFF_BOUNDARY,
|
|
131
|
+
],
|
|
132
|
+
// Newline-anchored: the base sentence is a prefix of REVIEWER_HANDOFF_BOUNDARY, so an
|
|
133
|
+
// unanchored pair would re-match its own output and append the clause on every run.
|
|
134
|
+
[`${REVIEWER_HANDOFF_BOUNDARY_BASE}\n`, `${REVIEWER_HANDOFF_BOUNDARY}\n`],
|
|
135
|
+
[
|
|
136
|
+
'- Commit message should reference the spec identifier (task ID, issue reference) when one is clearly available; missing reference is a **Nice-to-have**.',
|
|
137
|
+
REVIEWER_COMMIT_RULES,
|
|
138
|
+
],
|
|
139
|
+
[
|
|
140
|
+
'- Commit message must reference the spec identifier (EXP ID, task ID, issue reference). Missing reference is a **Blocker** in research mode; **Nice-to-have** in generic mode unless a task ID was clearly available.',
|
|
141
|
+
REVIEWER_COMMIT_RULES,
|
|
142
|
+
],
|
|
143
|
+
['7. Check commit messages for spec-identifier references.', `7. ${REVIEWER_COMMIT_PROCEDURE}`],
|
|
144
|
+
['6. Check commit messages for spec-identifier references.', `6. ${REVIEWER_COMMIT_PROCEDURE}`],
|
|
145
|
+
[
|
|
146
|
+
'- **Drift you must catch for Coder**: spec improvisation, logic bugs and poor error handling in the diff, post-handoff commits, missing spec-identifier reference in commits, `--no-verify` bypass, runtime-only config.',
|
|
147
|
+
'- **Drift you must catch for Coder**: spec improvisation, logic bugs and poor error handling in the diff, post-handoff commits, `--no-verify` bypass, runtime-only config.',
|
|
148
|
+
],
|
|
149
|
+
];
|
|
@@ -7,6 +7,8 @@ declare class ThreadRepo {
|
|
|
7
7
|
private mutex;
|
|
8
8
|
/** Promise chain for `set()`/`delete()`-initiated persists, guarded by this.mutex. */
|
|
9
9
|
private _pendingPersist;
|
|
10
|
+
/** True while a persist is queued but not yet snapshotting — lets queuePersist coalesce. */
|
|
11
|
+
private _persistQueued;
|
|
10
12
|
/** Load threads from disk into memory. Populates the Map from threads.json. */
|
|
11
13
|
load(): void;
|
|
12
14
|
generateId(): ThreadId;
|
|
@@ -39,13 +41,22 @@ declare class ThreadRepo {
|
|
|
39
41
|
* Reads TASKS.yaml via the zero-dependency core parser (store → core is layer-legal). */
|
|
40
42
|
private hasLiveTaskChildren;
|
|
41
43
|
markRunningAsFailedOnStartup(): Promise<number>;
|
|
42
|
-
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
44
|
+
/** Archive terminal threads older than maxAge (default 7 days) to the JSONL archive and
|
|
45
|
+
* remove their workspace directories. Records are moved, never discarded. Auto-records
|
|
46
|
+
* (no workspace) use a shorter 24h TTL since they only need to survive !thread add chaining. */
|
|
45
47
|
cleanup(maxAgeMs?: number): Promise<number>;
|
|
48
|
+
/** Terminal records past their cutoff. Auto-records (no workspace) use the shorter TTL. */
|
|
49
|
+
private selectExpiredTerminal;
|
|
50
|
+
/** Archive expired terminal records to append-only JSONL, then drop them from the store and
|
|
51
|
+
* delete their workspace dirs. Append-then-delete: a crash can duplicate archive lines but
|
|
52
|
+
* never loses a record. If the append fails, records stay in the store (no data loss). */
|
|
53
|
+
private archiveExpiredTerminal;
|
|
46
54
|
/** Queue a persist through the mutex, chaining off any prior persist. Returns the promise.
|
|
47
55
|
* Errors are caught at the chain level so a single I/O failure does not poison all subsequent
|
|
48
|
-
* writes (returning a rejected chain would short-circuit every follow-up `.then`).
|
|
56
|
+
* writes (returning a rejected chain would short-circuit every follow-up `.then`).
|
|
57
|
+
* Coalescing: map mutations are synchronous and persist() snapshots the whole map, so any
|
|
58
|
+
* mutation made before a queued persist STARTS is covered by it. The flag resets right before
|
|
59
|
+
* the snapshot; later mutations queue a fresh persist. Collapses sync bursts to one write. */
|
|
49
60
|
queuePersist(): Promise<void>;
|
|
50
61
|
/** Atomically persist the entire Map to disk. Uses `repo.write()` (no read-modify-write needed). */
|
|
51
62
|
private persist;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// input: threads.json persistence file
|
|
2
|
-
// output: { threadStore } — Thread state in-memory cache + atomic persistence
|
|
3
|
-
// pos: Thread
|
|
2
|
+
// output: { threadStore } — Thread state in-memory cache + coalesced atomic persistence
|
|
3
|
+
// pos: Thread persistence layer: CRUD + queries; cleanup archives old terminal threads to JSONL
|
|
4
4
|
// >>> If I am updated, update my header comment and CORTEX.md <<<
|
|
5
5
|
import * as path from 'path';
|
|
6
6
|
import * as crypto from 'crypto';
|
|
7
7
|
import { readFileSync, rmSync } from 'fs';
|
|
8
|
+
import { appendFile, mkdir } from 'fs/promises';
|
|
8
9
|
import { JsonRepository } from '../core/json-repository.js';
|
|
9
10
|
import { createLogger } from '../core/log.js';
|
|
10
11
|
import { AsyncMutex } from '../core/async-mutex.js';
|
|
@@ -12,17 +13,21 @@ import { STORE_DIR } from '../core/paths.js';
|
|
|
12
13
|
import { scanAllTasks } from '../core/task-parser.js';
|
|
13
14
|
const log = createLogger('thread-store');
|
|
14
15
|
const THREADS_FILE = path.join(STORE_DIR, 'threads.json');
|
|
16
|
+
const THREADS_ARCHIVE_FILE = path.join(STORE_DIR, 'archive', 'threads-archive.jsonl');
|
|
15
17
|
class ThreadRepo {
|
|
16
18
|
/** In-memory source of truth for all thread records. All sync reads come from here. */
|
|
17
19
|
map = new Map();
|
|
18
20
|
repo = new JsonRepository({
|
|
19
21
|
filePath: THREADS_FILE,
|
|
20
22
|
defaultValue: () => ({}),
|
|
23
|
+
compact: true, // multi-MB store: pretty-printing costs ~40% extra sync stringify per write
|
|
21
24
|
});
|
|
22
25
|
/** Serializes all persist operations (set, delete, mutate, lifecycle). */
|
|
23
26
|
mutex = new AsyncMutex();
|
|
24
27
|
/** Promise chain for `set()`/`delete()`-initiated persists, guarded by this.mutex. */
|
|
25
28
|
_pendingPersist = Promise.resolve();
|
|
29
|
+
/** True while a persist is queued but not yet snapshotting — lets queuePersist coalesce. */
|
|
30
|
+
_persistQueued = false;
|
|
26
31
|
// --- Lifecycle ---
|
|
27
32
|
/** Load threads from disk into memory. Populates the Map from threads.json. */
|
|
28
33
|
load() {
|
|
@@ -174,9 +179,9 @@ class ThreadRepo {
|
|
|
174
179
|
return count;
|
|
175
180
|
});
|
|
176
181
|
}
|
|
177
|
-
/**
|
|
178
|
-
*
|
|
179
|
-
*
|
|
182
|
+
/** Archive terminal threads older than maxAge (default 7 days) to the JSONL archive and
|
|
183
|
+
* remove their workspace directories. Records are moved, never discarded. Auto-records
|
|
184
|
+
* (no workspace) use a shorter 24h TTL since they only need to survive !thread add chaining. */
|
|
180
185
|
async cleanup(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
181
186
|
await this._pendingPersist;
|
|
182
187
|
return this.mutex.run(async () => {
|
|
@@ -213,37 +218,69 @@ class ThreadRepo {
|
|
|
213
218
|
}
|
|
214
219
|
if (staleWaiting > 0)
|
|
215
220
|
log.info(`Failed ${staleWaiting} stale waiting threads (leak safety net)`);
|
|
216
|
-
|
|
217
|
-
const isTerminal = record.status === 'completed' || record.status === 'failed'
|
|
218
|
-
|| record.status === 'cancelled' || record.status === 'aborted';
|
|
219
|
-
const isAutoRecord = !record.workspacePath;
|
|
220
|
-
const effectiveCutoff = isAutoRecord ? autoRecordCutoff : cutoff;
|
|
221
|
-
if (isTerminal && record.updatedAt < effectiveCutoff) {
|
|
222
|
-
if (record.workspacePath) {
|
|
223
|
-
try {
|
|
224
|
-
rmSync(record.workspacePath, { recursive: true, force: true });
|
|
225
|
-
}
|
|
226
|
-
catch { }
|
|
227
|
-
}
|
|
228
|
-
this.map.delete(id);
|
|
229
|
-
count++;
|
|
230
|
-
}
|
|
231
|
-
}
|
|
221
|
+
count = await this.archiveExpiredTerminal(cutoff, autoRecordCutoff);
|
|
232
222
|
if (count > 0 || staleWaiting > 0) {
|
|
233
223
|
await this.persist();
|
|
234
224
|
if (count > 0)
|
|
235
|
-
log.info(`
|
|
225
|
+
log.info(`Archived ${count} old threads to ${THREADS_ARCHIVE_FILE} (workspaces removed)`);
|
|
236
226
|
}
|
|
237
227
|
return count;
|
|
238
228
|
});
|
|
239
229
|
}
|
|
230
|
+
/** Terminal records past their cutoff. Auto-records (no workspace) use the shorter TTL. */
|
|
231
|
+
selectExpiredTerminal(cutoff, autoRecordCutoff) {
|
|
232
|
+
const expired = [];
|
|
233
|
+
for (const record of this.map.values()) {
|
|
234
|
+
const isTerminal = record.status === 'completed' || record.status === 'failed'
|
|
235
|
+
|| record.status === 'cancelled' || record.status === 'aborted';
|
|
236
|
+
const effectiveCutoff = record.workspacePath ? cutoff : autoRecordCutoff;
|
|
237
|
+
if (isTerminal && record.updatedAt < effectiveCutoff)
|
|
238
|
+
expired.push(record);
|
|
239
|
+
}
|
|
240
|
+
return expired;
|
|
241
|
+
}
|
|
242
|
+
/** Archive expired terminal records to append-only JSONL, then drop them from the store and
|
|
243
|
+
* delete their workspace dirs. Append-then-delete: a crash can duplicate archive lines but
|
|
244
|
+
* never loses a record. If the append fails, records stay in the store (no data loss). */
|
|
245
|
+
async archiveExpiredTerminal(cutoff, autoRecordCutoff) {
|
|
246
|
+
const expired = this.selectExpiredTerminal(cutoff, autoRecordCutoff);
|
|
247
|
+
if (expired.length === 0)
|
|
248
|
+
return 0;
|
|
249
|
+
try {
|
|
250
|
+
await mkdir(path.dirname(THREADS_ARCHIVE_FILE), { recursive: true });
|
|
251
|
+
await appendFile(THREADS_ARCHIVE_FILE, expired.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
|
|
252
|
+
}
|
|
253
|
+
catch (err) {
|
|
254
|
+
log.error(`Thread archive append failed — keeping ${expired.length} record(s): ${err.message}`);
|
|
255
|
+
return 0;
|
|
256
|
+
}
|
|
257
|
+
for (const record of expired) {
|
|
258
|
+
if (record.workspacePath) {
|
|
259
|
+
try {
|
|
260
|
+
rmSync(record.workspacePath, { recursive: true, force: true });
|
|
261
|
+
}
|
|
262
|
+
catch { }
|
|
263
|
+
}
|
|
264
|
+
this.map.delete(record.id);
|
|
265
|
+
}
|
|
266
|
+
return expired.length;
|
|
267
|
+
}
|
|
240
268
|
/** Queue a persist through the mutex, chaining off any prior persist. Returns the promise.
|
|
241
269
|
* Errors are caught at the chain level so a single I/O failure does not poison all subsequent
|
|
242
|
-
* writes (returning a rejected chain would short-circuit every follow-up `.then`).
|
|
270
|
+
* writes (returning a rejected chain would short-circuit every follow-up `.then`).
|
|
271
|
+
* Coalescing: map mutations are synchronous and persist() snapshots the whole map, so any
|
|
272
|
+
* mutation made before a queued persist STARTS is covered by it. The flag resets right before
|
|
273
|
+
* the snapshot; later mutations queue a fresh persist. Collapses sync bursts to one write. */
|
|
243
274
|
queuePersist() {
|
|
275
|
+
if (this._persistQueued)
|
|
276
|
+
return this._pendingPersist;
|
|
277
|
+
this._persistQueued = true;
|
|
244
278
|
this._pendingPersist = this._pendingPersist
|
|
245
279
|
.catch(() => { })
|
|
246
|
-
.then(() => this.mutex.run(() =>
|
|
280
|
+
.then(() => this.mutex.run(() => {
|
|
281
|
+
this._persistQueued = false;
|
|
282
|
+
return this.persist();
|
|
283
|
+
}))
|
|
247
284
|
.catch((err) => { log.error('persist failed:', err); });
|
|
248
285
|
return this._pendingPersist;
|
|
249
286
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// input: versions, user config,
|
|
1
|
+
// input: versions, user config, defaults, prompt replacements
|
|
2
2
|
// output: Versioned and collision-safe startup migrations
|
|
3
3
|
// pos: Migrates user-owned files during server startup
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
@@ -11,6 +11,7 @@ import { atomicWrite } from '../core/atomic-write.js';
|
|
|
11
11
|
import { createLogger } from '../core/log.js';
|
|
12
12
|
import { validateHookEntry } from './hook-registry.js';
|
|
13
13
|
import { migrateProviderStateFromSchedules } from './provider-state-repo.js';
|
|
14
|
+
import { CODER_COMMIT_POLICY_REPLACEMENTS, CODER_REVIEWER_COMMIT_POLICY_REPLACEMENTS, MANAGER_TASK_FILE_REPLACEMENTS, STATUS_REGISTER_REPLACEMENTS, } from './prompt-migration-replacements.js';
|
|
14
15
|
const log = createLogger('version-migrations');
|
|
15
16
|
// ── CalVer comparison ──────────────────────────────────────────
|
|
16
17
|
// CalVer format: YYYY.M.D (no zero-padding, e.g. 2026.5.23).
|
|
@@ -336,6 +337,40 @@ const migrations = [
|
|
|
336
337
|
return applyReplacements(data, PI_SUBAGENT_ROLE_REPLACEMENTS);
|
|
337
338
|
},
|
|
338
339
|
})),
|
|
340
|
+
// M7: Align coder-review commit attribution with repository policy.
|
|
341
|
+
{
|
|
342
|
+
filePath: 'prompts/directives/coder-reviewer.md', version: '2026.7.31', format: 'text',
|
|
343
|
+
migrate: (data) => typeof data === 'string'
|
|
344
|
+
? applyReplacements(data, CODER_REVIEWER_COMMIT_POLICY_REPLACEMENTS) : data,
|
|
345
|
+
},
|
|
346
|
+
// M8: Move stock manager task creation off shell-interpolated arguments.
|
|
347
|
+
{
|
|
348
|
+
filePath: 'prompts/directives/manager.md', version: '2026.7.31', format: 'text',
|
|
349
|
+
migrate: (data) => typeof data === 'string'
|
|
350
|
+
? applyReplacements(data, MANAGER_TASK_FILE_REPLACEMENTS) : data,
|
|
351
|
+
},
|
|
352
|
+
// M9: Align coder commit instructions with repository privacy policy.
|
|
353
|
+
{
|
|
354
|
+
filePath: 'prompts/directives/coder.md', version: '2026.7.31', format: 'text',
|
|
355
|
+
migrate: (data) => typeof data === 'string'
|
|
356
|
+
? applyReplacements(data, CODER_COMMIT_POLICY_REPLACEMENTS) : data,
|
|
357
|
+
},
|
|
358
|
+
// M10: STATUS.md register semantics. Stock prompts mandated unconditional
|
|
359
|
+
// STATUS.md updates (worker exit checklist, manager step 7) and a
|
|
360
|
+
// `## Milestone Verdict` STATUS section (director); the register convention
|
|
361
|
+
// makes STATUS updates conditional and keeps verdicts in the gate artifact.
|
|
362
|
+
// Idempotent via applyReplacements; customized copies don't match → no-op.
|
|
363
|
+
...[
|
|
364
|
+
'prompts/systemPrompts/worker.md',
|
|
365
|
+
'prompts/directives/manager.md',
|
|
366
|
+
'prompts/directives/director.md',
|
|
367
|
+
].map((filePath) => ({
|
|
368
|
+
filePath,
|
|
369
|
+
version: '2026.8.2',
|
|
370
|
+
format: 'text',
|
|
371
|
+
migrate: (data) => typeof data === 'string'
|
|
372
|
+
? applyReplacements(data, STATUS_REGISTER_REPLACEMENTS) : data,
|
|
373
|
+
})),
|
|
339
374
|
];
|
|
340
375
|
// ── Versions file I/O ──────────────────────────────────────────
|
|
341
376
|
async function loadVersionsFrom(filePath) {
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema_version": "cortex-supervisor-build/1",
|
|
3
|
+
"artifact": "dist/cortex-supervisor",
|
|
4
|
+
"source_files": [
|
|
5
|
+
"build.sh",
|
|
6
|
+
"src/cli.c",
|
|
7
|
+
"src/cli.h",
|
|
8
|
+
"src/main.c",
|
|
9
|
+
"src/process-tree.c",
|
|
10
|
+
"src/process-tree.h",
|
|
11
|
+
"src/protocol.c",
|
|
12
|
+
"src/protocol.h",
|
|
13
|
+
"src/supervisor.c",
|
|
14
|
+
"src/supervisor.h"
|
|
15
|
+
],
|
|
16
|
+
"source_sha256": "71faacfb6f6ce255574c93db2e07ca37d9cd43d769033bc4f6518301b35d6306",
|
|
17
|
+
"binary_sha256": "e44280a45b5a7155d619c2184bb775fd53d44208ffaea8069568c62d32fe5d99",
|
|
18
|
+
"target_arch": "x86_64",
|
|
19
|
+
"target_triple": "x86_64-linux-gnu",
|
|
20
|
+
"compiler": "gcc 13.3.0",
|
|
21
|
+
"libc": { "name": "glibc", "version": "2.39", "linkage": "static" }
|
|
22
|
+
}
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortex-agent/server",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.8.3-2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Autonomous agent system for long-running projects — mission-driven, multi-agent pipelines, self-evolving skills.",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"files": [
|
|
18
18
|
"dist/",
|
|
19
19
|
"defaults/",
|
|
20
|
+
"native/cortex-supervisor/dist/",
|
|
20
21
|
"web/dist/",
|
|
21
22
|
"scripts/postinstall-restart-trigger.mjs",
|
|
22
23
|
"README.md"
|
|
@@ -26,9 +27,11 @@
|
|
|
26
27
|
},
|
|
27
28
|
"scripts": {
|
|
28
29
|
"prepare": "cp ../README.md . && npm run build",
|
|
29
|
-
"prepack": "node scripts/copy-web-dist.js",
|
|
30
|
+
"prepack": "npm run build:supervisor && node scripts/copy-web-dist.js",
|
|
30
31
|
"postinstall": "node scripts/postinstall-restart-trigger.mjs",
|
|
31
32
|
"build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && node scripts/copy-assets.js",
|
|
33
|
+
"build:supervisor": "bash native/cortex-supervisor/build.sh",
|
|
34
|
+
"benchmark:pi-provider-discovery": "node --import tsx scripts/benchmark-pi-provider-discovery.ts",
|
|
32
35
|
"typecheck": "tsc --noEmit",
|
|
33
36
|
"test": "bash scripts/run-tests.sh",
|
|
34
37
|
"test:quick": "bash scripts/run-tests.sh --quick",
|