iguowz/dsh-cortex

iguowz/dsh-cortexx

DeepSeek-Harness 多模型编排插件,支持递归任务拆解、动态路由、质量门控、失败恢复与 KPI 报表。

工作流与自动化dsh

Cortex — Multi-Model Orchestration & Evaluation for DeepSeek-Harness

English | 中文 | npm package | GitHub

Cortex is a DeepSeek-Harness plugin that turns the host's primary (strong) model into a high-leverage supervisor. The supervisor plans, decomposes, verifies and accepts; routed executor models (small/cheap models such as Qwen3.8-9B) and tools do the heavy lifting. With a recursive task tree, dynamic routing, four-stage quality gates, budget control, failure recovery, policy reuse and per-dimension model evaluation, Cortex keeps quality stable while driving the unit cost of successful tasks down.

The supervisor is the host primary model that drives the cortex_* tools (e.g. deepseek-v4-pro in the bundled registry), and executors are the models the dynamic router picks per subtask (L1/L2 tiers, e.g. Qwen3.8-9B).

Suggested repository topics (GitHub): dsh-plugin · dsh · cordis · llm-orchestration · multi-model · model-routing · quality-gate


Highlights

CapabilityEntryNotes
Task intelligencecortex_startProfile → fingerprint → strategy match (≥0.90 reuse / 0.70~0.90 light-check / <0.70 replan) → budget pool → granularity check
Recursive task treecortex_decomposeSafety limits: maxDepth 6 / maxTotalNodes 50 / maxChildrenPerNode 10 / maxReplan 3; DAG depends_on; aggregate nodes merge children by node schema + Gate0, active-model only
Recursive executioncortex_execute recursiveReady leaves auto-scheduled, aggregate nodes merged; evaluate:gate2 / multi_vote pass through — same standard as manual batch
Cachingengine built-inL1 exact + L2 semantic (near-duplicate text similarity, conservative 0.88 threshold, skip-able) + L3 cross-task component reuse
Drift & valueengine built-inModel drift monitoring vs static baseline (auto routing penalty, surfaced in registry/matrix) + value score & Pareto frontier per evaluation run
Dynamic routingcortex_executeCandidate filter → utility scoring (quality/success/risk − cost/latency/failure) → MQC upgrade gate; costFirst / balanced / qualityFirst; multi-model vote
Quality gatesGate0 deterministic · Gate1 self-check · Gate2 evaluator · Gate3 cortex_review · Gate3.5 red-teamHard fails: format_validity / safety / groundedness < 0.5; review decisions carry node quality/Gate1 context snapshots; red-team adversarially challenges high-impact acceptances (S/M, risk≥0.5 or quality≥0.9) — material defect → downgrade to retry
Recovery enginecortex_recoverFailure taxonomy → retry / switch / prompt-fix / decompose / upgrade / human + failure-pattern learning
Soft-defect correctioncortex_execute / cortex_recoverSoft cap max_delegations (default 3): a capable-but-insufficient result is corrected in place (same model → better model → escalate to supervisor); optional continuable sub-session (config.continuableCorrection) keeps context across rounds; hard failures still use type-based recovery
Price overridecortex_models / UI / CLISet/clear a model's effective price (price/clear_price, or `/cortex models set-price
Budget controlengine built-in4 pools (10/70/10/10), STOP-1..4 (STOP-2 from observed MQC — real ΔQ/ΔC, not hard-coded), 90% high-cost lock, degraded mode
Model evaluationcortex_evaluate7-dim scoring per case; per-model × task-type × capability × 7-dim profile (dims_profile, EMA, persisted across restarts; also fed by production Gate2/cortex_review dims); dynamic capabilities (profile-thresholded caps auto-register into the catalog and union with static capabilities at routing); Rule-First deterministic correctness for structured expected; UI one-click run; value score (Q×SR/Cost) + Pareto frontier; drift monitoring (vs static baseline → automatic routing penalty)
Model registrycortex_models (config/models.yaml)Static YAML + DSH ctx.llm dynamic discovery + enable/disable management; routing scores (ranking preview)
Policy centercortex_policy / cortex_strategy_matchFingerprint similarity, versioned policies, template families with metric-driven grayscale, skip-level tree suggestions
Organization mode (probes & governance)cortex_start.organization_mode / cortex_probeThe organization mode is a task property (standard / department / auto — auto decides by difficulty = max(complexity, scale, risk) against organizationAutoThreshold 0.75; an explicit declaration always wins). Department mode layers 8 built-in probes (requirements/engineering/testing/security/compliance/release/operations/knowledge, append-only custom ones) with scope, tool ceiling, quality floor, budget share and authority tiers P0–P4 (observe/advise/execute/decide/veto), Rule-First fail-closed governance (pass/review/veto → blocked_by_veto freezes the node and its downstream), a hash-chained ledger (governance.jsonl, verifiable), event bus × probe subscriptions → deterministic to-dos (intents.jsonl), adversarial governance review, critical-op approval chain, probe budget hard quota, priority dispatch and ROI ranking — all ledgered, all opt-in per task
Human-in-the-loopengine + cortex_probe interactionsWhen a rule says a human must answer (critical-op approval / veto confirmation / arbitration / human review / supervisor escalation / probe budget), the engine records the question + options + suggested action and, on unattended paths, wakes the conversation so the supervisor asks the user (deduped, batched, delivery recorded: interactions.jsonl); nothing is decided silently
KPIcortex_reportSupervisor calls/task, A-cost breakdown by call kind (start/decompose/review/…) (aByKind), supervisor leverage, saving vs direct primary-model run (negative → orchestration warning), quality, policy reuse rate, node autonomy rate / S-tier cost share / voting & engine-compute stats / admission queue
Phase-3 control planecortex_execute.control / UI / CLIAdmission queue (global + per-task limits, round-robin so big tasks cannot starve small ones), workflow control (pause / resume / terminate / isolate a node's call chain — in-flight calls cancelled, no false failure statuses), review protocols & prompt templates (versioned, append-only, with a contract-gap self-check)
Self-tuningUI “Learn chain” / /cortexBounded parameter proposals derived from recorded evidence (KPI / queue / execution profiles / learning-chain samples), applied only on explicit click with a confidence threshold and a per-run cap, every change ledgered; routing-weight learning (suggest/apply/rollback), budget rebalancing ledger, evaluator-calibration samples, audit snapshots
Web console/cortex ui / 8788Trends / timeline / model registry / capability matrix (4 metrics + 7-dim rows) / evaluation center / L0 tools / learning chain / departments, i18n zh+en follows the DSH General-settings language (the console reads and writes the same locale setting, the header button writes it back through the official settings service, every open console follows over SSE; a console without the settings service reads the document read-only and says so), light/dark theme, CNY/USD display, SSE live updates; no global organization-mode indicator (mode is a task property), department tasks badged per row
Watchdog/cortex watchdog / /watchdogCross-workspace timed task injection + goal-reached auto-iteration: schedule (--at/--after/--every, every ≥300s) injected via the official inbox channel (agent.followup — never writes session events), goal-loop (set goals; after an injected/executed task, the strong model objectively evaluates the conversation against the goals and re-injects improvement guidance until met (met+score double gate) or maxRounds reached), task-list (ordered task chain, each auto-advanced after the previous completes); work windows (global ws window <HH:MM-HH:MM>, cross-midnight/days supported), startAt/endAt, cross-workspace (ws:/session:/workspaceId/workspacePath targets); web console /watchdog + /api/watchdog/*; consecutive eval failures terminalize to failed (observable)

Recent Changes

A condensed log of the capabilities added after the initial release (full per-round evidence lives in docs/开发任务清单.md):

  • Organization mode — department probes & governance (cortex_probe, cortex_start.organization_mode): the mode is a task property (standard / department / auto = engine decides by difficulty = max(complexity, scale, risk), threshold organizationAutoThreshold 0.75; an explicit declaration always wins; domain/capability tags deliberately do not count as difficulty signals). Department mode adds 8 built-in probes (append-only custom), authority tiers P0–P4, Rule-First fail-closed governance (pass/review/veto, veto freezes the node and its downstream, cleared only by an explicit lift), a hash-chained ledger (governance.jsonl, verify-able), event bus × subscriptions → deterministic to-dos, adversarial governance review, a critical-op approval chain (veto-lift / P4 grant / enabling governance suspend until approved), a probe budget hard quota, priority dispatch and ROI ranking. Department mode is a layer on top of standard mode — it never introduces its own model pool, filter or routing criterion.
  • Human-in-the-loop: questions the rules say a human must answer (critical-op approval / veto confirmation / arbitration / human review / supervisor escalation / probe budget) are recorded with options + a suggested action, and on unattended paths the engine wakes the conversation so the supervisor asks the user — deduped, batched, delivery recorded; the console deliberately keeps no second to-do inbox (questions are asked in the conversation; data plane /api/interactions and cortex_probe interactions remain for scripts).
  • Phase-3 control plane: admission queue (global + per-task, round-robin), workflow control (pause/resume/terminate/per-node isolate), review protocols & prompt templates (versioned, append-only, contract-gap self-check), self-tuning proposals with guardrails + ledger, routing-weight learning, budget rebalancing and audit snapshots — all observable in the console's “Learn chain” tab and reachable from /cortex control|tune|org|gate|protocols.
  • Console language follows DSH General settings: lib/locale.js reads the host locale preference (settings service first, settings.yaml read-only fallback) and writes it back through the official settings service; the header button switches it, every open console follows over SSE (with a storage-event/heartbeat fallback so a missing host event can never silently strand the page), and the first paint already carries the language. The session “Tasks” panel registers one cortex dictionary (zh+en) and renders every label/status/button through it.
  • Console simplification: the global organization-mode switch and the “default mode” badge are gone (mode is per task; each task row still shows its own mode badge), the “needs your action” block is gone, and the remaining panels (probes / responsibility matrix / authority / ledger / dispatch / to-dos / ROI / learning chain / L0 / evaluation) are all business-worded with no raw JSON and no framework names.
  • Quality & routing depth: Gate3.5 red-team, per-dimension capability profiles (dims_profile, EMA) fed by evaluation and production Gate2/review, drift monitoring with automatic routing penalties, value score + Pareto frontier, static-baseline reset, effective price override (3-tier priority), L1/L2/L3 cache, deterministic statistics via type:"compute" engine nodes, and an L0 deterministic tool library that is generated and sandbox-verified at runtime.
  • Maintainability pass: shared numeric helpers (lib/engine/util.js) replace nine sets of duplicated implementations; the browser bundle's UI text lives in one dictionary (a regression test forbids hard-coded Chinese in the bundle); dead exports/CSS/scripts were removed with evidence.

Install & Auto-Enable

dsh plugin is the supported way: it installs the package into the profile, and because this package declares dsh.bundle.patch (= cordis.patch.yml), it is automatically appended to dsh.profile.bundles — enabled on next boot with no manual profile edits.

From npm (published):

# install the plugin package as a dependency
yarn add dsh-cortex            # or: npm install dsh-cortex

# register it into a DSH profile and boot
npx @deepseek-ai/dsh plugin --profile web add dsh-cortex
npx @deepseek-ai/dsh web        # boot — the 13 cortex_* tools are live

From a local checkout (development):

cd <repo-path>                                   # the repo root
npx @deepseek-ai/dsh plugin --profile web add .  # anchors to this dir (or pass the absolute path)
npx @deepseek-ai/dsh web

Remove: npx @deepseek-ai/dsh plugin --profile web remove dsh-cortex.

The shipped bundle patch inserts the cortex row with uiEnabled: true, uiPort: 8788 (console listens on loopback only). stateDir and modelsFile use built-in defaults ($DSH_HOME/storages/cortex and the bundled config/models.yaml) — anything can be overridden by an - id: cortex config row in your profile's own cordis.patch.yml (it applies after bundle layers).

Typical Flow (agent view)

cortex_start → (cortex_strategy_match) → cortex_decompose T0 → cortex_execute [node_ids | recursive]
→ cortex_review (batch accept) → cortex_recover (on failures) → cortex_report (KPI) → cortex_policy (settle)

Operations & Commands

1. Agent tools (14 — the supervisor calls them autonomously)

ToolPurposeKey parameters
cortex_startCreate a task (profile → fingerprint → strategy match → budget pool)goal, profile{task_type, domain, complexity, risk, quality_requirement, budget_limit, input_tokens?, expected_output_tokens?, latency_requirement_ms?, language?, capability?}, input, organization_mode? (standard|department|auto — per-task; explicit wins over auto; the reply carries organizationMode{mode,source,reason,difficulty?})
cortex_strategy_matchPolicy-center lookup (3-tier reuse verdict)profile
cortex_decomposeSplit a parent node (safety limits / DAG / replace; large-text split: children[].split {count?, by?} auto-splits into N parallel shard executors + 1 aggregator)task_id, parent_id?, replace?, children[{goal, task_type, capability, output_schema, quality_target?, tool_allow?, depends_on?, type?, split?}]
cortex_executeRoute & execute (Gate0/1[/2], cache, accounting)task_id, node_id?/node_ids?, recursive?, mode? (costFirst
cortex_reviewGate3 batch acceptance (decisions carry quality/self-check snapshots; Gate3.5 red-team)task_id, decisions[{node_id, status, reason_code?, missing_items?, next_action, recommended_depth?, confidence?}], auto?, red_team?
cortex_probeDepartments & governance (probes / per-task mode / authority tiers / ledger / dispatch / ROI / to-dos & approvals / interactions / veto-lift / budget)action (list|show|add|enable|disable|policy|assign|mode|authority|authority-reset|ledger|verify|dispatch|roi|intents|intent-ack|intent-resolve|interactions|interaction-ack|interaction-resolve|subscriptions|approve|veto|lift), task_id?, node_id?, probe_id?, mode?, policy?, reason?
cortex_recoverRecovery decision tree (retry/switch/upgrade re-run in-engine)task_id, node_id?
cortex_policySettle a policy from a successful tasktask_id, note?
cortex_reportKPI report (per task or global)task_id?
cortex_modelsModel registry / profiles / routing scores / drift / price overridetask_type?, capability?, model?, enabled?, refresh?, reset?, price?, clear_price?
cortex_evaluateModel evaluation (7-dim × capability profiles, value/Pareto)cases?, use_saved?, models?, task_type?, quality_target?
cortex_eval_casesEval-case library (page + conversation shared)action? (list
cortex_capabilitiesCapability catalog (append-only)action? (list
cortex_l0L0 deterministic tool library (list/show/add/remove/generate/run)action?, keywords, allowed?

2. Slash commands (/cortex <subcommand>)

CommandWhat it does
/cortex statusEngine state: tasks (running), nodes, attempts, policies, models, discipline status
/cortex task <id>Task tree (profile/strategy/budget/nodes)
/cortex trace <id>Execution trail (attempts + decisions)
/cortex kpi [id]KPI report (global or per task)
/cortex models [enable|disable <id>|refresh|reset|set-price <id> <in> <out> [cached]|clear-price <id>]Registry listing; reset clears evaluation feedback; enable/disable toggles; refresh re-discovers dynamic models; set-price/clear-price set/clear a model's effective price (persisted, 3-tier priority)
`/cortex policies [disableenable ]`
/cortex model-pref [set <id> [reason]|clear|show]Set/clear the preferred executor model with preference content (reason = which tasks it suits): routing adopts it when the task scene is covered by the content (>=50%) + active + quality <0.9 (user preference is authoritative — capability tags are advisory only, prefCapabilityMismatch audited; failed executions auto-upgrade via the recovery engine); persisted; same as page ★
/cortex l0L0 deterministic tool library (list/show/remove/generate/run)
/cortex rate [refresh]USD→CNY rate (refresh forces fetch)
/cortex resetDelete state files + clear in-memory store + reload static registry + immediately re-discover models from DSH (no host restart needed); newly discovered third-party models are dedup-merged into config/models.yaml (append-only, comments preserved) so they join the static registry permanently
`/cortex ui startstop
/cortex watchdog <add task|add goal|list|rm|pause|resume|run|goal|ws|ui>Watchdog: cross-workspace scheduled task injection (at/after/every, ≥300s) + goal-loop auto evaluation & remediation until reached (startAt/endAt optional; global work window 09:00–18:00; ws window to set/clear; consecutive eval failures terminalize to "failed" for visibility)
/cortex routing [suggest|show|apply|rollback]Route-weight learning: sample-driven weights suggestion (suggest), show current, one-click apply, rollback — automation driven by per-node routing samples + drift
/cortex budgetBudget rebalancing: shared-pool balance + ledger (dynamic reclaim/re-distribution)
/cortex calibrationEvaluator-calibration chain (historical contradictory samples across review vs self-check vs terminal state)
/cortex org [mode <standard|department|auto> [task]|dispatch [task]|roi [task]|intents|ledger [probe]]Departments & governance: per-task mode (or global default), priority dispatch, department ROI, to-dos/approvals, ledger view
/cortex gate <interactions|approve|veto|lift|protocols>Governance gate: pending human questions, approve a suspended critical op, explicit veto / lift, review protocols & prompt templates
/cortex control <status|pause|resume|terminate|isolate|unisolate|purge> [task] [node]Phase-3 workflow control (admission queue snapshot + per-task/per-node control), audit purge
/cortex tune [apply|history]Self-tuning proposals (dry-run by default) / apply with guardrails / ledger
/cortex helpCommand usage

3. Console REST (127.0.0.1:8788)

GET  /api/overview · /api/timeline?hours=all|24|168 · /api/rate · /api/models
     /api/matrix · /api/evaluations · /api/eval-cases · /api/capabilities
     /api/evaluate/status · /api/task/<id> · /api/tasks?limit&session · /api/events (SSE live)
     /api/organization[?dispatch=<taskId>] · /api/interactions · /api/control
     /api/protocols[?task=<id>] · /api/tune · /api/budget · /api/routing
     /api/kpi-snapshots · /api/lang · /api/watchdog/calibration
POST /api/models/<id>            {enabled?: boolean, preferred?: boolean, reason?: string}   // reason = preference content (required on the page)
     /api/matrix/reset           (clear evaluation feedback)
     /api/eval-cases             {action: add|remove|save, ...}
     /api/capabilities           {name, description?}
     /api/evaluate               {models?, cases?, use_saved?} (real background run)
     /api/tasks/<id>             (DELETE — remove a history task with its nodes/attempts)
     /api/tasks/<id>/control     {action: pause|resume|terminate|isolate|unisolate}
     /api/control/purge          {kinds?, reason?}        (audit-purge, itself ledgered)
     /api/organization           {action: mode|assign|approve|intent-ack|intent-resolve|interaction-ack|interaction-resolve, ...} (whitelisted)
     /api/interactions           {action: ack|resolve, id, note?}
     /api/protocols              {protocol?|template?}   (versioned append-only writes)

     /api/lang                   GET  → {value, writable, pushed, settingsFile}   (console language follows DSH General settings)
                                 POST {lang} → writes the host `locale` setting through the official settings service
     /api/watchdog               {action: add-task|add-goal|pause|resume|remove|run|window-set|window-clear|ws-add, ...} (whitelisted)
GET  /watchdog · /api/watchdog/rules|runs?limit=50|targets|windows   (watchdog page, uses /api/events SSE)

4. Runtime lifecycle