* fix: harden pagination and fallback warnings
* fix: close the clusters Claude+Codex both missed — events loss/busy-wait, cookie gateway-ok, OAuth state, TOML rewrite
Builds on the Codex pagination/fallback/credentials sweep with the high-value
findings neither pass had covered (v1.3.17 deep health check):
- 簇D get_new_events HIGH: drain() advanced the global cursor to EOF, so a caller
capping its result permanently lost every event past the cap. readFrom/drain
now consume at most maxEvents and advance the cursor only past what was
returned; the tail stays pending. truncated now means "more pending — call
again". (Residual: a non-"*" profile filter still shares the single global
cursor — documented; per-profile cursor tracked separately.)
- 簇D withMutex busy-spin → Atomics.wait park. The old `while (Date.now()<until){}`
pegged a core and froze the event loop during lock contention.
- 簇B cookie gateway-ok: search/createChat/getGroupInfo discarded the `ok` flag
and returned []/null on a non-2xx gateway response, misreporting a transient
failure (expired cookie / rate limit) as an empty result. They now throw,
mirroring _sendMsg. (_sendMsg packet.status hardening deferred to live
inspection of a real success packet — see report.)
- 簇E OAuth: authorize URL + loopback /callback now carry & verify a random
`state` (CSRF / cross-flow code-injection guard, OAuth 2.0 §10.12).
- 簇E _removeTomlServer: replaced the greedy regex (it stopped at the `[` inside
`args=["…"]`, orphaning fragments, and ate to EOF when feishu was last) with a
TOML-table-aware line scan that preserves unrelated tables and user comments.
- quick wins: error-codes maps 99991672 (oauth_scope_not_granted); listChats/
readMessagesAsUser guard `data.data` against a code:0-empty envelope;
switch_profile not-found text points to the SSOT setup flow.
New regression tests (fixture/stub, no live API), all wired into test-all.js
alongside Codex's 3: config-toml-removal (10), events-drain-bounded (6),
cookie-gateway-ok (6). smoke 85/9, tool-count 85, gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: profile-state safety (簇A) + save_path validation + oc_ resolve guard
- keepalive --all no longer flips the global `active` pointer to route a UAT
refresh persist. It threads the target profile via official._persistProfile →
persistUAT → persistToConfig(updates, targetProfile) → persistProfileUpdate.
The old flip raced a live server and, on a mid-flip crash, left
credentials.json::active permanently pointed at the wrong profile.
- _resolveCookieChatId: require a UNIQUE exact-name match. The old fuzzy
fallback (`results.find(r => r.type==='group')`) picked the FIRST group of any
name, so a common/ambiguous chat name could resolve oc_xxx to an unrelated
chat and send the message there. Now errors with guidance instead.
- _ocCache is now keyed by active profile. Numeric chat ids are identity-scoped,
so a switch_profile used to reuse the previous profile's numeric id and send
to the wrong/nonexistent chat. (both 簇A/簇B)
- maybeSave (download save_path): enforce the documented absolute-path contract
and reject null bytes; a relative path silently resolved against the server
cwd. (簇E security; full root-confinement left as a product decision)
- setup.js: the pointer-only summary logged ${targetProfile} but writes
${harnessActive} — corrected the misleading line.
New test test-resolve-and-save.js (7 cases) wired into test-all.js. All 7
v1.3.17 regression suites green; smoke 85/9; tool-count 85; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: LOW-cluster hardening — oauth XSS/shell, ctx single-build, search-error wrap, contacts cache key, smoke stderr
- oauth loopback callback: HTML-escape the reflected err.message and scope
before embedding them in the page; open the browser via execFileSync (no
shell) on mac/linux so a configured APP_ID / URL can't be shell-interpreted.
- server.js: build ctx once per tool call and share it between the router and
the handler (they must reason over one currentProfile, not two closures).
- im-read read_p2p: wrap uc.search — now that cookie search throws on a non-2xx
gateway (this PR's 簇B fix) an expired cookie would otherwise reject raw
instead of the friendly "use search_contacts" guidance.
- contacts.getUserById: key the name cache by `${userIdType}:${userId}` — the
same id string under open_id vs union_id vs user_id is a different lookup.
- scripts/smoke.js: buffer the last 4 KB of server stderr and include it in the
"server exited" error instead of discarding it, so a failing gate says WHY.
smoke 85/9; tool-count 85; all 7 regression suites green; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: events ENOSPC drop-marker + remove dead fallbackWarning guards
- ws-server: when an events.jsonl append fails (disk full) the owner-arbitrated
get_new_events never drains the in-memory buffer, so those events are lost to
consumers. Track the drop count and, on the next successful append, emit a
sticky _events_dropped marker into the log so consumers learn events were
missed instead of silently losing them.
- identity-state: _buildFallbackWarning always returns a non-empty string
(BOT_ONLY included, intentionally), so the `if (fallbackWarning)` guards were
always-true dead branches implying a falsy case that can't occur. Assign
unconditionally — behaviour identical, intent clear.
smoke 85/9; tool-count 85; existing identity-state/events tests + all 7
regression suites green; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: auto-switch hint hygiene — banner only on real failover, clear stale hints
profile-router withProfileRouting:
- [autoSwitched] is now annotated only when an earlier profile actually failed,
not when a stored hint was honoured on the first attempt (the intended
primary path). The old banner fired on every hinted-first success, misleading
the model into thinking a recovery happened.
- A stale hint that was tried first and failed is now CLEARED when the active
profile wins, so the next call stops re-trying (and wasting a forbidden
round-trip on) the known-bad profile. Hints now converge on what works.
New deterministic test test-profile-router-hint.js (4 cases: failover banner+set,
clean-success no-op, stale-hint clear, hinted-first no-banner) wired into
test-all.js. smoke 85/9; tool-count 85; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: request granular task scopes (task:task → task:task:read/write)
Root-cause of "UAT 总是掉 / 任务工具老要重新授权": NOT a token-renewal failure.
Decoding the live token shows auto-renewal is healthy — the access token was
silently refreshed (auth_time ~37 days old = no re-consent, 2h AT rolled via the
7-day refresh_token). refreshUAT updates _uatExpires after each refresh and has
the v1.3.15 invalid_grant self-heal, so the chain holds.
The real cause: Feishu granularized `task:task` into `task:task:read` /
`task:task:write`. The token was consented with the old name, so task tools
return 99991679 ("请重新授权") on the user path and 99991672 on the app path —
which feels like the UAT dropped. Request the granular scopes instead.
NOTE (external, can't be done from code): the app must also enable
task:task:read/write in the Feishu developer console, then re-run
`npx feishu-user-plugin oauth` to re-consent — only then do task tools work.
Updated SCOPES + docs/AUTH-SETUP.md (check-scopes CI gate green).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: multi-profile auto-switch is in-memory only + always restores (簇A)
Auto-switch read trials (and explicit via_profile pins) used ctx.setActiveProfile,
which writes credentials.json::active (the durable SSOT peer MCP processes read)
and runs an fsync-grade write + SHA + credMonitor hook fan-out — per transient
trial. A peer reading mid-trial adopted the wrong active profile.
- Add ctx.setActiveProfileEphemeral: in-memory flip + client-cache invalidation
only, no disk persist / no sync. profile-router now uses it for ALL per-call
routing; durable setActiveProfile is reserved for the explicit switch_profile
tool.
- Restructure the auto-switch loop so wasActive is restored in a finally on
every exit (return / throw / exhaust) — an unexpected throw between a switch
and the handler can no longer leak the trial profile into the process-global
currentProfile.
New test case E (ephemeral-only + finally-restore-on-throw) added to
test-profile-router-hint (5 cases). All suites green; smoke 85/9; tool-count 85.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: nit cluster — getBlockChildren pagination, bitable 500-cap, repairTail window, doc-block mode; document 1254000 code-reuse
- getBlockChildren now paginates to completion (was a single page_size:500),
so createDocTable no longer aborts after creating an empty >500-cell table.
- manage_bitable_record enforces Feishu's 500-per-call batch cap locally with a
clear error (was an opaque API failure / partial write).
- repairTail grows its scan window past a >8KB partial trailing record, and
empties a whole-file single corrupt record, instead of giving up at 8KB and
letting the next append concatenate into one corrupt line.
- manage_doc_block(create) mode detection no longer counts an empty children:[]
as a selected mode (`[].filter(Boolean)` kept []).
- error-codes/profile-router: document that 1254000/1254301 are reused by Feishu
across APIs (upload-transient-retry on writes vs bitable-read profile-switch);
the two never fire on the same call-site — not a contradiction, no behaviour
change needed.
New test test-nits-batch.js (6 cases) wired into test-all.js. smoke 85/9;
tool-count 85; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: events single-owner concurrency — steal-detecting heartbeat, atomic rotate, drop dead reconfigureProfile
- acquireLongLived now stamps a unique ownerToken in the lock body. heartbeat()
re-reads it and refreshes mtime ONLY if still ours — so a force-steal (rename
+ EXCL recreate under a new owner) is detected instead of a blind utimesSync
succeeding on the successor's file. release() likewise only unlinks our own
lock, never a successor's.
- server.js owner heartbeat checks that return value: on a lost lock it
_relinquishOwnership (stop WS + heartbeat, null handle WITHOUT release, re-run
election) so we never double-write events.jsonl as a phantom second writer.
- Defer-rotate now runs the rename + cursor-reset inside cursor.rotateUnderLock
(the same mutex drain() takes), so rotation is atomic w.r.t. a concurrent
drain on a peer process.
- Removed the dead/misleading ws-server reconfigureProfile (restarted with the
same construction-fixed registrations; real switching tears down + rebuilds).
New test test-events-concurrency.js (5 cases) wired in. smoke 85/9; tool-count
85; all events tests green; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: per-profile event cursor + download memory guard + document _sendMsg send-status
- get_new_events: each profile now drains its OWN cursor file
(events.cursor.<profile>.json; "*"/"any" keeps the legacy events.cursor.json
"all" cursor), so one profile's poll never advances a shared cursor past
another profile's unread events. readFrom takes a match predicate (count only
this profile's events toward the cap, but advance past others — they have
their own cursors); _system events are delivered to every profile. A single
shared lock keeps all drains + rotate mutually atomic; rotateUnderLock now
uses the SLOWEST profile cursor for the caught-up check and resets ALL
per-profile cursors.
- downloadMessageResource guards on Content-Length before arrayBuffer() so a
giant/hostile attachment can't OOM the process (50 MiB cap), on both the UAT
and app paths.
- _sendMsg: documented (from live probes) why there is no packet.status failure
guard — success returns status:null and invalid ids return non-2xx (already
caught), so a "status!==0" check would false-positive; the empty-packet path
is mitigated upstream by the exact-match oc_ resolver.
New test test-events-per-profile-cursor.js (4 cases) wired in. All events tests
green (back-compat preserved); smoke 85/9; tool-count 85; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: redact cookie bytes in non-ASCII error + token-based get_wiki_node fallback
- LARK_COOKIE non-ASCII validation error no longer echoes a 40-char window of
the surrounding cookie bytes (which could overlap live sl_session/csrf material
and reach logs/the agent transcript). Reports only the offending pasted char +
its index; the rest is redacted.
- get_wiki_node: stop gating the obj_token fallback on a brittle wiki error-code
regex (which missed codes Feishu adds over time). Key off the token instead —
if it's a recognizable non-wiki obj_token, getNode can never succeed on it, so
synthesize the node-shape; a real wiki token (inferObjTypeFromToken → null)
still surfaces the genuine error.
- (calendar need_notification: already documented in the schema — "on create
(default true)" — no change needed.)
test-nits-batch extended (8 cases) with both get_wiki_node paths. smoke 85/9;
tool-count 85; gitleaks clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: make oauth callback-wait timeout env-configurable (FEISHU_OAUTH_TIMEOUT_MS)
The 120s default is tight when re-consent needs an account switch or the app is
missing a scope (the consent page errors and there's no authorize button until
fixed). Allow overriding via FEISHU_OAUTH_TIMEOUT_MS (min 10s); default
unchanged at 120s. Surfaced while re-authorizing the UAT for the newly-granted
task:task:read/write + search:message scopes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: sync server.json with the v1.3.17 list_wiki_spaces description
The events/per-profile sweep updated the list_wiki_spaces description (cursor
stall now reports truncated:true + cursorUnavailable:true) and the smoke
baseline, but server.json (MCP registry manifest) wasn't regenerated. Re-synced
via scripts/sync-server-json.js — 85 tools, no other change.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: release v1.4.0
Reliability hardening from a full multi-agent health check. Bumps all version
sources (package.json + lock, .claude-plugin/.cursor-plugin plugin.json,
SKILL.md, mcp-registry.json x2, .mcpb manifest; server.json regenerated) to
1.4.0 and adds the [1.4.0] CHANGELOG entry.
Also brought into this version:
- docs/AUTH-SETUP.md: document FEISHU_OAUTH_TIMEOUT_MS.
- CLAUDE.md (+ derived AGENTS.md): caveats for the granular task:task:read/write
scope (re-consent needed) and get_new_events per-profile cursors.
85 tools + 9 prompts unchanged; no breaking API. See CHANGELOG [1.4.0] for the
full Changed/Fixed/Security list (15 commits since v1.3.17).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: align test-uat-read-paths with empty-page advancing-cursor behavior
The v1.4.0 pagination work made searchDocs/searchWiki emit an ADVANCING
nextOffset (offset + page_size) + cursorWarning on an abnormal has_more:true +
empty page — upholding "hasMore:true must carry a resumable cursor". The old
test still asserted the superseded behavior (nextOffset withheld / undefined),
which failed CI's npm test. Updated the two assertions to the new behavior
(searchDocs 5→15, searchWiki 5→25, cursorWarning present); matches
test-pagination-cursor-invariant. npm test now exits 0 with no credentials.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>