@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
@@ -12,7 +12,8 @@
12
12
  "plugins/cortex-common",
13
13
  "plugins/cortex-stage-gate",
14
14
  "plugins/cortex-coder",
15
- "plugins/cortex-system"
15
+ "plugins/cortex-system",
16
+ "plugins/cortex-feishu"
16
17
  ]
17
18
  },
18
19
  "direct": {
@@ -27,7 +28,8 @@
27
28
  "plugins/cortex-common",
28
29
  "plugins/cortex-stage-gate",
29
30
  "plugins/cortex-coder",
30
- "plugins/cortex-system"
31
+ "plugins/cortex-system",
32
+ "plugins/cortex-feishu"
31
33
  ]
32
34
  },
33
35
  "direct-web": {
@@ -42,7 +44,8 @@
42
44
  "plugins/cortex-common",
43
45
  "plugins/cortex-stage-gate",
44
46
  "plugins/cortex-coder",
45
- "plugins/cortex-system"
47
+ "plugins/cortex-system",
48
+ "plugins/cortex-feishu"
46
49
  ]
47
50
  },
48
51
  "direct-review": {
@@ -58,7 +61,8 @@
58
61
  "plugins/cortex-common",
59
62
  "plugins/cortex-stage-gate",
60
63
  "plugins/cortex-coder",
61
- "plugins/cortex-system"
64
+ "plugins/cortex-system",
65
+ "plugins/cortex-feishu"
62
66
  ]
63
67
  },
64
68
  "scheduler-main": {
@@ -73,7 +77,8 @@
73
77
  "plugins/cortex-common",
74
78
  "plugins/cortex-stage-gate",
75
79
  "plugins/cortex-coder",
76
- "plugins/cortex-system"
80
+ "plugins/cortex-system",
81
+ "plugins/cortex-feishu"
77
82
  ]
78
83
  },
79
84
  "planner": {
@@ -317,7 +322,8 @@
317
322
  "plugins/cortex-common",
318
323
  "plugins/cortex-stage-gate",
319
324
  "plugins/cortex-coder",
320
- "plugins/cortex-system"
325
+ "plugins/cortex-system",
326
+ "plugins/cortex-feishu"
321
327
  ]
322
328
  }
323
329
  },
@@ -11,8 +11,8 @@ User-level memory directory. Stores user personal preferences and context across
11
11
  ## Rules
12
12
 
13
13
  - `USER.md` is maintained by the agent (`/user-learn` skill), user corrects via `/feedback`
14
- - Only injected into threads where the user is directly conversing (direct / direct-web / direct-review), not injected into dispatch threads
15
- - Injection is controlled by environment variable `CORTEX_INJECT_USER_CONTEXT=1`
14
+ - Injected only into plain direct conversation turns (the thread-free chat path); multi-agent thread steps never carry the user profile
15
+ - Injected by default; set environment variable `CORTEX_DISABLE_USER_CONTEXT=1` to disable
16
16
  - File hard limit 3KB, compress rather than grow when approaching the limit
17
17
 
18
18
  ## Lookup Rules
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PreToolUse event, node:http
3
4
  // output: stdout updatedInput containing user answers received from Slack
4
5
  // pos: PreToolUse hook: intercept AskUserQuestion and forward to Slack to collect answers
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PreToolUse event, node:http
3
4
  // output: stdout permissionDecision (plan injected back after Slack approval)
4
5
  // pos: PreToolUse hook: intercept ExitPlanMode and forward plan to Slack for approval
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin JSON from Claude PostToolUse hook
3
4
  // output: appends to _meta/access-log.jsonl per project
4
5
  // pos: Read/Grep memory access tracking hook
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin { channel, sessionId, sessionName, trigger, timestampIso } + env CORTEX_HOOK_*
3
4
  // output: stdout — prompt to inject into the closing session (empty stdout = skip)
4
5
  // pos: !new pre-close memory flush hook — recall valuable user and project info from the session, write to corresponding context files
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin HookContext, argv [targetAgent]
3
4
  // output: HookResult — compound + git commit prompt to targetAgent
4
5
  // pos: scheduler and *-review template onEnd compound/commit hook
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin JSON — Claude Code PostToolUse event or PI hook-bridge payload
3
4
  // output: { matched: [...], hookSpecificOutput: { additionalContext: "..." } }
4
5
  // pos: Read/Grep hook — check if file path matches scoped rules in ~/.cortex/rules/
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PreToolUse event, node:fs
3
4
  // output: Direct-write target file + deny to prevent Claude from re-running built-in Edit/Write
4
5
  // pos: PreToolUse hook: bypass Claude Code's hardcoded protection on .claude/ paths
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin Claude Code PostToolUse event, node:fs
3
4
  // output: Appends records to logs/session-activity/<session_id>.jsonl
4
5
  // pos: PostToolUse hook: track Read/Edit/Write/Skill for diff reconstruction
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin HookContext, argv [project, taskId]
3
4
  // output: HookResult — checks TASKS.yaml task status after thread ends
4
5
  // pos: task-dispatch thread onEnd status check hook
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.22-2
2
3
  // input: stdin JSON — Claude Code PreToolUse event payload
3
4
  // output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason } }
4
5
  // pos: PreToolUse hook — intercepts Edit/Write on **/TASKS.yaml, checks project lock
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "cortex-feishu",
3
+ "version": "0.1.0",
4
+ "description": "Feishu/Lark rich-text skill bundle — drive Feishu documents, native tables, spreadsheets, and base through the official lark-cli (feishu-doc skill). Separate from the cortex-feishu MCP server, which only sends files."
5
+ }
@@ -0,0 +1,163 @@
1
+ ---
2
+ name: feishu-doc
3
+ description: "Use when creating, reading, or editing Feishu/Lark cloud documents (docx/wiki), especially inserting or batch-updating native tables, callouts, whiteboards, or other rich blocks, or converting markdown ↔ Feishu docs. Also use for Feishu spreadsheets (sheets) and multi-dimensional tables (bitable/base). Cortex drives all Feishu rich-text work through the official lark-cli — NOT through MCP tools (the docx MCP was removed because its table support was structurally weak). Trigger on a feishu.cn/larksuite.com docx/wiki/sheets/base URL or token, or any request to write/update a Feishu document."
4
+ author: Cortex
5
+ version: 1.0.0
6
+ allowed-tools:
7
+ - Bash
8
+ - Read
9
+ - Write
10
+ - Edit
11
+ date: 2026-06-23
12
+ ---
13
+
14
+ # feishu-doc — Feishu rich-text via the official lark-cli
15
+
16
+ ## Why this skill exists
17
+
18
+ Feishu cloud documents are a block tree; native tables are a strict block type.
19
+ Cortex previously exposed `feishu_docx_*` MCP tools whose table support was
20
+ structurally weak, so they were removed. The reliable channel is now the **official
21
+ `lark-cli`** (`@larksuite/cli`), which ships its own version-matched agent skills
22
+ covering the exact XML/block workflow.
23
+
24
+ > The old MCP's limitations do **not** apply to lark-cli. In particular, with the
25
+ > current CLI both of these work fine (verified on v1.0.56): markdown tables import
26
+ > as **native** `<table>` blocks (they do not degrade to text), and `block_replace`
27
+ > can replace **across types** (e.g. a text paragraph → a table). Do not carry the
28
+ > retired MCP's table caveats into lark-cli guidance.
29
+
30
+ This Cortex skill is a thin **integration + delegation** layer: it gets `lark-cli`
31
+ installed and authenticated, surfaces the Cortex-environment gotchas below, then hands
32
+ you off to the official embedded skills. Do not re-document or freeze the lark-cli
33
+ content/XML/table workflow here — read it live (Step 3) so it stays in sync with the
34
+ installed CLI.
35
+
36
+ `feishu_send_file` (uploading a file to a Feishu chat) still lives in the cortex-feishu
37
+ MCP and is unrelated to this skill. Feishu IM messaging runs through the platform
38
+ adapter, not MCP — none of that is affected.
39
+
40
+ ## Step 1 — Preflight (install + config)
41
+
42
+ Run the bundled preflight (idempotent: installs only if missing, configures the app
43
+ from Cortex's `FEISHU_APP_ID` / `FEISHU_APP_SECRET`, prints auth status):
44
+
45
+ ```bash
46
+ bash plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh
47
+ ```
48
+
49
+ If the script path is unavailable, the essential check inline:
50
+
51
+ ```bash
52
+ command -v lark-cli >/dev/null 2>&1 || npm install -g @larksuite/cli
53
+ lark-cli auth status
54
+ ```
55
+
56
+ Notes:
57
+ - Cortex runs on **lab2**; install/run there. `lark-cli` stores credentials in the
58
+ OS keychain (falls back to a local file on headless Linux).
59
+ - `config init` is non-interactive via `--app-id <id> --app-secret-stdin` and refuses
60
+ only inside OpenClaw/Hermes agent workspaces (Cortex is neither).
61
+
62
+ ## Step 2 — Authenticate (one-time, may need the user)
63
+
64
+ Document editing defaults to the **user** identity (`--as user`). `auth status` shows
65
+ two identities:
66
+ - `bot` (tenant): ready as soon as `config init` ran — enough for many tenant API calls.
67
+ - `user`: requires a one-time **device-flow** login the bot cannot complete alone.
68
+
69
+ If the user identity is missing and you need it, do NOT block silently. Use the
70
+ non-interactive flow:
71
+
72
+ ```bash
73
+ lark-cli auth login --no-wait --json --domain docs,drive,sheets,base
74
+ ```
75
+
76
+ Surface the returned verification URL (or `lark-cli auth qrcode`) to the user as your
77
+ turn's final message, end the turn, and after they confirm, resume with:
78
+
79
+ ```bash
80
+ lark-cli auth login --device-code <code-from-previous-output>
81
+ ```
82
+
83
+ ## Step 3 — Delegate to the official lark-cli skills (authoritative)
84
+
85
+ Before running any `docs` / `sheets` / `base` command, read the matching embedded
86
+ skill — it is version-matched to the installed CLI and is the source of truth for
87
+ flags, XML syntax, block selectors, and table handling. Read it via the CLI (do NOT
88
+ grep local SKILL.md files):
89
+
90
+ ```bash
91
+ lark-cli skills read lark-doc # documents / blocks / tables / whiteboards
92
+ lark-cli skills read lark-doc <path> # a referenced sub-file, e.g. references/lark-doc-update.md
93
+ lark-cli skills read lark-sheets # spreadsheets
94
+ lark-cli skills read lark-base # bitable / multi-dimensional tables
95
+ ```
96
+
97
+ Key facts the official skill expands on (read it for the exact commands):
98
+ - Docs use **v2 API**: pass `--api-version v2` to `docs +create/+fetch/+update`.
99
+ - Create / full-section import: XML or Markdown both work
100
+ (`docs +create --api-version v2 --content '<title>..</title><p>..</p>'`).
101
+ - Precise edits (insert/replace/delete a block): prefer XML (`--doc-format xml`, the
102
+ default) and the `+update` commands (`str_replace`, `block_insert_after`,
103
+ `block_replace`, `block_delete`, `block_move_after`).
104
+ - **Native tables work both ways**: an XML `<table>` (via `+create`,
105
+ `block_insert_after`, or `block_replace` — cross-type text→table is fine) and a
106
+ markdown table (via `append`/`overwrite --doc-format markdown`) both produce a real
107
+ native table block. The `lark-doc` references document the exact `<table>` XML and
108
+ styling (`colgroup`, header `background-color`, `colspan`/`rowspan`).
109
+ - Embedded `<sheet>` / `<bitable>` tags: extract the token and switch to the
110
+ `lark-sheets` / `lark-base` skill to operate the data inside.
111
+
112
+ ## Step 4 — Programmatic / batch table updates
113
+
114
+ The motivating use case (update a doc table from data) is what the CLI is for. Pattern:
115
+
116
+ 1. Read the target doc to locate the table block id:
117
+ `lark-cli docs +fetch --api-version v2 --doc "<url-or-token>" --detail with-ids`.
118
+ 2. Generate the new `<table>` XML from your data (CSV/dict) in a small script.
119
+ 3. Apply it with `docs +update --api-version v2 --doc "<token>" --command block_replace`
120
+ on the table block (cross-type is fine), or `block_insert_after` + `block_delete` the
121
+ stale block (per the `lark-doc` reference).
122
+
123
+ Keep generation in a script under the project so the update is repeatable; this is the
124
+ right home for data-driven table maintenance, not one-off MCP calls.
125
+
126
+ ## Step 5 — Cortex-environment gotchas (read before driving the CLI)
127
+
128
+ These are integration-layer facts specific to running lark-cli inside Cortex. They are
129
+ NOT in the official lark-cli skills — check them here, then defer everything about
130
+ content/XML/blocks to Step 3.
131
+
132
+ - **Pass content via stdin, not `@file`.** lark-cli's `@file` only accepts a path
133
+ *relative to the current directory*, but each Cortex bash call resets `cwd` to
134
+ `~/.cortex`, so an absolute `@/path` fails ("--file must be a relative path"). Use
135
+ `--content -` and pipe the body in (`--content - < body.xml`, or a `<<'EOF'` heredoc).
136
+ - **Check `data.result`, not just exit code / `ok`.** A failed edit (e.g. a stale/bad
137
+ `--block-id`) still returns exit 0 and `"ok": true`, with `"result": "failed"` and a
138
+ terse, sometimes misleading warning ("content may be identical" can actually mean the
139
+ block id does not exist). Always read `data.result` (`success` | `partial_success` |
140
+ `failed`) and `data.warnings` before reporting success. After a `block_replace`,
141
+ re-`fetch --detail with-ids` because the old block id may no longer be valid.
142
+ - **Identity matters for visibility.** Editing defaults to `--as user`. If only the
143
+ `bot` identity is authenticated, create/edit still succeed, but the response carries
144
+ `permission_grant.status = "skipped"` — the document is owned by the bot and the human
145
+ user **cannot see it**. For any output the user must open, either complete the user
146
+ device-flow login (Step 2) first, or explicitly share the doc to them afterward. Don't
147
+ hand the user a bot-only URL and assume they can read it.
148
+ - **Bot scope coverage is partial.** The bot has the docx scopes but, as configured, is
149
+ missing `sheets:spreadsheet:write_only` (writing sheet cells) and `base:app:create`
150
+ (creating a Base) — it can create a spreadsheet file yet not write its cells. If a
151
+ sheets/base call fails with `app_scope_not_applied` / `missing_scopes`, either grant
152
+ the scope at the printed `console_url`, or switch to the `user` identity.
153
+
154
+ ## Troubleshooting
155
+
156
+ lark-cli error messages can be terse. When a command fails or flags are unclear,
157
+ introspect rather than guess:
158
+
159
+ ```bash
160
+ lark-cli docs --help
161
+ lark-cli schema docx.document.block.patch # or the relevant service.resource.method
162
+ lark-cli api <METHOD> <path> # raw OAPI when no shortcut fits
163
+ ```
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env bash
2
+ # Idempotent preflight for the official Lark/Feishu CLI (@larksuite/cli).
3
+ # - Installs lark-cli globally via npm if absent (skips when already present).
4
+ # - Optionally runs `config init` from Cortex's FEISHU_APP_ID / FEISHU_APP_SECRET.
5
+ # - Reports auth status; does NOT perform the interactive device-flow login
6
+ # (that is surfaced to the user by the feishu-doc skill).
7
+ #
8
+ # Usage: bash ensure-lark-cli.sh
9
+ # Exit: 0 = lark-cli present (installed or already there); non-zero = install failed.
10
+ set -uo pipefail
11
+
12
+ log() { printf '[ensure-lark-cli] %s\n' "$*"; }
13
+
14
+ # 1) Ensure the binary is present.
15
+ if command -v lark-cli >/dev/null 2>&1; then
16
+ log "lark-cli already installed: $(lark-cli --version 2>/dev/null | head -1)"
17
+ else
18
+ log "lark-cli not found — installing @larksuite/cli globally via npm ..."
19
+ if ! npm install -g @larksuite/cli; then
20
+ log "ERROR: npm install -g @larksuite/cli failed."
21
+ exit 1
22
+ fi
23
+ # npm global bin may not be on PATH for this shell; surface a hint if so.
24
+ if ! command -v lark-cli >/dev/null 2>&1; then
25
+ log "Installed, but lark-cli is not on PATH. Add \$(npm root -g)/../bin to PATH."
26
+ exit 1
27
+ fi
28
+ log "Installed: $(lark-cli --version 2>/dev/null | head -1)"
29
+ fi
30
+
31
+ # 2) Best-effort non-interactive app config from Cortex env (tenant-level credentials).
32
+ # `config init` refuses inside OpenClaw/Hermes agent workspaces; Cortex is neither,
33
+ # so this normally succeeds. Skip if already configured.
34
+ if [ -n "${FEISHU_APP_ID:-}" ] && [ -n "${FEISHU_APP_SECRET:-}" ]; then
35
+ if lark-cli config show >/dev/null 2>&1; then
36
+ log "lark-cli config already present (skipping config init)."
37
+ else
38
+ log "Configuring lark-cli app from FEISHU_APP_ID / FEISHU_APP_SECRET ..."
39
+ if printf '%s' "$FEISHU_APP_SECRET" | lark-cli config init --app-id "$FEISHU_APP_ID" --app-secret-stdin --brand feishu >/dev/null 2>&1; then
40
+ log "config init done."
41
+ else
42
+ log "config init did not complete (may already be bound, or needs manual setup)."
43
+ fi
44
+ fi
45
+ else
46
+ log "FEISHU_APP_ID / FEISHU_APP_SECRET not set — skipping config init."
47
+ fi
48
+
49
+ # 3) Report auth status (user-token login is interactive — handled by the skill, not here).
50
+ log "auth status:"
51
+ lark-cli auth status 2>&1 | sed 's/^/ /' || log " (unable to read auth status)"
52
+
53
+ log "Preflight complete. If not logged in, run the device-flow login (see feishu-doc skill)."
@@ -55,11 +55,11 @@ Review committed code for correctness and quality beyond spec match. Flag:
55
55
 
56
56
  Severity: defects that can produce incorrect results, corrupt state, leak resources, or break the contracted API are **Blockers**; readability and maintainability issues are **Nice-to-have**. Cite `file_path:line_number` and quote the problematic snippet; do not allege a bug without showing the control-flow path that reaches it.
57
57
 
58
- ### TDD discipline
59
- Coder must land tests alongside (or before) the implementation, with coverage over the spec's happy path **and** edge cases (boundaries, empty/null inputs, error paths, concurrency hazards relevant to the diff); missing tests, tests that don't exercise the new control-flow paths, or untested edge cases called out by the spec are **Blockers**.
58
+ ### Test discipline
59
+ When the project has a test setup, Coder must land tests alongside (or before) the implementation, with coverage over the spec's happy path **and** edge cases (boundaries, empty/null inputs, error paths, concurrency hazards relevant to the diff); missing tests, tests that don't exercise the new control-flow paths, or untested edge cases called out by the spec are **Blockers**. If the project has no test harness, verify correctness by the means the project already uses and do not treat the absence of tests as a Blocker.
60
60
 
61
- ### Full-suite pass (non-negotiable)
62
- Run the project's full test suite (`npm test` or equivalent). This includes not just unit tests but also architecture linters, integration tests, and regression suites. **Any test failure or architecture violation (e.g. dependency-cruiser error) is a Blocker.** Do not rely on Coder's claim that tests passed — run them yourself. If the suite had pre-existing failures before this invocation, verify that no NEW failures were introduced; new failures are Blockers regardless of pre-existing state.
61
+ ### Full-suite pass
62
+ If the project has a test suite, run it using the project's own command (e.g. `npm test`, `pytest`, `make test`). This includes not just unit tests but also any linters or architecture checks, integration tests, and regression suites the project configures. **Any test failure or lint/architecture violation is a Blocker.** Do not rely on Coder's claim that tests passed — run them yourself. If the suite had pre-existing failures before this invocation, verify that no NEW failures were introduced; new failures are Blockers regardless of pre-existing state.
63
63
 
64
64
  ### Git discipline
65
65
  - 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**.
@@ -74,7 +74,7 @@ Parameters, seeds, and data paths must live in committed files (config YAML, arg
74
74
  1. Read the spec end-to-end.
75
75
  2. Read the implementation summary (if one exists). Note declared commits and flagged ambiguities.
76
76
  3. `git log --oneline <pre-SHA>..HEAD` and `git diff <pre-SHA>..HEAD` on the invocation's commits.
77
- 4. **Run the full test suite** (`npm test` or equivalent). Confirm that every stage passes: architecture linter, unit tests, integration tests, regression suite. If any test or lint stage fails, it is a Blocker — do not proceed to code review until Coder fixes it (or mark it as a pre-existing failure with evidence).
77
+ 4. **If the project has a test suite, run it** with the project's own command. Confirm that every configured stage passes: linters or architecture checks, unit tests, integration tests, regression suite. If any test or lint stage fails, it is a Blocker — do not proceed to code review until Coder fixes it (or mark it as a pre-existing failure with evidence).
78
78
  5. Spot-check code changes against the spec: pick the non-trivial parameters or requirements the spec specified and verify them in the committed code.
79
79
  6. Review the diff for code quality: trace at least one non-trivial control-flow path per changed function; check boundary conditions, error paths, invariants, concurrency. Cite `file_path:line_number` for each concern.
80
80
  7. Check commit messages for spec-identifier references.
@@ -93,7 +93,7 @@ Parameters, seeds, and data paths must live in committed files (config YAML, arg
93
93
  - **Runtime-only config tolerance**: accepting "the flags are in the commit message" as equivalent to in-repo config. They are not.
94
94
  - **Bug-hunt skipping**: signing off on spec-match alone without tracing control-flow paths, boundary conditions, or error handling through the diff. Spec fidelity is not a correctness guarantee.
95
95
  - **Cosmetic over substantive**: flooding the review with style nits while missing a logic bug. Lead with Blockers; Nice-to-have is secondary.
96
- - **Test run omission**: signing off on an implementation without running the full test suite yourself. Coder's claim that tests pass is not evidence. Run `npm test` and check every stage. A dependency-cruiser error or a test regression that Coder missed is as much your failure as theirs.
96
+ - **Test run omission**: signing off on an implementation without running the project's test suite yourself when one exists. Coder's claim that tests pass is not evidence. Run the suite and check every stage. A lint/architecture error or a test regression that Coder missed is as much your failure as theirs.
97
97
 
98
98
  # Reviewer / QA Relationship
99
99
 
@@ -9,7 +9,7 @@ Your mission is to **faithfully implement the spec and commit it to git**, produ
9
9
 
10
10
  Cortex optimizes **Quality > Cost > Speed**. For you, that means:
11
11
  - **Quality**: reproducibility is non-negotiable. Configuration (parameters, seeds, paths) lives in committed files, not in runtime flags that are lost after the session.
12
- - **Cost**: wrong code silently burns downstream compute. TDD, reading before editing, and not improvising on ambiguous specs are cheaper than a re-run.
12
+ - **Cost**: wrong code silently burns downstream compute. Testing, reading before editing, and not improvising on ambiguous specs are cheaper than a re-run.
13
13
  - **Speed**: subordinate. Do not skip tests, do not skip commits, do not skip reading the spec end-to-end. Speed comes from parallel tool calls and avoiding sleep-poll loops, not from skipping discipline.
14
14
 
15
15
  # Inputs & Outputs Contract
@@ -35,17 +35,16 @@ Cortex optimizes **Quality > Cost > Speed**. For you, that means:
35
35
  - Implement exactly what the spec specifies. Do not refactor surrounding code "while you're in there". Do not add defensive checks, extra logging, or configurability not in the spec.
36
36
  - If the spec appears wrong or incomplete, **stop and escalate**; do not invent a fix.
37
37
 
38
- ### TDD via `/develop`
39
- - Before implementing non-trivial logic, write a failing test.
40
- - Run the test, confirm it fails, implement, confirm it passes.
41
- - Trivial glue code and obvious one-liners are exempt; use judgment but bias toward tests.
42
- - Code that governs correctness (computation, data handling, seed handling) **requires** a test regardless.
38
+ ### Testing
39
+ - Follow the project's existing testing practice. If the project has a test setup, add or update tests covering the logic you change. If the project practices test-driven development, write the failing test first, confirm it fails, implement, then confirm it passes.
40
+ - Code that governs correctness (computation, data handling, seed handling) should be tested whenever the project provides a way to test it. Trivial glue code and obvious one-liners are exempt.
41
+ - If the project has no test harness, verify by the means it already uses; do not scaffold a test framework unless the spec asks for it.
43
42
 
44
- ### Full-suite pass (non-negotiable)
45
- - After implementing and committing, run the project's full test suite (`npm test` or equivalent).
46
- - The full suite includes unit tests, architecture linters (e.g. dependency-cruiser), integration tests, and regression suites. Every stage must pass.
47
- - Do NOT commit or hand off until the full suite is green. A single red test or architecture violation means you are not done.
48
- - If the test suite had pre-existing failures before your invocation, note them explicitly in the implementation summary; you must still verify that no NEW failures were introduced by your changes.
43
+ ### Full-suite pass
44
+ - If the project has a test suite, run it after implementing and committing, using whatever command the project defines (e.g. `npm test`, `pytest`, `make test`).
45
+ - Run every stage the project configures — unit tests, linters or architecture checks, integration tests, regression suites. Every configured stage must pass.
46
+ - Do NOT commit or hand off until the suite is green. A single red test or lint violation means you are not done.
47
+ - If the suite had pre-existing failures before your invocation, note them explicitly in the implementation summary; you must still verify that no NEW failures were introduced by your changes.
49
48
 
50
49
  ### Git discipline
51
50
  - Commit your implementation **before** handing off (before downstream consumers run it, before QA reviews, before the thread hands back). The SHA must anchor the delivered code.
@@ -64,10 +63,10 @@ Cortex optimizes **Quality > Cost > Speed**. For you, that means:
64
63
  ## Procedural requirements
65
64
  1. Read the spec end-to-end. List any ambiguities. If there are any, stop and escalate. Do not proceed on assumptions.
66
65
  2. Read existing code that the implementation will touch. Understand before modifying.
67
- 3. Implement per spec. Use `/develop` for TDD on non-trivial logic.
68
- 4. Run the **full test suite** (`npm test` or equivalent) locally; confirm every stage passes (architecture linter, unit tests, integration tests, regression suite). If it fails, fix before committing.
66
+ 3. Implement per spec. If the project practices TDD, use `/develop` to drive it on non-trivial logic.
67
+ 4. If the project has a test suite, run it locally with the project's own command; confirm every configured stage passes (linters or architecture checks, unit tests, integration tests, regression suite). If it fails, fix before committing.
69
68
  5. Commit your implementation with a message referencing the spec identifier.
70
- 6. Run the full test suite one more time after committing to confirm the SHA is green.
69
+ 6. If the project has a test suite, run it once more after committing to confirm the SHA is green.
71
70
  7. Produce the implementation summary through the channel the thread template supplies: list changed files, commit SHAs, any flagged ambiguities, any environment changes, and the test suite pass/fail status.
72
71
 
73
72
  ## Prohibited behaviors
@@ -83,7 +82,7 @@ Cortex optimizes **Quality > Cost > Speed**. For you, that means:
83
82
  - **Hook bypass**: using `--no-verify` when a pre-commit hook blocks. Root-cause the failure; do not bypass.
84
83
  - **Debug rabbit hole**: more than 3 iterations debugging the same failure without structured analysis. Invoke `/debug-campaign`.
85
84
  - **Runtime-only config**: passing all the important knobs as CLI flags without landing defaults in the repo. Put them in a committed config.
86
- - **Partial test pass**: running only unit tests for the changed module while skipping integration tests, regression suites, or architecture linters. The full suite (`npm test`) must pass.
85
+ - **Partial test pass**: running only unit tests for the changed module while skipping integration tests, regression suites, or lint/architecture checks the project configures. The project's full suite must pass when one exists.
87
86
 
88
87
  # Reviewer / QA Relationship
89
88
 
@@ -165,6 +165,18 @@ export declare class ClaudeTuiSession {
165
165
  * have JsonlTail watching a non-existent path and timing out on first turn.
166
166
  */
167
167
  export declare function computeJsonlPath(cwd: string, sessionId: string): string;
168
+ /**
169
+ * Decide whether a TUI session should spawn with `--resume <id>` (vs `--session-id <id>`).
170
+ *
171
+ * `--resume` only succeeds when a Claude transcript already exists for that id. A *fresh* TUI
172
+ * session pre-registers its channel→sessionId mapping BEFORE the first Claude turn (so transcript
173
+ * replay / session naming work), which makes the orchestrator's generic "a session mapping exists
174
+ * ⇒ resume" heuristic ask to resume an id that has no transcript yet — Claude then exits with
175
+ * "No conversation found with session ID: <id>". Gating the resume request on the transcript
176
+ * actually existing keeps the first turn on `--session-id` (create) and lets only later turns /
177
+ * reconnects use `--resume`. Self-healing: a deleted transcript also correctly falls back to create.
178
+ */
179
+ export declare function resolveTuiResume(requestedResume: boolean, jsonlPath: string, exists?: (p: string) => boolean): boolean;
168
180
  /**
169
181
  * Convenience factory: real JsonlTail wired to the path. Used by production code; tests inject
170
182
  * a custom factory instead.
@@ -2,6 +2,7 @@
2
2
  // output: ClaudeTuiSession — interactive Claude under tmux with jsonl tail; implements turn lifecycle
3
3
  // pos: DR-0012 Phase 2 — parallel adapter to claude/adapter.ts; selects via spawn-args mode='tui'
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { existsSync } from 'node:fs';
5
6
  import * as path from 'path';
6
7
  import { createLogger } from '../../core/log.js';
7
8
  import { JsonlTail, JsonlEventNormalizer } from './jsonl-tail.js';
@@ -492,6 +493,20 @@ export function computeJsonlPath(cwd, sessionId) {
492
493
  const encoded = cwd.replace(/[/.]/g, '-');
493
494
  return path.join(TUI_JSONL_BASE, encoded, `${sessionId}.jsonl`);
494
495
  }
496
+ /**
497
+ * Decide whether a TUI session should spawn with `--resume <id>` (vs `--session-id <id>`).
498
+ *
499
+ * `--resume` only succeeds when a Claude transcript already exists for that id. A *fresh* TUI
500
+ * session pre-registers its channel→sessionId mapping BEFORE the first Claude turn (so transcript
501
+ * replay / session naming work), which makes the orchestrator's generic "a session mapping exists
502
+ * ⇒ resume" heuristic ask to resume an id that has no transcript yet — Claude then exits with
503
+ * "No conversation found with session ID: <id>". Gating the resume request on the transcript
504
+ * actually existing keeps the first turn on `--session-id` (create) and lets only later turns /
505
+ * reconnects use `--resume`. Self-healing: a deleted transcript also correctly falls back to create.
506
+ */
507
+ export function resolveTuiResume(requestedResume, jsonlPath, exists = existsSync) {
508
+ return requestedResume && exists(jsonlPath);
509
+ }
495
510
  /**
496
511
  * Convenience factory: real JsonlTail wired to the path. Used by production code; tests inject
497
512
  * a custom factory instead.
@@ -15,7 +15,7 @@ import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
15
15
  import { createEventStream } from '../normalize/event-stream.js';
16
16
  import { CancelledError, CORE_MCP_CONFIG, IDLE_SESSION_TIMEOUT, LOGS_DIR, MAX_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
17
17
  import { buildClaudeEnv, buildSpawnArgs } from './spawn-args.js';
18
- import { ClaudeTuiSession, defaultTailFactory } from './adapter-tui.js';
18
+ import { ClaudeTuiSession, defaultTailFactory, computeJsonlPath, resolveTuiResume } from './adapter-tui.js';
19
19
  import { TmuxControl } from './tmux-control.js';
20
20
  import { TUI_TMUX_NAME_PREFIX } from './defaults.js';
21
21
  import { buildPrompt, clearActivePlanFile, extractAskUserQuestions, extractResult, formatEvent, getCurrentPlanFilePath, isPlanFilePath, mergeSubstantialOutput, setActivePlanFile, } from './event-parser.js';
@@ -579,12 +579,16 @@ function getOrCreateTuiSession(config, sessionIdEffective) {
579
579
  const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
580
580
  const cwd = config.cwd || DATA_DIR;
581
581
  const opts = sessionOptionsFromSpawnConfig({ ...config, sessionId: sessionIdEffective });
582
+ // `--resume` only works once a transcript exists. A fresh TUI session pre-registers its
583
+ // sessionId before the first turn, so config.resume can be true with no transcript yet —
584
+ // gate it on the jsonl actually existing, else the first turn fails "No conversation found".
585
+ const needsResume = resolveTuiResume(config.resume, computeJsonlPath(cwd, sessionIdEffective));
582
586
  const sessionConfig = {
583
587
  channel,
584
588
  sessionId: sessionIdEffective,
585
589
  sessionKey: key,
586
590
  cwd,
587
- needsResume: config.resume,
591
+ needsResume,
588
592
  tools: opts.tools,
589
593
  systemPrompt: opts.systemPrompt,
590
594
  appendSystemPrompt: opts.appendSystemPrompt,
@@ -7,6 +7,14 @@
7
7
  * - completion: { type:'system', subtype:'task_updated', task_id, patch:{status:'completed'} }
8
8
  * { type:'system', subtype:'task_notification', task_id, status:'completed', summary }
9
9
  *
10
+ * IMPORTANT: task_updated{completed} and task_notification are TWO separate events, and the
11
+ * CLI emits task_updated FIRST — sometimes seconds before the matching task_notification
12
+ * (gaps up to ~24s observed when several run_in_background tasks finish close together).
13
+ * task_notification is the one that actually re-invokes the model (the continuation turn).
14
+ * So pending is keyed off task_notification ONLY; clearing on task_updated would let the
15
+ * count hit 0 while continuation turns are still undelivered, sealing a turn "done"
16
+ * prematurely (a continuation result resolving in that gap snapshots pendingCount==0).
17
+ *
10
18
  * When a background task completes the CLI spontaneously re-invokes the model and
11
19
  * emits a fresh turn whose terminating `result` carries `origin.kind:'task-notification'`
12
20
  * (see isContinuationResult). The adapter uses pendingCount to decide whether a turn's
@@ -11,6 +11,14 @@
11
11
  * - completion: { type:'system', subtype:'task_updated', task_id, patch:{status:'completed'} }
12
12
  * { type:'system', subtype:'task_notification', task_id, status:'completed', summary }
13
13
  *
14
+ * IMPORTANT: task_updated{completed} and task_notification are TWO separate events, and the
15
+ * CLI emits task_updated FIRST — sometimes seconds before the matching task_notification
16
+ * (gaps up to ~24s observed when several run_in_background tasks finish close together).
17
+ * task_notification is the one that actually re-invokes the model (the continuation turn).
18
+ * So pending is keyed off task_notification ONLY; clearing on task_updated would let the
19
+ * count hit 0 while continuation turns are still undelivered, sealing a turn "done"
20
+ * prematurely (a continuation result resolving in that gap snapshots pendingCount==0).
21
+ *
14
22
  * When a background task completes the CLI spontaneously re-invokes the model and
15
23
  * emits a fresh turn whose terminating `result` carries `origin.kind:'task-notification'`
16
24
  * (see isContinuationResult). The adapter uses pendingCount to decide whether a turn's
@@ -34,14 +42,19 @@ export class BgTaskTracker {
34
42
  this.pending.add(id);
35
43
  break;
36
44
  case 'task_updated':
37
- if (data.patch?.status === 'completed') {
38
- this.pending.delete(id);
39
- this.continuationArmed = true;
40
- }
45
+ // Intentionally a no-op for pending/arming, even on status 'completed'.
46
+ // task_updated marks the task's WORK as finished, but the CLI emits the
47
+ // matching task_notification LATER (observed gaps up to ~24s with several
48
+ // parallel tasks). task_notification is the event that actually re-invokes
49
+ // the model (the continuation turn). If we cleared pending here, the count
50
+ // could reach 0 while notifications are still undelivered, and a continuation
51
+ // turn resolving in that gap would seal the turn "done" prematurely. Pending
52
+ // is therefore keyed off task_notification only (see below).
41
53
  break;
42
54
  case 'task_notification':
43
55
  // Emitted when a background task finishes (status 'completed' or error);
44
- // this is the event that re-invokes the model.
56
+ // this is the event that re-invokes the model. It is the authoritative
57
+ // completion-delivery signal, so it (and only it) clears pending + arms.
45
58
  this.pending.delete(id);
46
59
  this.continuationArmed = true;
47
60
  break;
@@ -41,7 +41,16 @@ const FLAT_ENDPOINT_KEYS = ['keys', 'base_url', 'auth_style', 'passthrough', 'fa
41
41
  /** Synthetic mode name used to hold a flat endpoint config (aistatus assigns these to mode "default"). */
42
42
  const FLAT_MODE = 'default';
43
43
  // ─── Anthropic models (default tier) ─────────────────────────────
44
- const ANTHROPIC_MODELS = ['claude-fable-5', 'claude-4-8', 'claude-sonnet-4-6', 'claude-haiku-4-5'];
44
+ // Each 1M-capable model also exposes a "[1m]" variant — Claude Code's context-window suffix that
45
+ // opts the session into the 1M-token window. Haiku 4.5 is 200K-only, so it has no [1m] variant.
46
+ const ANTHROPIC_MODELS = [
47
+ 'claude-fable-5', 'claude-fable-5[1m]',
48
+ 'claude-opus-4-8', 'claude-opus-4-8[1m]',
49
+ 'claude-opus-4-7', 'claude-opus-4-7[1m]',
50
+ 'claude-opus-4-6', 'claude-opus-4-6[1m]',
51
+ 'claude-sonnet-4-6', 'claude-sonnet-4-6[1m]',
52
+ 'claude-haiku-4-5',
53
+ ];
45
54
  // ─── PI provider → upstream URL lookup (manually maintained) ────────────────
46
55
  /**
47
56
  * Map a PI built-in provider name to its real upstream URL. Used by `generateGatewayYaml` so PI