@cortex-agent/server 2026.6.22 → 2026.6.24

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.
Files changed (95) hide show
  1. package/defaults/config/thread-templates.json +12 -6
  2. package/defaults/context/user/CORTEX.md +2 -2
  3. package/defaults/hooks/ask-user-question-hook.mjs +1 -0
  4. package/defaults/hooks/exit-plan-mode-hook.mjs +1 -0
  5. package/defaults/hooks/memory-ref-tracker.mjs +1 -0
  6. package/defaults/hooks/new-session-hook.mjs +1 -0
  7. package/defaults/hooks/post-task-hook.mjs +1 -0
  8. package/defaults/hooks/rules-loader.mjs +1 -0
  9. package/defaults/hooks/sensitive-file-edit.mjs +1 -0
  10. package/defaults/hooks/session-activity-tracker.mjs +1 -0
  11. package/defaults/hooks/task-status-check.mjs +1 -0
  12. package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
  13. package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
  15. package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
  16. package/defaults/prompts/directives/coder-reviewer.md +6 -6
  17. package/defaults/prompts/directives/coder.md +14 -15
  18. package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
  19. package/dist/agent-adapter/claude/adapter-tui.js +15 -0
  20. package/dist/agent-adapter/claude/adapter.js +6 -2
  21. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +8 -0
  22. package/dist/agent-adapter/claude/bg-task-tracker.js +18 -5
  23. package/dist/core/gateway-generator.js +10 -1
  24. package/dist/core/locales/en.d.ts +6 -0
  25. package/dist/core/locales/slices/interactions.d.ts +6 -0
  26. package/dist/core/locales/slices/interactions.js +14 -0
  27. package/dist/core/status-format.d.ts +14 -0
  28. package/dist/core/status-format.js +23 -1
  29. package/dist/core/types/thread-types.d.ts +3 -0
  30. package/dist/domain/agents/facade.d.ts +13 -0
  31. package/dist/domain/agents/facade.js +24 -1
  32. package/dist/domain/mcp/feishu/index.js +5 -51
  33. package/dist/domain/mcp/feishu-server.js +3 -2
  34. package/dist/domain/memory/user-context.d.ts +6 -5
  35. package/dist/domain/memory/user-context.js +12 -7
  36. package/dist/domain/remote/client-hot-reload.d.ts +9 -2
  37. package/dist/domain/remote/client-hot-reload.js +77 -6
  38. package/dist/domain/scheduling/jobs/task-dispatch.js +1 -0
  39. package/dist/domain/sessions/session-hooks.d.ts +31 -1
  40. package/dist/domain/sessions/session-hooks.js +69 -17
  41. package/dist/domain/system/doctor.d.ts +63 -0
  42. package/dist/domain/system/doctor.js +362 -0
  43. package/dist/domain/tasks/system/task-cli.js +7 -4
  44. package/dist/domain/tasks/system/task-state.d.ts +10 -1
  45. package/dist/domain/tasks/system/task-state.js +31 -1
  46. package/dist/domain/threads/prompt-builder.d.ts +7 -4
  47. package/dist/domain/threads/prompt-builder.js +9 -8
  48. package/dist/domain/threads/runner.js +30 -7
  49. package/dist/entry/app.js +38 -14
  50. package/dist/entry/cli.js +10 -0
  51. package/dist/entry/doctor-cli.d.ts +12 -0
  52. package/dist/entry/doctor-cli.js +76 -0
  53. package/dist/hooks/ask-user-question-hook.mjs +1 -0
  54. package/dist/hooks/exit-plan-mode-hook.mjs +1 -0
  55. package/dist/hooks/memory-ref-tracker.mjs +1 -0
  56. package/dist/hooks/new-session-hook.mjs +1 -0
  57. package/dist/hooks/post-task-hook.mjs +1 -0
  58. package/dist/hooks/rules-loader.mjs +1 -0
  59. package/dist/hooks/sensitive-file-edit.mjs +1 -0
  60. package/dist/hooks/session-activity-tracker.mjs +1 -0
  61. package/dist/hooks/task-status-check.mjs +1 -0
  62. package/dist/hooks/tasks-yaml-guard.mjs +1 -0
  63. package/dist/orchestration/agent-runner.js +3 -2
  64. package/dist/orchestration/conversation-runner.js +4 -1
  65. package/dist/orchestration/lifecycle.d.ts +2 -1
  66. package/dist/orchestration/lifecycle.js +15 -1
  67. package/dist/orchestration/manager-qa.d.ts +3 -2
  68. package/dist/orchestration/manager-qa.js +17 -12
  69. package/dist/orchestration/resume-dispatcher.d.ts +5 -0
  70. package/dist/orchestration/resume-dispatcher.js +38 -22
  71. package/dist/orchestration/thread-callback.d.ts +7 -3
  72. package/dist/orchestration/thread-callback.js +39 -35
  73. package/dist/store/plugin-sync.d.ts +21 -0
  74. package/dist/store/plugin-sync.js +119 -0
  75. package/dist/store/version-migrations.d.ts +9 -0
  76. package/dist/store/version-migrations.js +100 -0
  77. package/dist/tui/App.js +11 -7
  78. package/dist/tui/components/Dashboard.js +26 -11
  79. package/dist/tui/components/InputBox.js +43 -4
  80. package/dist/tui/components/SidePanel.js +1 -1
  81. package/package.json +1 -1
  82. package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
  83. package/dist/domain/mcp/feishu/bitable.js +0 -168
  84. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
  85. package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
  86. package/dist/domain/mcp/feishu/docx.d.ts +0 -3
  87. package/dist/domain/mcp/feishu/docx.js +0 -163
  88. package/dist/domain/mcp/feishu/drive.d.ts +0 -23
  89. package/dist/domain/mcp/feishu/drive.js +0 -66
  90. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
  91. package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
  92. package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
  93. package/dist/domain/mcp/feishu/sheets.js +0 -119
  94. package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
  95. package/dist/domain/mcp/feishu/wiki.js +0 -77
@@ -1,5 +1,6 @@
1
1
  // input: agent-server/session-hooks.json (lazy-read), spawn() subprocess, OutputStream
2
2
  // output: runSessionHook() unified pipeline + fireAndForgetPreCloseHook (onNew) + onMessageEnd helpers
3
+ // + runHookInjection / onNewInjectSessionKey (isolated pool key for the onNew pre-close turn)
3
4
  // pos: session-level hook subsystem — config loading, subprocess spawn, unified Slack-display pipeline
4
5
  // (parallel to thread-hook system, scoped to channel/session rather than thread)
5
6
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
@@ -10,6 +11,7 @@ import { DATA_DIR, CONFIG_DIR } from '../../core/paths.js';
10
11
  import { createLogger } from '../../core/log.js';
11
12
  import { Icons } from '../../core/icons.js';
12
13
  import { runAgent, resolveBackendForChannel } from '../agents/index.js';
14
+ import { getAdapter } from '../../agent-adapter/index.js';
13
15
  import { getSessionAsync } from '../sessions/session.js';
14
16
  import { sessionStore } from '../../store/session-registry-repo.js';
15
17
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
@@ -99,6 +101,63 @@ function spawnHookProcess({ cfg, stdinPayload, env, label }) {
99
101
  }
100
102
  });
101
103
  }
104
+ /** Pool key for the onNew hook's injected "pre-close" turn.
105
+ *
106
+ * MUST be distinct from the channel's live session-pool slot (which is keyed by the channel
107
+ * itself, see ClaudeAdapter / facade `sessionKey: options.channel`). Race it guards against:
108
+ * `!new` fires this hook fire-and-forget, then synchronously closeSession(channel) +
109
+ * resetChannelSession(channel). The hook's memory-write subprocess finishes LATER and injects
110
+ * its stdout as a final turn that RESUMES the old session. If that turn used `channel` as its
111
+ * pool key it would re-create (resurrect) a live session under the channel slot AFTER the reset
112
+ * — so the next message of the brand-new conversation (also keyed by channel) would reuse the
113
+ * resurrected OLD session instead of starting fresh. Routing the pre-close turn to a dedicated
114
+ * key keeps it off the live slot; we close that key once the turn is done. */
115
+ export function onNewInjectSessionKey(channel) {
116
+ return `${channel}::onnew-hook`;
117
+ }
118
+ const defaultInjectDeps = {
119
+ runAgent,
120
+ closeInjectedSession: async (channel, sessionKey) => {
121
+ try {
122
+ await getAdapter(resolveBackendForChannel(channel)).close(sessionKey);
123
+ }
124
+ catch (e) {
125
+ log.warn(`closeInjectedSession failed (${sessionKey}): ${e?.message || e}`);
126
+ }
127
+ },
128
+ };
129
+ /** Inject hook stdout as a fresh agent turn against `inject.targetSessionId`, routed through
130
+ * `stream`. Runs on `inject.sessionKey`; for onNew that is an isolated key which we close
131
+ * afterwards (the resurrected old session must not linger on / collide with the channel slot).
132
+ * For onMessageEnd the key IS the channel (live conversation) and is left open. */
133
+ export async function runHookInjection(output, spec, stream, deps = defaultInjectDeps) {
134
+ const inject = spec.inject;
135
+ if (!inject)
136
+ return;
137
+ try {
138
+ const handle = deps.runAgent(output, {
139
+ channel: spec.ctx.channel,
140
+ sessionId: inject.targetSessionId,
141
+ sessionKey: inject.sessionKey,
142
+ isUserInitiated: false,
143
+ profileName: inject.profileName,
144
+ trigger: inject.trigger ?? `hook:${spec.name}`,
145
+ onAssistantMessage: (text) => stream.emitText(text),
146
+ });
147
+ await handle.promise;
148
+ }
149
+ catch (err) {
150
+ const msg = err?.message || String(err);
151
+ log.error(`hook ${spec.name} injected agent failed: ${msg}`);
152
+ stream.emitText(`${Icons.warning} ${spec.name} hook follow-up failed: ${msg}`);
153
+ }
154
+ finally {
155
+ // Only the isolated (onNew) key is torn down; the channel live slot (onMessageEnd) stays.
156
+ if (inject.sessionKey !== spec.ctx.channel) {
157
+ await deps.closeInjectedSession(spec.ctx.channel, inject.sessionKey);
158
+ }
159
+ }
160
+ }
102
161
  function buildHookEnv(name, ctx) {
103
162
  const env = {
104
163
  ...process.env,
@@ -131,7 +190,7 @@ function buildHookStdin(name, ctx) {
131
190
  * reply chain (no top-level leak).
132
191
  * - onNew: pass a fresh stream anchored at the last assistant message's thread parent
133
192
  * (resolved via resolveSessionThreadTs). */
134
- export async function runSessionHook(spec, stream) {
193
+ export async function runSessionHook(spec, stream, deps = defaultInjectDeps) {
135
194
  const cfg = loadHookConfig(spec.name);
136
195
  if (!cfg)
137
196
  return;
@@ -161,21 +220,7 @@ export async function runSessionHook(spec, stream) {
161
220
  return;
162
221
  }
163
222
  try {
164
- const handle = runAgent(result.stdout, {
165
- channel: spec.ctx.channel,
166
- sessionId: spec.inject.targetSessionId,
167
- sessionKey: spec.ctx.channel,
168
- isUserInitiated: false,
169
- profileName: spec.inject.profileName,
170
- trigger: spec.inject.trigger ?? `hook:${spec.name}`,
171
- onAssistantMessage: (text) => stream.emitText(text),
172
- });
173
- await handle.promise;
174
- }
175
- catch (err) {
176
- const msg = err?.message || String(err);
177
- log.error(`hook ${spec.name} injected agent failed: ${msg}`);
178
- stream.emitText(`${Icons.warning} ${spec.name} hook follow-up failed: ${msg}`);
223
+ await runHookInjection(result.stdout, spec, stream, deps);
179
224
  }
180
225
  finally {
181
226
  await stream.flush().catch((e) => log.warn(`stream.flush after inject failed (${label}): ${e?.message || e}`));
@@ -261,7 +306,12 @@ async function prepareOnNewRun(channel, adapter, threadAnchorId) {
261
306
  name: 'onNew',
262
307
  ctx: { channel, sessionId, sessionName, profile: profileName },
263
308
  format: ONNEW_FORMAT,
264
- inject: { targetSessionId: sessionId, profileName, trigger: 'hook:onNew' },
309
+ inject: {
310
+ targetSessionId: sessionId,
311
+ profileName,
312
+ sessionKey: onNewInjectSessionKey(channel),
313
+ trigger: 'hook:onNew',
314
+ },
265
315
  };
266
316
  return { spec, stream };
267
317
  }
@@ -304,6 +354,8 @@ export async function runMessageEndSessionHook(args) {
304
354
  inject: {
305
355
  targetSessionId: args.sessionId,
306
356
  profileName: args.profile ?? null,
357
+ // onMessageEnd continues the live conversation — keep it on the channel pool slot.
358
+ sessionKey: args.channel,
307
359
  trigger: 'hook:onMessageEnd',
308
360
  },
309
361
  };
@@ -0,0 +1,63 @@
1
+ export type CheckStatus = 'pass' | 'warn' | 'fail' | 'skip';
2
+ export interface CheckResult {
3
+ id: string;
4
+ label: string;
5
+ status: CheckStatus;
6
+ detail: string;
7
+ hint?: string;
8
+ /** Whether `applySafeFixes` can repair this issue idempotently. */
9
+ fixable?: boolean;
10
+ }
11
+ export interface DoctorSection {
12
+ title: string;
13
+ checks: CheckResult[];
14
+ }
15
+ export interface DoctorReport {
16
+ sections: DoctorSection[];
17
+ counts: {
18
+ pass: number;
19
+ warn: number;
20
+ fail: number;
21
+ skip: number;
22
+ };
23
+ /** True when no check failed (warnings/skips do not break ok). */
24
+ ok: boolean;
25
+ }
26
+ export interface DoctorPaths {
27
+ DATA_DIR: string;
28
+ CONFIG_DIR: string;
29
+ STORE_DIR: string;
30
+ }
31
+ /** Read-only environment probes — the diagnostic path never writes. */
32
+ export interface DoctorDeps {
33
+ env: Record<string, string | undefined>;
34
+ paths: DoctorPaths;
35
+ homeDir: string;
36
+ nodeVersion: string;
37
+ requiredNodeMajor: number;
38
+ fileExists(p: string): boolean;
39
+ isWritable(p: string): boolean;
40
+ readText(p: string): string | null;
41
+ parseDotenv(text: string): Record<string, string>;
42
+ commandExists(bin: string): boolean;
43
+ pidAlive(pid: number): boolean;
44
+ probeGateway(): Promise<boolean>;
45
+ }
46
+ /** Write actuators used only by `applySafeFixes` (idempotent, non-destructive). */
47
+ export interface FixActuators {
48
+ mkdirp(p: string): void;
49
+ ensureEnvFile(envPath: string): void;
50
+ /** Generate any missing auth tokens, persist to envPath; return names generated. */
51
+ ensureAuthTokens(envPath: string): string[];
52
+ regenerateMcpConfig(): void;
53
+ }
54
+ export interface FixOutcome {
55
+ id: string;
56
+ label: string;
57
+ applied: boolean;
58
+ detail: string;
59
+ }
60
+ export declare function runDiagnostics(deps: DoctorDeps): Promise<DoctorReport>;
61
+ export declare function applySafeFixes(report: DoctorReport, deps: DoctorDeps, fix: FixActuators): Promise<FixOutcome[]>;
62
+ export declare function createDefaultDoctorDeps(): DoctorDeps;
63
+ export declare function createDefaultFixActuators(): FixActuators;
@@ -0,0 +1,362 @@
1
+ // input: injected DoctorDeps (env, paths, fs probes, gateway probe) + FixActuators
2
+ // output: runDiagnostics(deps) → DoctorReport; applySafeFixes(report, deps, fix) → FixOutcome[]
3
+ // createDefaultDoctorDeps / createDefaultFixActuators — real-environment wiring
4
+ // pos: Pure diagnostic engine for `cortex doctor`. Health-checks the whole install
5
+ // (runtime, backend/login, messaging platform, gateway). No side effects in the
6
+ // diagnostic path; all writes go through injected FixActuators (--fix only).
7
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
8
+ import * as fs from 'node:fs';
9
+ import * as os from 'node:os';
10
+ import * as path from 'node:path';
11
+ import * as http from 'node:http';
12
+ import { parse as parseDotenvLib } from 'dotenv';
13
+ import { DATA_DIR, CONFIG_DIR, STORE_DIR, GATEWAY_MANAGED_KEY_PLACEHOLDER } from '../../core/utils.js';
14
+ import { ensureAuthTokens, CLIENT_TOKEN_ENV, WEBHOOK_TOKEN_ENV } from '../../core/auth.js';
15
+ import { generateMcpConfig } from '../../core/config-generator.js';
16
+ // ─── Helpers ──────────────────────────────────────────────────────
17
+ const GW_HOST = '127.0.0.1';
18
+ const GW_PORT = 9880;
19
+ function normalize(v) {
20
+ if (typeof v !== 'string')
21
+ return undefined;
22
+ const t = v.trim();
23
+ if (!t || t === 'null' || t === 'undefined')
24
+ return undefined;
25
+ return t;
26
+ }
27
+ function nodeMajor(version) {
28
+ const m = version.match(/^v?(\d+)/);
29
+ return m ? Number(m[1]) : 0;
30
+ }
31
+ /** Merge process env over the .env file, normalizing blanks/null/undefined away. */
32
+ function buildEnvReader(deps) {
33
+ const envPath = path.join(deps.paths.CONFIG_DIR, '.env');
34
+ let fileEnv = {};
35
+ const text = deps.readText(envPath);
36
+ if (text != null) {
37
+ try {
38
+ fileEnv = deps.parseDotenv(text);
39
+ }
40
+ catch {
41
+ fileEnv = {};
42
+ }
43
+ }
44
+ return (name) => normalize(deps.env[name] ?? fileEnv[name]);
45
+ }
46
+ // ─── Section: Runtime & Process ───────────────────────────────────
47
+ function sectionRuntime(deps) {
48
+ const checks = [];
49
+ const major = nodeMajor(deps.nodeVersion);
50
+ checks.push(major >= deps.requiredNodeMajor
51
+ ? { id: 'node-version', label: 'Node version', status: 'pass', detail: `${deps.nodeVersion} (>=${deps.requiredNodeMajor})` }
52
+ : { id: 'node-version', label: 'Node version', status: 'warn', detail: `${deps.nodeVersion} — Cortex requires Node >=${deps.requiredNodeMajor}`, hint: 'Upgrade Node.js' });
53
+ checks.push(deps.commandExists('git')
54
+ ? { id: 'git', label: 'git', status: 'pass', detail: 'found on PATH' }
55
+ : { id: 'git', label: 'git', status: 'fail', detail: 'not found on PATH', hint: 'Install git — required for context sync' });
56
+ // Backend binary, per mode.json backend selection.
57
+ const modeText = deps.readText(path.join(deps.paths.STORE_DIR, 'mode.json'));
58
+ let backend = 'claude';
59
+ try {
60
+ if (modeText) {
61
+ const m = JSON.parse(modeText);
62
+ if (typeof m.backend === 'string')
63
+ backend = m.backend;
64
+ }
65
+ }
66
+ catch { /* fall back to claude */ }
67
+ const bin = backend === 'pi' ? 'pi' : backend === 'codex' ? 'codex' : 'claude';
68
+ checks.push(deps.commandExists(bin)
69
+ ? { id: 'backend-binary', label: 'Backend binary', status: 'pass', detail: `${bin} found on PATH (backend: ${backend})` }
70
+ : { id: 'backend-binary', label: 'Backend binary', status: 'warn', detail: `${bin} not on PATH (backend: ${backend})`, hint: `Install/login the ${bin} CLI` });
71
+ // Daemon — informational only.
72
+ const pidPath = path.join(deps.paths.STORE_DIR, 'daemon.pid');
73
+ const pidText = deps.fileExists(pidPath) ? deps.readText(pidPath) : null;
74
+ const pid = pidText ? Number(pidText.trim()) : NaN;
75
+ if (Number.isFinite(pid) && deps.pidAlive(pid)) {
76
+ checks.push({ id: 'daemon', label: 'Daemon', status: 'pass', detail: `running (pid ${pid})` });
77
+ }
78
+ else {
79
+ checks.push({ id: 'daemon', label: 'Daemon', status: 'skip', detail: 'not running', hint: 'Start with `cortex daemon`' });
80
+ }
81
+ return { title: 'Runtime & Process', checks };
82
+ }
83
+ // ─── Section: Backend Install / Login ─────────────────────────────
84
+ function sectionBackend(deps, getEnv) {
85
+ const checks = [];
86
+ const { DATA_DIR: data, CONFIG_DIR: config, STORE_DIR: store } = deps.paths;
87
+ // Directories exist + writable.
88
+ const dirProblems = [];
89
+ for (const [name, p] of [['DATA_DIR', data], ['CONFIG_DIR', config], ['STORE_DIR', store]]) {
90
+ if (!deps.fileExists(p))
91
+ dirProblems.push(`${name} missing (${p})`);
92
+ else if (!deps.isWritable(p))
93
+ dirProblems.push(`${name} not writable (${p})`);
94
+ }
95
+ checks.push(dirProblems.length === 0
96
+ ? { id: 'dirs', label: 'Data directories', status: 'pass', detail: 'present and writable' }
97
+ : { id: 'dirs', label: 'Data directories', status: 'fail', detail: dirProblems.join('; '), hint: 'run `cortex doctor --fix` or `cortex init`', fixable: true });
98
+ // .env file.
99
+ const envPath = path.join(config, '.env');
100
+ checks.push(deps.fileExists(envPath)
101
+ ? { id: 'env-file', label: '.env file', status: 'pass', detail: envPath }
102
+ : { id: 'env-file', label: '.env file', status: 'fail', detail: `missing (${envPath})`, hint: 'run `cortex init`' });
103
+ // Auth tokens.
104
+ const missingTokens = [CLIENT_TOKEN_ENV, WEBHOOK_TOKEN_ENV].filter(n => !getEnv(n));
105
+ checks.push(missingTokens.length === 0
106
+ ? { id: 'auth-tokens', label: 'Auth tokens', status: 'pass', detail: 'client + webhook tokens set' }
107
+ : { id: 'auth-tokens', label: 'Auth tokens', status: 'fail', detail: `missing: ${missingTokens.join(', ')}`, hint: 'run `cortex doctor --fix` to generate', fixable: true });
108
+ // Anthropic API key — warn (plan/subscription mode does not need it).
109
+ const apiKey = getEnv('ANTHROPIC_API_KEY');
110
+ if (apiKey === GATEWAY_MANAGED_KEY_PLACEHOLDER) {
111
+ checks.push({ id: 'anthropic-key', label: 'Anthropic API key', status: 'pass', detail: 'managed by gateway' });
112
+ }
113
+ else if (apiKey) {
114
+ checks.push({ id: 'anthropic-key', label: 'Anthropic API key', status: 'pass', detail: 'set' });
115
+ }
116
+ else {
117
+ checks.push({ id: 'anthropic-key', label: 'Anthropic API key', status: 'warn', detail: 'not set — required for API mode (plan/subscription mode can ignore)', hint: 'set ANTHROPIC_API_KEY in .env or run `cortex init`' });
118
+ }
119
+ // mode.json
120
+ pushJsonCheck(checks, deps, path.join(store, 'mode.json'), 'mode-json', 'mode.json', 'warn');
121
+ // profiles.json (schema-lite)
122
+ checks.push(checkProfiles(deps, path.join(config, 'profiles.json')));
123
+ // mcp-config.json
124
+ const mcpPath = path.join(config, 'mcp-config.json');
125
+ if (!deps.fileExists(mcpPath)) {
126
+ checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'warn', detail: `missing (${mcpPath})`, hint: 'run `cortex doctor --fix` to regenerate', fixable: true });
127
+ }
128
+ else if (!isValidJson(deps.readText(mcpPath))) {
129
+ checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'warn', detail: 'invalid JSON', hint: 'run `cortex doctor --fix` to regenerate', fixable: true });
130
+ }
131
+ else {
132
+ checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'pass', detail: 'valid' });
133
+ }
134
+ return { title: 'Backend Install / Login', checks };
135
+ }
136
+ function isValidJson(text) {
137
+ if (text == null)
138
+ return false;
139
+ try {
140
+ JSON.parse(text);
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ function pushJsonCheck(checks, deps, p, id, label, missingStatus) {
148
+ if (!deps.fileExists(p)) {
149
+ checks.push({ id, label, status: missingStatus, detail: `missing (${p})` });
150
+ return;
151
+ }
152
+ checks.push(isValidJson(deps.readText(p))
153
+ ? { id, label, status: 'pass', detail: 'valid' }
154
+ : { id, label, status: missingStatus, detail: 'invalid JSON' });
155
+ }
156
+ function checkProfiles(deps, p) {
157
+ if (!deps.fileExists(p)) {
158
+ return { id: 'profiles', label: 'profiles.json', status: 'warn', detail: `missing (${p})`, hint: 'run `cortex setup-gateway`' };
159
+ }
160
+ const text = deps.readText(p);
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(text ?? '');
164
+ }
165
+ catch {
166
+ return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: 'invalid JSON', hint: 're-run `cortex setup-gateway`' };
167
+ }
168
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.profiles !== 'object' || parsed.profiles == null) {
169
+ return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: 'missing `profiles` object' };
170
+ }
171
+ if (parsed.defaultProfile && !(parsed.defaultProfile in parsed.profiles)) {
172
+ return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: `defaultProfile "${parsed.defaultProfile}" not found in profiles` };
173
+ }
174
+ const names = Object.keys(parsed.profiles).join(', ');
175
+ return { id: 'profiles', label: 'profiles.json', status: 'pass', detail: `profiles: ${names || '(none)'}` };
176
+ }
177
+ // ─── Section: Messaging Platform ──────────────────────────────────
178
+ function sectionPlatform(deps, getEnv) {
179
+ const checks = [];
180
+ const raw = getEnv('CORTEX_PLATFORM') ?? 'slack';
181
+ const names = raw.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
182
+ checks.push({ id: 'platform', label: 'Platform', status: 'pass', detail: `configured: ${names.join(', ') || '(none)'}` });
183
+ for (const name of names) {
184
+ if (name === 'slack') {
185
+ const problems = [];
186
+ const bot = getEnv('SLACK_BOT_TOKEN');
187
+ const sign = getEnv('SLACK_SIGNING_SECRET');
188
+ const app = getEnv('SLACK_APP_TOKEN');
189
+ if (!bot)
190
+ problems.push('SLACK_BOT_TOKEN missing');
191
+ else if (!bot.startsWith('xoxb-'))
192
+ problems.push('SLACK_BOT_TOKEN should start with xoxb-');
193
+ if (!sign)
194
+ problems.push('SLACK_SIGNING_SECRET missing');
195
+ if (!app)
196
+ problems.push('SLACK_APP_TOKEN missing');
197
+ else if (!app.startsWith('xapp-'))
198
+ problems.push('SLACK_APP_TOKEN should start with xapp-');
199
+ checks.push(problems.length === 0
200
+ ? { id: 'slack-creds', label: 'Slack credentials', status: 'pass', detail: 'bot / signing / app tokens present' }
201
+ : { id: 'slack-creds', label: 'Slack credentials', status: 'fail', detail: problems.join('; '), hint: 'set Slack tokens in .env (see `cortex init`)' });
202
+ }
203
+ else if (name === 'feishu') {
204
+ const problems = [];
205
+ if (!getEnv('FEISHU_APP_ID'))
206
+ problems.push('FEISHU_APP_ID missing');
207
+ if (!getEnv('FEISHU_APP_SECRET'))
208
+ problems.push('FEISHU_APP_SECRET missing');
209
+ checks.push(problems.length === 0
210
+ ? { id: 'feishu-creds', label: 'Feishu credentials', status: 'pass', detail: 'app id / secret present' }
211
+ : { id: 'feishu-creds', label: 'Feishu credentials', status: 'fail', detail: problems.join('; '), hint: 'set FEISHU_APP_ID / FEISHU_APP_SECRET in .env' });
212
+ }
213
+ else if (name === 'test') {
214
+ checks.push({ id: 'test-platform', label: 'Test platform', status: 'skip', detail: 'mock adapter (test only)' });
215
+ }
216
+ else {
217
+ checks.push({ id: `platform-${name}`, label: `Platform: ${name}`, status: 'warn', detail: 'unknown platform name' });
218
+ }
219
+ }
220
+ return { title: 'Messaging Platform', checks };
221
+ }
222
+ // ─── Section: Gateway ─────────────────────────────────────────────
223
+ async function sectionGateway(deps, getEnv) {
224
+ const checks = [];
225
+ const gwYaml = path.join(deps.homeDir, '.aistatus', 'gateway.yaml');
226
+ const gwConfigured = deps.fileExists(gwYaml);
227
+ checks.push(gwConfigured
228
+ ? { id: 'gateway-config', label: 'Gateway config', status: 'pass', detail: gwYaml }
229
+ : { id: 'gateway-config', label: 'Gateway config', status: 'skip', detail: 'not configured (no ~/.aistatus/gateway.yaml)', hint: 'run `cortex setup-gateway` if you use the gateway' });
230
+ const healthy = await deps.probeGateway();
231
+ const gatewayInUse = getEnv('ANTHROPIC_API_KEY') === GATEWAY_MANAGED_KEY_PLACEHOLDER || gwConfigured;
232
+ if (healthy) {
233
+ checks.push({ id: 'gateway-health', label: 'Gateway health', status: 'pass', detail: `responding at ${GW_HOST}:${GW_PORT}` });
234
+ }
235
+ else if (gatewayInUse) {
236
+ checks.push({ id: 'gateway-health', label: 'Gateway health', status: 'fail', detail: `no response at ${GW_HOST}:${GW_PORT}/status`, hint: 'check gateway.log or restart Cortex (the server auto-starts the gateway)' });
237
+ }
238
+ else {
239
+ checks.push({ id: 'gateway-health', label: 'Gateway health', status: 'skip', detail: 'not running (not required for current backend)' });
240
+ }
241
+ return { title: 'Gateway', checks };
242
+ }
243
+ // ─── Engine ───────────────────────────────────────────────────────
244
+ export async function runDiagnostics(deps) {
245
+ const getEnv = buildEnvReader(deps);
246
+ const sections = [
247
+ sectionRuntime(deps),
248
+ sectionBackend(deps, getEnv),
249
+ sectionPlatform(deps, getEnv),
250
+ await sectionGateway(deps, getEnv),
251
+ ];
252
+ const counts = { pass: 0, warn: 0, fail: 0, skip: 0 };
253
+ for (const s of sections)
254
+ for (const c of s.checks)
255
+ counts[c.status]++;
256
+ return { sections, counts, ok: counts.fail === 0 };
257
+ }
258
+ // ─── Safe fixes ───────────────────────────────────────────────────
259
+ export async function applySafeFixes(report, deps, fix) {
260
+ const fixable = new Map();
261
+ for (const s of report.sections)
262
+ for (const c of s.checks) {
263
+ if (c.fixable && (c.status === 'fail' || c.status === 'warn'))
264
+ fixable.set(c.id, c);
265
+ }
266
+ const outcomes = [];
267
+ const envPath = path.join(deps.paths.CONFIG_DIR, '.env');
268
+ if (fixable.has('dirs')) {
269
+ for (const p of [deps.paths.DATA_DIR, deps.paths.CONFIG_DIR, deps.paths.STORE_DIR])
270
+ fix.mkdirp(p);
271
+ outcomes.push({ id: 'dirs', label: 'Data directories', applied: true, detail: 'created missing directories' });
272
+ }
273
+ if (fixable.has('auth-tokens')) {
274
+ fix.ensureEnvFile(envPath);
275
+ const generated = fix.ensureAuthTokens(envPath);
276
+ outcomes.push({ id: 'auth-tokens', label: 'Auth tokens', applied: generated.length > 0, detail: generated.length > 0 ? `generated: ${generated.join(', ')}` : 'already present' });
277
+ }
278
+ if (fixable.has('mcp-config')) {
279
+ fix.regenerateMcpConfig();
280
+ outcomes.push({ id: 'mcp-config', label: 'mcp-config.json', applied: true, detail: 'regenerated' });
281
+ }
282
+ return outcomes;
283
+ }
284
+ // ─── Default real-environment wiring ──────────────────────────────
285
+ function commandExistsOnPath(bin) {
286
+ const pathVar = process.env.PATH || '';
287
+ const exts = process.platform === 'win32' ? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
288
+ for (const dir of pathVar.split(path.delimiter)) {
289
+ if (!dir)
290
+ continue;
291
+ for (const ext of exts) {
292
+ const candidate = path.join(dir, bin + ext);
293
+ try {
294
+ if (fs.existsSync(candidate))
295
+ return true;
296
+ }
297
+ catch { /* ignore */ }
298
+ }
299
+ }
300
+ return false;
301
+ }
302
+ function probeGatewayHttp() {
303
+ return new Promise((resolve) => {
304
+ const req = http.get(`http://${GW_HOST}:${GW_PORT}/status`, { timeout: 5000 }, (res) => {
305
+ res.resume();
306
+ resolve(res.statusCode === 200);
307
+ });
308
+ req.on('error', () => resolve(false));
309
+ req.on('timeout', () => { req.destroy(); resolve(false); });
310
+ });
311
+ }
312
+ export function createDefaultDoctorDeps() {
313
+ return {
314
+ env: process.env,
315
+ paths: { DATA_DIR, CONFIG_DIR, STORE_DIR },
316
+ homeDir: os.homedir(),
317
+ nodeVersion: process.version,
318
+ requiredNodeMajor: 20,
319
+ fileExists: (p) => { try {
320
+ return fs.existsSync(p);
321
+ }
322
+ catch {
323
+ return false;
324
+ } },
325
+ isWritable: (p) => { try {
326
+ fs.accessSync(p, fs.constants.W_OK);
327
+ return true;
328
+ }
329
+ catch {
330
+ return false;
331
+ } },
332
+ readText: (p) => { try {
333
+ return fs.readFileSync(p, 'utf8');
334
+ }
335
+ catch {
336
+ return null;
337
+ } },
338
+ parseDotenv: (t) => parseDotenvLib(t),
339
+ commandExists: commandExistsOnPath,
340
+ pidAlive: (pid) => { try {
341
+ process.kill(pid, 0);
342
+ return true;
343
+ }
344
+ catch {
345
+ return false;
346
+ } },
347
+ probeGateway: probeGatewayHttp,
348
+ };
349
+ }
350
+ export function createDefaultFixActuators() {
351
+ return {
352
+ mkdirp: (p) => { fs.mkdirSync(p, { recursive: true }); },
353
+ ensureEnvFile: (envPath) => {
354
+ if (!fs.existsSync(envPath)) {
355
+ fs.mkdirSync(path.dirname(envPath), { recursive: true });
356
+ fs.writeFileSync(envPath, '');
357
+ }
358
+ },
359
+ ensureAuthTokens: (envPath) => ensureAuthTokens({ envPath }).generated,
360
+ regenerateMcpConfig: () => generateMcpConfig(),
361
+ };
362
+ }
@@ -9,14 +9,14 @@ import { lintTasks } from '../lint.js';
9
9
  import { loadConfig, listTemplateNames } from '../../threads/template-loader.js';
10
10
  import { editTask } from './task-lifecycle-edit.js';
11
11
  import { assignIds, validateIds } from './task-id-utils.js';
12
- import { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, } from './task-state.js';
12
+ import { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, reopenTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, } from './task-state.js';
13
13
  import { completeTask, uncompleteTask } from './task-completion.js';
14
14
  import { addTask, batchEdit, bulkAddTasks, decomposeTask } from './task-mutations.js';
15
15
  import { stopTask, stopTaskDryRun } from './task-process.js';
16
16
  import { acquireLock, assertLockHeld, getOwnerIdentity, readLock, releaseLock, } from './task-lock.js';
17
17
  const READ_COMMANDS = new Set(['list', 'all', 'query', 'show', 'deps', 'lint', 'stats', 'tree']);
18
18
  const WRITE_COMMANDS = new Set([
19
- 'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
19
+ 'claim', 'unclaim', 'pause', 'resume', 'pending', 'reopen', 'complete', 'uncomplete',
20
20
  'request-approval', 'approve', 'clear-approval',
21
21
  'block', 'unblock',
22
22
  'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
@@ -25,14 +25,14 @@ const WRITE_COMMANDS = new Set([
25
25
  ]);
26
26
  const ALL_COMMANDS = new Set([...READ_COMMANDS, ...WRITE_COMMANDS]);
27
27
  const COMMANDS_NEEDING_TASK = new Set([
28
- 'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
28
+ 'claim', 'unclaim', 'pause', 'resume', 'pending', 'reopen', 'complete', 'uncomplete',
29
29
  'request-approval', 'approve', 'clear-approval',
30
30
  'block', 'unblock',
31
31
  'edit', 'decompose',
32
32
  ]);
33
33
  const COMMANDS_NEEDING_REASON = new Set(['block']);
34
34
  const COMMANDS_NEEDING_PROJECT = new Set([
35
- 'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
35
+ 'claim', 'unclaim', 'pause', 'resume', 'pending', 'reopen', 'complete', 'uncomplete',
36
36
  'request-approval', 'approve', 'clear-approval',
37
37
  'block', 'unblock',
38
38
  'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
@@ -55,6 +55,7 @@ const COMMAND_FLAG_ALLOWLIST = {
55
55
  pause: new Set([...COMMON_FLAGS, '--task']),
56
56
  resume: new Set([...COMMON_FLAGS, '--task']),
57
57
  pending: new Set([...COMMON_FLAGS, '--task']),
58
+ reopen: new Set([...COMMON_FLAGS, '--task']),
58
59
  complete: new Set([...COMMON_FLAGS, '--task', '--note', '--skip-verify', '--skip-verify-reason']),
59
60
  uncomplete: new Set([...COMMON_FLAGS, '--task']),
60
61
  'request-approval': new Set([...COMMON_FLAGS, '--task']),
@@ -105,6 +106,7 @@ const HELP_CONFIG = {
105
106
  { name: 'pause', description: 'Pause' },
106
107
  { name: 'resume', description: 'Resume a paused task' },
107
108
  { name: 'pending', description: 'Mark pending (waiting for cortex-run)' },
109
+ { name: 'reopen', description: 'Restore a stuck pending task back to open (e.g. after a lost cortex-run callback)' },
108
110
  { name: 'complete', description: 'Mark complete (--note)' },
109
111
  { name: 'uncomplete', description: 'Reverse a completed task' },
110
112
  ],
@@ -774,6 +776,7 @@ const WRITE_HANDLERS = {
774
776
  pause: (v) => pauseTask(v.task, v.project, v.taskId),
775
777
  resume: (v) => resumeTask(v.task, v.project, v.taskId),
776
778
  pending: (v) => pendingTask(v.task, v.project, v.taskId),
779
+ reopen: (v) => reopenTask(v.task, v.project, v.taskId),
777
780
  complete: (v) => completeTask(v.task, v.project, v.note, v.taskId, v.skipVerify, v.skipVerifyReason),
778
781
  uncomplete: (v) => uncompleteTask(v.task, v.project, v.taskId),
779
782
  'request-approval': (v) => requestApprovalTask(v.task, v.project, v.taskId),
@@ -67,4 +67,13 @@ declare function unblockTask(taskText: string | null, project: string, taskId?:
67
67
  message: string;
68
68
  task_id: string;
69
69
  };
70
- export { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, };
70
+ declare function reopenTask(taskText: string | null, project: string, taskId?: string | null): {
71
+ success: boolean;
72
+ message: string;
73
+ task_id?: undefined;
74
+ } | {
75
+ success: boolean;
76
+ message: string;
77
+ task_id: string;
78
+ };
79
+ export { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, reopenTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, };