Commit Graph

409 Commits

Author SHA1 Message Date
matevip
4c56df2ed3 fix(wiki): add fail-closed option for empty source-path allow-list 2026-05-31 07:57:44 +08:00
matevip
3a781ef0d9 test(wiki): cross-feature end-to-end domain scenario 2026-05-31 07:57:31 +08:00
matevip
8b4e1a12f9 feat(wiki): scheduled single-owner source-directory watcher 2026-05-31 07:57:25 +08:00
matevip
cc8c9cf951 feat(wiki): knowledge-layer filter on wiki search 2026-05-31 07:57:18 +08:00
matevip
ad1f5b4a15 feat(wiki): fire count-threshold pipeline triggers after ingest 2026-05-31 07:56:58 +08:00
matevip
526a361488 feat(wiki): restricted Skill pipeline step executor 2026-05-31 07:56:51 +08:00
matevip
15a8b2d73c feat(wiki): LLM pipeline step executor via model routing 2026-05-31 07:56:45 +08:00
matevip
85f5df394b feat(wiki): page-type count-threshold trigger for pipelines 2026-05-31 07:56:38 +08:00
matevip
5278568594 test(wiki): drop unnecessary @DirtiesContext from new E2E tests 2026-05-31 07:56:31 +08:00
matevip
6e0e62556f feat(wiki): pipeline run orchestration with pluggable step executors 2026-05-31 07:56:24 +08:00
matevip
c3388c3f1e feat(wiki): pipeline runtime schema — definitions, runs, step runs 2026-05-31 07:56:17 +08:00
matevip
66e4788226 feat(wiki): fact/experience dependency graph and stale propagation engine 2026-05-31 07:56:10 +08:00
matevip
28284fbcac feat(wiki): layered-knowledge schema — layer, dependency table, stale columns 2026-05-31 07:55:55 +08:00
matevip
7a79fe93d0 test(wiki): isolate profile/metadata E2E tests from the shared file DB 2026-05-31 07:55:44 +08:00
matevip
16a7aadbcd feat(wiki): unified source-path validation with symlink resolution and allowed roots 2026-05-31 07:54:48 +08:00
matevip
eb63ce4865 feat(wiki): validate and persist structured page metadata on ingest 2026-05-31 07:54:41 +08:00
matevip
b50e384e0d feat(wiki): inject KB pageType profile into the batch-create prompt 2026-05-31 07:54:34 +08:00
matevip
bea48bcf89 feat(wiki): pageType profile CRUD API and service operations 2026-05-31 07:54:27 +08:00
matevip
7cd9971596 feat(wiki): schema validator for structured page metadata 2026-05-31 07:54:20 +08:00
matevip
7f4987c30a feat(wiki): resolve effective pageType profile per KB with built-in default 2026-05-31 07:54:13 +08:00
matevip
368797e619 feat(wiki): add KB-scoped pageType profile table and page metadata columns 2026-05-31 07:54:06 +08:00
matevip
ec47d19bf8 feat(wiki): gate wiki write/mutate tools by pageType permission 2026-05-31 07:53:59 +08:00
matevip
502b8406a6 feat(wiki): per-agent pageType read permission gate for wiki tools 2026-05-31 07:53:48 +08:00
matevip
f1c55b80e8 feat(memory): route summarized typed facts into structured memory 2026-05-30 07:36:20 +08:00
matevip
de98368b4e feat(channel): shared inbound media pipeline with magic-byte typing and retry 2026-05-30 07:30:38 +08:00
matevip
7e9f2ee54c fix(memory): prefer recalled personal memory over knowledge base for user/project questions 2026-05-29 18:03:13 +08:00
matevip
d4ea75a806 fix(approval): deny approval-required tools in non-interactive runs 2026-05-29 18:03:13 +08:00
matevip
ceb4da642b fix(memory): rebuild agent on workspace file change so memory edits apply 2026-05-29 16:05:21 +08:00
matevip
a27084f9cf feat(memory): recall project facts via query-conditioned prefetch 2026-05-29 16:05:10 +08:00
matevip
96ed3e8aa7 fix(feishu): mirror router conversationId fallback for recent-file cache 2026-05-29 10:15:06 +08:00
matevip
237f649e7e fix(tool-guard): trust shared skill root outside the workspace boundary 2026-05-29 09:59:19 +08:00
matevip
82538ca3aa feat(llm): add Claude Opus 4.8 + 4.8 Fast model entries 2026-05-29 07:06:19 +08:00
lichuan
bd02734d61 feat(agent): add knowledge base binding tab to agent editor (#237)
Agents now have a per-agent primary wiki KB stored on
mate_agent.primary_kb_id. KBs remain workspace-shared — selecting one in
the agent editor only chooses the default wiki target for that agent, it
does not change the KB's ownership or visibility.

Backend
- AgentEntity: add primary_kb_id field (FieldStrategy.ALWAYS so the UI
  can clear it back to "no primary")
- AgentController#update: switch body to Map<String, Object> so we can
  tell "field missing" apart from "explicit null" via containsKey, then
  convertValue back to AgentEntity
- WikiKnowledgeBaseService:
  - new resolvePrimaryKb(agentId): prefers agent.primary_kb_id when it
    points to a workspace-visible KB; falls back to legacy
    kb.agent_id marker, then to most-recently-updated workspace KB
  - listByAgentId now returns the full workspace set (KBs are
    workspace-shared under the new model)
  - update(id, name, description) no longer touches agent_id
- WikiController: new GET /knowledge-bases/bindable for the UI picker;
  PUT /knowledge-bases/{id} no longer reads agentId
- WikiKnowledgeBaseEntity: add FieldStrategy.ALWAYS on embeddingModelId
  and configContent so explicit nulls actually unbind/clear instead of
  being silently skipped by MyBatis-Plus's NOT_NULL default
- Migrations V129 (H2 + MySQL): add primary_kb_id column + index, backfill
  from legacy kb.agent_id, MySQL uses INFORMATION_SCHEMA guard +
  PREPARE/EXECUTE for idempotency
- WikiKnowledgeBaseServiceTest: 13 cases, all passing

Frontend
- Agents.vue: new "Knowledge Base" tab, radio-select bindable KBs
- API: listBindableKBs() + Agent.primaryKbId typed string | number | null
- IDs handled as strings throughout (Snowflake-safe)
- i18n keys for the new tab in zh-CN and en-US
2026-05-29 06:00:52 +08:00
matevip
af9928bf54 fix(wiki): case-only rename portability + SpringBootTest regression suite 2026-05-28 08:18:01 +08:00
matevip
a71c49d374 feat(wiki): analyze-stage slug whitelist + code-aware enrich applier 2026-05-28 08:17:27 +08:00
matevip
16eac232c4 feat(wiki): cascade delete + rename to keep wikilinks consistent 2026-05-28 08:17:19 +08:00
matevip
2b3c068db9 feat(wiki): broken-link lint with job-based async scan 2026-05-28 08:17:04 +08:00
matevip
65cf53779a refactor(approval-grants-ui): paginated list, Element Plus icons, shorter sidebar label 2026-05-27 15:08:41 +08:00
matevip
fe072191ea feat(approval): REST surface for auto-grant strategies with tiered authorization 2026-05-27 14:07:56 +08:00
matevip
2653356613 feat(approval): record human-approval and timeout resolutions, retire grants on conversation delete 2026-05-27 14:07:48 +08:00
matevip
b7e923fac4 feat(approval): grant-based auto-approve with safety floor and resolution log 2026-05-27 14:07:39 +08:00
matevip
ac090afde3 fix(workflow): pre-check unique name on create/rename, return 409 instead of 500 (Fixes Gitee #IJPYWA) 2026-05-26 23:35:04 +08:00
matevip
c8b25e1bfb fix(agent): deny skill-discovery tools when skillsDisabled (#184 follow-up) 2026-05-26 22:16:51 +08:00
matevip
0ac325a337 feat(agent): explicit "no skills / no tools" opt-out flags (#184) 2026-05-26 22:07:12 +08:00
matevip
ff2620dfcf fix(wiki): harden kbName/kbId routing — ambiguous fail-closed, kbId param, prompt cleanup (#224) 2026-05-26 14:31:07 +08:00
matevip
d2b23c049c fix(wiki): let agents reach every visible KB via kbName + wiki_list_kbs (#224) 2026-05-26 13:53:32 +08:00
matevip
7f5652b2f0 fix(agent): replace per-loop head/tail trim with anchored token-budget budgeter 2026-05-26 07:34:25 +08:00
matevip
07eb625d11 fix(agent): collapse SystemMessages at egress to fix LM Studio 400 (#218)
Some OpenAI-compatible providers (LM Studio's built-in server, certain
strict-mode vLLM / SGLang deployments) reject 400 "System message must
be at the beginning" when SystemMessages appear after user / assistant
/ tool messages. The reasoning loop currently emits four SystemMessage
segments — main prompt at index 0, skill catalog inserted at index 1,
progress-ledger snapshot and stale-reminder appended at the end of
nonHistoryPrefix after the runtime-context UserMessage. The latter two
violate the strict shape, so conversations on LM Studio 400 on the
first turn (reported in #218).

Add MessageNormalizer: collects every SystemMessage in the outbound
prompt regardless of position, joins their text with a blank-line
separator, and emits a single SystemMessage at index 0. Non-system
messages keep their relative order, so AssistantMessage(tool_calls) ↔
ToolResponseMessage adjacency is preserved verbatim (required by strict
pair validators).

Wire it into doStreamCall as the first pre-egress step so every node
(reasoning, step-execution, summarizing, plan-generation, limit-exceeded)
inherits the fix without per-node changes, and any future node that
emits multiple SystemMessages stays compliant.

The transformation is semantically equivalent on permissive providers
(OpenAI, DashScope, Ollama, DeepSeek, Kimi, Doubao, GLM) — the merged
token sequence matches what they would have seen across N SystemMessages
— and safe on non-OpenAI protocols (Anthropic, Vertex / Gemini), whose
adapters already extract SystemMessages into a top-level system field
and receive an identical payload.

Kill switch: -Dmateclaw.llm.message-normalizer.enabled=false reverts to
the prior behavior for emergency rollback.

Tests: 11 unit tests on MessageNormalizer cover empty / no-system /
canonical / mid-list / tail / blanks / tool-pair preservation / Prompt
option-reference preservation / kill switch. 1 wiring test pins the
call site in doStreamCall. Full vip.mate.agent.** suite (504 tests)
stays green.

Closes #218.
2026-05-25 17:57:03 +08:00
matevip
a37074a9a6 fix(tool): close three sandbox follow-up gaps surfaced by review
1. Relative parent traversal in shell commands (HIGH)

   validateShellCommand only scanned absolute path tokens, so commands
   like `cat ../mateclaw/CLAUDE.md`, `cd .. && cat foo`, or
   `ln -sf ../bar breakout` had no absolute path to trip the check.
   From a workspace cwd that's a real escape — `..` segments resolve
   against the JVM cwd at file-tool time and reach anywhere the user
   can read.

   Add a second pass: any token containing `..` as a path segment is
   resolved against the workspace root via root.resolve(token).
   normalize(); reject when the result falls outside. In-workspace
   traversal like `subdir/../sibling` normalizes back inside and
   passes. Identifiers without slashes (e.g. version strings with
   `1.2..3`) are not treated as paths.

2. Shell validation and process working directory used different
   context sources (MEDIUM)

   execute_shell_command validated with the explicit ToolContext, but
   buildShellProcess called WorkspacePathGuard.getWorkingDirectory()
   (no-arg), which only sees the ThreadLocal fallback. Today the
   ToolExecutionExecutor sets both so the discrepancy is latent, but
   a future direct Spring AI invocation passing only ToolContext would
   validate against one basePath and exec against another. Thread ctx
   through buildShellProcess and call getWorkingDirectory(ctx) so
   validation and execution agree on a single source of truth.

3. Absolute agent override could disable workspace scoping (MEDIUM)

   resolveAgentBasePath accepted an absolute override verbatim, even
   when it pointed outside the workspace root. An admin (or any
   account with agent-edit permission) could set workspaceBasePath="/"
   or another team's repo and bypass workspace boundaries entirely.

   When a workspace has its own basePath, require absolute overrides
   to sit underneath it. The caller in build() catches the rejection,
   logs WARN, and falls back to the workspace basePath so chat stays
   available rather than crashing agent construction. When the
   workspace has no basePath there's no boundary to enforce, so legacy
   behavior is preserved.

Test coverage: WorkspacePathGuardShellTest grows from 17 to 23 (six
new cases for `cd ..`, relative parent traversal, relative symlink
escape, deeper traversal, in-workspace normalization, and the
identifier false-positive guard). AgentGraphBuilderBasePathResolutionTest
grows from 7 to 10 (three new cases for in-workspace absolute,
outside-workspace absolute rejection, and no-workspace legacy
behavior). All 45 sandbox-area tests pass with no regressions.
2026-05-25 17:55:56 +08:00
matevip
7272d8f633 fix(tool): allow standard /dev/* character devices in shell sandbox 2026-05-25 16:38:31 +08:00
matevip
b09a220ec7 fix(tool): enforce workspace boundary on shell commands and file metadata tools 2026-05-25 16:26:16 +08:00
matevip
9e9a96f674 fix(agent): resolve relative workspaceBasePath under workspace root 2026-05-25 15:58:05 +08:00
matevip
692362e7a7 fix(channel): flush emergency save before SSE idle eviction disposes the run 2026-05-24 23:01:14 +08:00
matevip
f1d9104422 fix(channel): evict SSE RunState by inactivity, not wall-clock age 2026-05-24 23:01:04 +08:00
matevip
c36abf38b8 feat(agent): inject stale-ledger reminder when the model stops updating 2026-05-24 23:00:35 +08:00
matevip
9f2fb3db23 feat(agent): echo full ledger snapshot in progress_update tool result 2026-05-24 23:00:24 +08:00
matevip
7736f6b0ab fix(agent): serialise progress-ledger upsert per conversation 2026-05-24 23:00:17 +08:00
matevip
e953f8be5a feat(agent): age-based compaction of older tool-response bodies 2026-05-24 23:00:11 +08:00
matevip
05289e6bdb feat(agent): per-conversation progress ledger to survive context trims 2026-05-24 23:00:03 +08:00
matevip
fe9610dfa6 fix(dashboard): count tool calls from assistant.metadata, not role=tool rows 2026-05-24 22:58:02 +08:00
matevip
8030a41125 fix(api): return 400 on path-variable type mismatch instead of 500 2026-05-24 22:57:51 +08:00
matevip
c857d6dd45 fix(agent): retry empty LLM completion before treating it as final answer 2026-05-24 22:57:19 +08:00
matevip
481cece733 fix(channel): preserve queued chat inputs across turns 2026-05-24 22:57:08 +08:00
matevip
a9c2d45790 Harden goal approval and workspace flows 2026-05-23 22:55:16 +08:00
matevip
5cd6e841a4 feat(skill): broaden script security scan + GBK zip-import fallback 2026-05-23 22:55:10 +08:00
matevip
3fc121c6b7 fix(tool): show runtime names in tools admin 2026-05-23 22:54:57 +08:00
matevip
123d912f84 fix(skill): allow template file access 2026-05-23 09:08:01 +08:00
matevip
cef1730e6e feat(tool,skill,ui): progressive tool/skill disclosure (load_skill + enable_tool + tier UI) 2026-05-23 09:07:45 +08:00
matevip
5f571e86a2 feat(agent,ui): multi-level subagent delegation tree 2026-05-22 13:44:01 +08:00
matevip
81915ccfae feat(tool): read_file can page through an oversized single line via startColumn (#190) 2026-05-21 22:27:09 +08:00
matevip
9e93c52d9a fix(goal): real evaluator, retry refactor, hardened node + extra edges 2026-05-21 22:27:00 +08:00
matevip
c34e8290ac feat(goal,ui): inline set-goal prompt, terminal system-line, sidebar dot 2026-05-21 22:26:40 +08:00
matevip
9c5ad29d42 chore(llm): drop unused imports, add XIAOMI_MIMO cross-turn cache tests 2026-05-21 17:24:53 +08:00
倪程伟
7861f603eb
fix(llm): MiMo thinking 模式 reasoning_content 多轮对话兼容修复 (#189)
MiMo V2 系列在 thinking 模式下,assistant 消息携带 tool_calls 时必须同时包含 reasoning_content,否则提供方返回 400。

- ModelFamily 新增 MIMO_THINKING 族,detect() 添加 mimo* 匹配
- FallbackPolicy 新增 XIAOMI_MIMO(patchCrossTurn=true, patchNonToolCall=true)
- 新增 ReasoningContentCache,按 tool_call_ids 回放真实推理内容
- 缓存作用范围:所有 patchCrossTurn=true 的 thinking provider(MiMo + DeepSeek)
- NodeStreamingChatHelper 流式响应完成后写入缓存

Closes #188
2026-05-21 17:15:35 +08:00
matevip
e61b05bba0 fix(tool): read_file no longer returns empty content + infinite retry on oversized single lines (#190) 2026-05-21 16:26:24 +08:00
matevip
a910004b3b feat(agent): digital-employee builder skill to auto-create agents and chain them into a workflow (#165) 2026-05-21 16:26:04 +08:00
matevip
03e68d3c74 fix(agent): structure-aware truncation to stop mid-JSON cuts inducing hallucination (#187) 2026-05-21 15:13:07 +08:00
matevip
c9e54e820f fix(goal,ui): live ring update after agent-triggered setGoal / addGoalCriterion 2026-05-21 14:43:59 +08:00
matevip
89f8413db8 test(agent): sync LaneDPerformanceFixesTest with MAX_RETRIES bump 2026-05-21 14:43:52 +08:00
matevip
6646e91585 feat(goal): built-in tools for agent-driven goal management 2026-05-21 14:43:20 +08:00
matevip
ce74a0ae48 feat(goal): graph topology + evaluation node wired into ReAct + Plan-Execute 2026-05-21 14:43:13 +08:00
matevip
ac6c8a18e3 feat(goal): persistent cross-turn goal with self-evaluation scaffolding 2026-05-21 14:43:01 +08:00
matevip
6a4318c268 fix(channel): IM conversations respect per-conversation model selection (#183) 2026-05-20 17:49:03 +08:00
matevip
43136fc663 fix(channel): sweep orphan tool rows + guard rules; scope rule name to channel 2026-05-20 16:35:57 +08:00
matevip
12ff190392 feat(feishu): transcribe inbound voice messages via SttService 2026-05-20 16:35:46 +08:00
matevip
6b4456043e fix(feishu): outbound generated-file URLs become native attachments 2026-05-20 16:01:03 +08:00
matevip
6b397a10ed feat(feishu): inbound file/audio/video download — SDK path + cache push 2026-05-20 15:53:40 +08:00
matevip
71e08b015e sync: Feishu approval card 5-chain hotfix — verified end-to-end in production 2026-05-20 15:24:47 +08:00
matevip
090bb64c6a sync: Feishu channel-native tool provider + DbRuleGuardian generic guard 2026-05-20 12:29:29 +08:00
matevip
85d7ee23c4 sync: ChannelToolProvider SPI + node-local reconcile framework for channel-native tools 2026-05-20 12:18:51 +08:00
matevip
a9fa8e7fb1 sync: interactive approval card on Feishu via Schema-2.0 button + card.action callback 2026-05-20 12:05:47 +08:00
matevip
3554da8dbc sync: inject sender context into agent prompt + Feishu DONE ack hook 2026-05-20 11:51:58 +08:00
matevip
35f010d7a1 sync: Feishu CardKit streaming-card adapter via cardkit/v1 SDK 2026-05-20 11:37:12 +08:00
matevip
0e1b8ca564 sync: componentized media upload SPI + Feishu SDK-backed file sender 2026-05-20 11:23:33 +08:00
matevip
3340885da3 fix(llm): skip chat-style probe for embedding-prefix models in DashScope discovery 2026-05-20 10:14:25 +08:00
matevip
a6b5e3b515 refactor(llm): extract testable embedding protocol routing + drop dead fromProviderId 2026-05-20 10:14:12 +08:00
matevip
73ab31a13c fix(feishu): fail open when bot open_id is unavailable 2026-05-20 10:13:34 +08:00
倪程伟
af3e68d271 fix(feishu): use SDK mentions field for require_mention group filtering (#163)
Closes #162

require_mention=true previously degraded to a no-op when botPrefix was unset:
shouldProcess() returned true for all messages and checkAccess() fell through
unconditionally, so any group message would be answered — including ones where
the @mention targeted another user.

FeishuChannelAdapter now consults the Feishu SDK's mentions field directly:

- WebSocket: read EventMessage.getMentions(); webhook: read mentions[] from the
  JSON payload. In both paths each mention's id.open_id is compared against the
  bot's own open_id.
- Bot open_id is fetched lazily via /open-apis/bot/v3/info and cached on the
  adapter instance. If the call fails the message is allowed through, matching
  the previous behaviour.
- The require_mention gate is applied at the top of handleFeishuMessage so 1:1
  chats are unaffected.

Tests: 15 unit cases covering null/empty inputs, bot mentioned, only-other
mentioned, bot among multiple mentions, and malformed payloads.
2026-05-20 08:49:11 +08:00
倪程伟
ee0c229f52
feat(feishu): support Interactive Card JSON for structured message rendering (#161)
Auto-route Agent replies to Feishu Interactive Card (schema 2.0) when the
content carries structure — JSON object / array, Markdown with code blocks
or headings, or long-form prose — and keep the original text path for
short plain replies.

- FeishuCardFormatter: package-private detect() + render() helper
  - JSON object → two-column summary card
  - JSON array (≤4 fields) → table component; (>4 fields) → div per item
  - Markdown → lark_md card with 'AI 助手' header
  - Long text (>300 chars with paragraph breaks) → plain_text card
  - JSON embedded in Markdown code blocks is recognised across all fences
- FeishuChannelAdapter
  - sendMessage() honours channel config 'card_format' (auto | always | never)
  - sendCard() POSTs interactive messages; ou_-prefixed targets use open_id
  - updateCard() PATCHes an existing message (streaming-update hook)
- Tests: 32 unit cases covering every detect path and render branch

Closes #141
2026-05-20 08:42:02 +08:00
matevip
db16ff02a5 chore: drop external project name references from code comments 2026-05-20 08:09:43 +08:00
matevip
c0f9d1d9fb test(wiki): add adversarial HTML normalization tests and harden skeleton-tag handling 2026-05-19 21:23:13 +08:00
matevip
c1b878b7e1 fix(agent): fail over to backup providers when the primary is rate-limited 2026-05-19 20:06:21 +08:00
matevip
c6d51f8ced fix(wiki): resolve an agent's own knowledge base before shared ones 2026-05-19 16:53:12 +08:00
matevip
3d643f909d feat(skill): typed wrapper tools for declared script entrypoints 2026-05-19 09:56:39 +08:00
matevip
31d4d014ed fix(skill): normalize runSkillScript JSON args 2026-05-19 09:56:33 +08:00
matevip
520429ac6f test(skill): end-to-end coverage for the lifecycle curator 2026-05-19 09:56:27 +08:00
matevip
4cd21056a0 feat(skill): automatic lifecycle archival for idle skills 2026-05-19 09:55:59 +08:00
matevip
d53d66abe3 feat(chat): per-conversation model selection (#150) 2026-05-18 16:27:27 +08:00
matevip
0ff8da0caa fix(llm): stop MODEL_NOT_FOUND from evicting the whole provider (#150) 2026-05-18 16:27:20 +08:00
matevip
3157dde1f4 fix(memory): route long-term memory edits to the file being edited (#148) 2026-05-18 11:28:01 +08:00
matevip
75107ac815 feat(llm): native Gemini chat builder, Nano Banana image gen, xAI/Grok provider 2026-05-18 10:00:55 +08:00
matevip
a88edbdd07 refactor(llm): decouple model construction from the agent graph layer (#147) 2026-05-18 07:47:49 +08:00
matevip
18df97a8e6 fix(agent): scope MCP tools to explicit per-agent selection (#117) 2026-05-17 09:24:56 +08:00
matevip
e647f1d6cf fix(cron): isolate scheduled-job runs from shared conversation (#142) 2026-05-17 07:58:10 +08:00
matevip
b4add8b139 fix(agent): keep wiki tools available to skill-bound agents (#143) 2026-05-16 23:00:45 +08:00
matevip
dca71b5a43 test(task): de-flake the submitOneShot enrolled-latch ordering test 2026-05-16 14:51:57 +08:00
matevip
f56f4b059a fix(workspace): reject impossible calendar dates in memory snapshot import 2026-05-16 14:51:52 +08:00
matevip
725fdd1e0f feat(workspace): memory snapshot export and import with whitelist 2026-05-16 14:51:25 +08:00
matevip
81c6488a3c feat(tool): async sub-agent delegation with attribution gate 2026-05-16 14:51:20 +08:00
matevip
419ee57cc8 feat(agent): structured compaction on prompt-too-long preserves prefix 2026-05-16 14:51:14 +08:00
matevip
b9c0ead024 feat(workspace): keyword search across agent memory files 2026-05-16 14:51:09 +08:00
matevip
d90591fa35 feat(task): generic one-shot Callable runner with parent-conv cancel 2026-05-16 14:51:04 +08:00
matevip
c320aab1ba fix(skill): synthesize SKILL.md body for ACP-derived virtual skills (#136) 2026-05-16 14:50:51 +08:00
matevip
130dfd5278 fix(skill): synthesize SKILL.md for MCP-derived virtual skills (#136) 2026-05-16 14:50:46 +08:00
matevip
3b9b4d79d5 feat(skill): scope skill catalog and runtime by workspace (#135) 2026-05-15 20:01:25 +08:00
matevip
65dd4c1f49 fix(skill): cascade-delete agent-skill bindings on skill removal (#127) 2026-05-15 10:17:41 +08:00
matevip
adf5d93975 fix(wiki): align HTTP status with R envelope and harden config + edit paths 2026-05-14 23:01:00 +08:00
matevip
1bba59fc7e fix(skill): encode bridge virtual ids in the top two bits 2026-05-14 18:18:21 +08:00
matevip
139a478bcd fix(skill): give CJK-only MCP/ACP names a stable id-based slug 2026-05-14 18:18:15 +08:00
matevip
d1be02985c fix(agent): collapse model-predicted tool results that the actual tool replaced 2026-05-14 15:44:03 +08:00
matevip
bf3f4af913 fix(agent): structured tool-call replay + final-answer-only content (#120) 2026-05-14 07:46:30 +08:00
matevip
1ea90c25cb fix(agent): make head-orphan repair order-sensitive — a later same-id assistant does not redeem an earlier orphan 2026-05-13 09:03:16 +08:00
matevip
bff57924d6 fix(agent): repair head-side orphan tool responses on the pagination cut 2026-05-13 09:03:10 +08:00
matevip
51b5eceb7d feat(context): preserve spill markers across compaction phases, persist enriched boundary, broadcast compact_status SSE (#110) 2026-05-13 08:50:28 +08:00
matevip
86a6829102 feat(executor): retention sweep and per-conversation purge for tool-result spill files 2026-05-13 08:50:22 +08:00
matevip
7015d1513c feat(context): anchor the first user message after compaction so long tasks remember the original goal 2026-05-13 08:50:15 +08:00
matevip
37894a6978 fix(context): never compact across a split tool_call ↔ tool_response pair 2026-05-13 08:50:08 +08:00
matevip
ae3d27922d fix(context): preserve raw older tool results instead of rewriting them to a lossy summary 2026-05-13 08:50:02 +08:00
matevip
8f49b0ec92 fix(executor): spill raw tool result before falling back to inline truncate 2026-05-13 08:49:56 +08:00
matevip
cc5d7d5ad0 fix(agent): auto-include enabled MCP tools in effective allowlist (#108) 2026-05-12 21:24:36 +08:00
matevip
0ffc224623 chore(test): backfill mateclaw-server/src/test/ that earlier PRIVATE_ITEMS pattern accidentally excluded
The PRIVATE_ITEMS list contained the bare 'test' entry, which rsync
interprets as 'any directory named test at any depth' — so it caught
the root-level /test/ scratch directory (intended) AND every src/test/
under each module (not intended).

Pattern is already anchored to /test (root-only). This commit rsyncs
the accumulated src/test/ tree forward so opensource has the unit tests
that have been written / updated against existing src/main/ code since
the pattern regression. Going forward each per-commit sync will carry
src/test/ files along with the main change.
2026-05-12 17:38:08 +08:00
srant1
5f77434953
fix(llm): activate default model after OpenAI OAuth and gate provider checks by enabled
OAuth token save now promotes the first available chat model when no usable default exists. Default-model resolution and provider availability checks require Provider.enabled=true alongside credentials, so disabled Providers no longer return stale defaults. /models/enabled drops the single-Provider hard-code so OpenAI OAuth and other enabled chat models surface in selectors. Docker exposes the 1455 PKCE callback via MATECLAW_OAUTH_OPENAI_CALLBACK_BIND_HOST (default 127.0.0.1) and a port mapping; deployment mode stays Host-driven.
2026-05-12 09:58:30 +08:00
matevip
74928d615d feat(memory): Dream v2 Phase 1 — lifecycle mediator foundation
Wire memory-facing events (turn-started, turn-completed, session-ended,
memory-written) through a single MemoryLifecycleMediator so
MemoryProvider implementations can hook into the agent conversational
flow without spreading side-effects across the runtime.

Ten atomic steps shipped under feat/dream-v2-p1-lifecycle:

- A.1 + A.2: MemoryLifecycleMediator class + TurnContext value object
- A.3: TurnStartedEvent / TurnCompletedEvent domain events
- A.4: MemoryLifecycleEventListener bean for Spring event plumbing
- A.5: MemoryProvider.onMemoryWrite default method (backward compatible)
- A.7: wire the mediator into AgentService at the right hook points
- A.8: LifecycleFlagGuardTest — feature flag must gate every hook
- A.9: MemoryLifecycleMediatorTest — unit coverage per hook
- A.10: LifecycleRecallCountIT — F4 regression across the stack

Feature flags (all default OFF; enable per phase after staging):
- mate.memory.lifecycle-mediator-enabled
- mate.memory.dream.focused-enabled
- mate.memory.dream.archive-enabled

This is Phase 1 foundation only — focused-dream and archive-dream
providers arrive in later phases.
2026-04-20 17:31:21 +08:00
matevip
a171f2ac0e fix(wiki): recover raw materials stuck in processing on server restart
Root cause: recoverOnStartup() only reset mate_wiki_processing_job rows,
not mate_wiki_raw_material. claimForProcessing() only accepts pending,
so restart-orphaned processing rows were permanently stuck — frontend
showed "preparing..." forever.

Fix:
- Add WikiRawMaterialService.recoverStuckRawMaterialsOnStartup():
  resets processing→pending, clears progress fields, fires
  WikiProcessingEvent when autoProcessOnUpload is enabled
- WikiAutoConfiguration: call raw recovery after job recovery
- Execution order: job table first (queued), then raw table (pending)

Test: WikiRawMaterialRecoveryTest — 4 cases: reset + events, reset
without events (autoProcess=false), noop on empty.
2026-04-19 19:37:50 +08:00
matevip
527a67374d fix(failover): probe URL construction + permissive 4xx/5xx handling
Two real bugs the user restart surfaced — both turned healthy providers
into HARD-removed false positives.

Bug #1 — URL duplication
  OpenAiCompatibleListModelsProbe always concatenated /v1/models, so
  providers whose Base URL already includes the version segment got the
  wrong URL:
    LMStudio  http://localhost:1234/v1     → /v1/v1/models  → 404
    ZhipuAI   .../api/paas/v4              → /v4/v1/models  → 404
  Fix: detect a trailing /vN suffix and append /models instead. Six unit
  tests in OpenAiCompatibleListModelsProbeTest lock the rule down.

Bug #2 — 404 false positives
  Kimi for Coding API does not expose /v1/models even though chat works
  fine, so the probe correctly received a 404 and incorrectly HARD-removed
  the provider from the pool. Other vendors will hit the same — listing
  is not a universal contract.
  Fix: classify HTTP responses semantically.
    401 / 403  → HARD remove (real auth failure)
    404 / 405 / 410 → fail-open (endpoint missing, server may be alive)
    other 4xx / 5xx → fail-open (probe inconclusive — let chat decide)
    network errors → fail (unreachable)
  This is the same philosophy as ChatGPTOAuthStatusProbe: when we cannot
  cheaply confirm health, we do not proactively penalize the provider.
  Same logic applied to Anthropic + DashScope probes for consistency.

Net effect on the user deployment after restart:
  - kimi-code stays in pool (404 → fail-open) → primary path works again
  - lmstudio + zhipu-cn also stay in pool (URL bug fixed)
  - dashscope + ollama unchanged (real 200 OK)

Tests: 6 new for resolveModelsPath. The 2 unrelated WikiRawMaterialDedupTest
failures pre-date this commit and live in ba86bea.
2026-04-19 19:36:38 +08:00
matevip
4700d0312d fix(wiki): deduplicate raw material uploads across all processing statuses
Root cause: addFile()/addText() hash dedup only matched rows with
status=completed, so the same file uploaded while in partial/pending/
processing/failed status would create a duplicate row.

Fix:
- Remove .eq(processingStatus, "completed") from dedup queries — match
  any non-deleted row with the same content hash in the KB
- On dedup hit: completed/pending/processing → return as-is;
  partial/failed → trigger reprocess (partial enters resume branch)
- Clean up the newly uploaded temp file when dedup discards it
- Frontend: uploadRawFile/addRawText check for existing id in the list
  before unshift to prevent visual duplicates

Test: WikiRawMaterialDedupTest — 10 cases covering all 5 statuses,
reprocess triggers for partial/failed, no-op for others, insert only
when no match.
2026-04-19 19:36:13 +08:00
matevip
3d213eb281 chore: sync multiple commits from private dev
Covers 15 upstream commits (private mirror → public):

Multi-provider failover (RFC-009):
- PR-0: extract ChatModelBuilder strategy seam
- PR-1a: AvailableProviderPool data structure
- PR-1b: startup provider liveness probe + 4 protocol strategies
- PR-1c: wire AvailableProviderPool into runtime chat-model selection
- PR-1d: provider pool REST endpoint + UI badges
- PR-1e: manual reprobe trigger + auto-reprobe on provider config change
- PR-3: per-agent provider preferences (agents can override the
  org-wide fallback chain)

Wiki subsystem (RFC-029~033):
- Relation model, resilient background jobs, light-weight processing
  path, retrieval enhancement, frontend redesign (single landing commit)
- Follow-up fixes: null guards + stats query + i18n polish, move
  WikiProcessingJobMapper to repository/ for @MapperScan, align
  implementation with RFC-029~031 spec
- Copy pass: replace "富化 / enrich" wording with clearer "链接 / link"
- Style: switch enrich/repair buttons to @element-plus/icons-vue
2026-04-19 18:37:44 +08:00
matevip
3b11a3def6 fix(failover): AUTH_ERROR triggers fallback chain + UI splits provider 401 from session expiry
Two related issues from the Kimi-401 user report:

1. Backend (NodeStreamingChatHelper): a primary AUTH_ERROR (e.g. Kimi 401
   with an invalid API key) returned immediately without trying the
   fallback chain — a fallback provider with a different, valid key
   never got a chance. Even with DashScope correctly configured as the
   fallback, the user chat dead-ended on a 401.

   The original assumption ("auth never self-heals so do not retry")
   holds for the primary same-model retry loop but is wrong for the
   fallback chain — different providers have different keys. Apply the
   same break-into-fallback policy that BILLING and MODEL_NOT_FOUND
   already use. recordPrimary(false) is preserved so the cooldown
   counter still accumulates.

2. Frontend (chatError.ts + i18n): the error-text matching for
   /认证|auth|unauthorized|401/i was so broad it matched the substring
   "auth" inside URLs like https://api.kimi.com/.../auth, classifying
   any model 401 as user "session expired" and rendering the misleading
   "页面将自动跳转到登录页" copy. (The redirect itself only fires from
   /api/v1/auth/* axios paths and SSE-connection 401s, not from this
   payload-text path — but the copy alone is the worst kind of false
   alarm.)

   Add a new ChatErrorCategory provider_auth_error and split the
   pattern matching: narrow auth_expired (HTTP 401 / 登录已过期 /
   session expired / 凭证失效) is matched FIRST, then the broad
   401-ish pattern routes to provider_auth_error. BACKEND_ERROR_TYPE_MAP
   for AUTH_ERROR is also remapped, since structured backend payloads
   currently always come from LLM providers — never from our own
   /api/v1/auth path.

Tests
- NodeStreamingChatHelperFailoverTest (5 cases): primary 401 →
  fallback succeeds; chain skips auth-failing fallback to next healthy
  one; whole-chain failure surfaces last AUTH_ERROR (no silent drop);
  BILLING regression unchanged; primary-success path does not touch
  chain
- Browser preview verified: new i18n keys resolve in en-US, classifier
  correctly routes "[错误] 401 from kimi.com" → provider_auth_error
  while "[错误] HTTP 401 from /api/v1/auth/ping" stays auth_expired
- 186 tests pass (was 181 + 5 new); vue-tsc clean

Do-not-touch list: handleAuthFailure() in useStream/api/index.ts (real
session-expiry path) is unmodified — only the misclassification
upstream is fixed. auth_expired i18n copy is unchanged.
2026-04-19 17:45:15 +08:00
matevip
7ba8fe602b feat(llm): track primary health + split BILLING / MODEL_NOT_FOUND from generic client errors
Track the primary model health, not just fallback entries
- NodeStreamingChatHelper accepts primaryProviderId via a new 5-arg
  constructor; AgentGraphBuilder passes ModelConfigEntity.getProvider()
- Before the 5-retry primary loop, check
  healthTracker.isInCooldown(primaryProviderId): if true, log + broadcast
  "主模型暂时不可用(冷却中),直接尝试备选模型..." and short-circuit
  straight to the fallback chain. Prevents a degraded primary from
  burning 30+ seconds of backoff on every conversation turn.
- recordPrimary(success/failure) now fires on every primary verdict —
  AUTH, BILLING, MODEL_NOT_FOUND, EMPTY_RESPONSE, generic UNKNOWN, and
  the explicit success path. Three consecutive failures push the
  primary provider into cooldown automatically.
- Legacy 1/2/3-arg constructors leave primaryProviderId null; tracking
  silently disables for them so existing tests/wiring keep working.

Split BILLING and MODEL_NOT_FOUND out of CLIENT_ERROR / AUTH_ERROR
- BILLING (HTTP 402, "insufficient_quota", "credit balance is too low",
  "billing_hard_limit_reached", "quota exceeded"): payment failure on
  primary does not kill the call — a different provider may have credits.
  Skips same-model retries and heads to fallback chain.
- MODEL_NOT_FOUND (HTTP 404, "Model not exist", "model_not_found",
  DashScope "[InvalidParameter] url error"): unknown model id will not
  start working on retry. Was previously misclassified as CLIENT_ERROR
  and terminated the whole call; now routes to fallback so a different
  provider can attempt with its default model.
- classifyError ordering matters: BILLING / MODEL_NOT_FOUND are matched
  BEFORE the generic 400 / Bad Request branch, otherwise they would be
  swallowed by CLIENT_ERROR.

Tests
- ErrorClassificationTest: 11 tests, covers multi-vendor error phrasing
  for both new types + regression checks that 401 / 429 / 400 still
  classify as before
- NodeStreamingChatHelperFallbackChainTest: +2 tests verifying
  primaryProviderId persistence on the new constructor and null on
  legacy ones
- 181 tests pass (was 168 + 13 new)
2026-04-19 17:10:27 +08:00
matevip
7b12c5f0c9 feat(llm): provider health tracker + UI editor for failover priority
UI — Failover priority editor
- ProviderConfigRequest + ProviderInfoDTO carry fallbackPriority
- ModelProviderService.updateProviderConfig persists it (null = unchanged);
  toProviderInfo exposes the current value to the UI (defaults to 0)
- ProviderConfigModal advanced panel exposes a number input with hint
- ProviderCard shows a "Fallback #N" badge for chain members so the
  priority order is visible at a glance without opening the modal
- 5 new i18n keys (zh + en) — verified to resolve at runtime via i18n.global.t

Backend — Per-provider health tracker
- ProviderHealthTracker: ConcurrentHashMap-backed counters; N consecutive
  failures (default 3) push the provider into a cooldown window (default
  5 min) during which the chain walker skips it. Success resets both
  counter and cooldown atomically. Lazy expiry on lookup so dead entries
  do not accumulate.
- ProviderHealthProperties exposed under mateclaw.llm.failover.health.*
  with sane production defaults
- New FallbackEntry record (providerId + ChatModel) replaces raw
  List<ChatModel> in the chain so the walker can correlate cooldown
  state to entries; AgentGraphBuilder.buildFallbackChain returns the
  new type
- NodeStreamingChatHelper takes the tracker through a new 4-arg
  constructor and consults it before each fallback call; records
  success/failure on each chain attempt. Legacy 2/3-arg constructors
  preserved as @Deprecated wrappers (synthetic providerId means no
  health tracking on the legacy path — that path is opt-out anyway)

Tests
- ProviderHealthTrackerTest (9 tests): below/at threshold, success
  reset, cooldown expiry (via reflection on the min-clamp setter),
  disabled-tracker no-op, null-providerId safety, per-provider
  isolation, snapshot output
- NodeStreamingChatHelperFallbackChainTest updated to FallbackEntry
  field type — verifies providerId + ChatModel survive the chain
- 168 tests pass (was 159 + 9 new)

Verification
- mvn test green; vue-tsc clean; live UI confirms i18n resolution
2026-04-19 16:57:03 +08:00
matevip
ed37e81e7e feat(llm): multi-model failover chain driven by per-provider priority
Replaces the hardcoded single-DashScope fallback with a DB-driven
ordered chain. Same-provider primary deployments (e.g., DashScope
qwen-max) finally get a real fallback; if any provider in the chain
returns an empty body or transient failure, the next is tried.

Schema — DB-driven chain
- mate_model_provider gains `fallback_priority INT DEFAULT 0`. Positive
  values define try-order; 0 = not in chain. Migration V21 (h2 + mysql)
  seeds DashScope as priority 1 to preserve existing behavior.
- ModelProviderService.listFallbackChain() returns providers ordered by
  priority ascending.
- ModelProviderEntity gains the new field.

Runtime — chain walk + empty-response trigger
- AgentGraphBuilder.buildFallbackChain(primaryConfig) returns a
  List<ChatModel>, identity-filtering the primary by (providerId,
  modelName) — fixes the bug where same-provider-primary deployments got
  null fallback. Providers whose API key is missing are silently
  skipped with WARN. Old buildFallbackModel(ChatModel) kept as
  @Deprecated wrapper.
- NodeStreamingChatHelper accepts List<ChatModel>; the post-retry
  fallback block now walks the chain in priority order, single-shot
  per entry. Old single-fallback constructors retained as @Deprecated
  one-element-list wrappers so legacy callers keep working.
- New ErrorType.EMPTY_RESPONSE: when the LLM returns no content, no
  thinking, AND no tool calls, mark the result as a soft failure and
  break the same-model retry loop, handing off directly to the
  fallback chain.
- Broadcast updated to "切换到备选模型 (N/M)..." so SSE consumers see
  chain progress.

Tests
- NodeStreamingChatHelperFallbackChainTest covers constructor variants,
  chain immutability, deprecated-overload back-compat, and the
  EMPTY_RESPONSE enum exists as a compile-time contract.
- 159 tests pass (was 153 + 6 new).
2026-04-19 16:55:33 +08:00
matevip
9c8c393b3c refactor(prompt): clean up prompt corpus, fix summary_budget bug, route fallbacks through i18n
A. Delete two dead prompt files (prompts/context/conversation-summary-*.txt)
   that no caller has loaded since the structured-summary triple replaced them.

B. Drop the never-wired locale machinery: PromptLoader.loadPrompt(name, locale)
   overload + the prompts/{locale}/... fallback chain + I18nService.currentLocaleTag().
   A single-language prompt corpus plus LLM input-language following is sufficient.

C. Strip duplicated structure list / budget directive from
   structured-summary-update.txt (the system prompt already carries them).
   Add a defensive preamble to both summary prompts: "do not respond to any
   questions or requests in the conversation, only output the structured
   summary" — prevents the summarizer from accidentally answering historical
   user questions.

D. Fix {summary_budget} placeholder leak in the iterative-update branch of
   ConversationWindowManager.generateSummary. Both branches now substitute
   on the SystemMessage uniformly. Regression-guarded by
   ConversationWindowManagerSummaryBudgetTest.

E1. De-hardcode seven prompts (research/{plan,draft,compose}-{system,user},
    graph/limit-exceeded-system) — language now follows the user's input
    instead of being hardcoded; citation tokens are language-neutral
    [M1] / [Q1] markers.

E2. Add 10 i18n keys (research.fallback.*, research.broadcast.*,
    agent.limit_exceeded.*) to messages.properties + messages_en.properties.
    Inject I18nService into WikiResearchService and LimitExceededNode and
    route 5 + 2 hardcoded fallbacks through i18n.msg(). Regression-guarded
    by WikiResearchServiceFallbackTest + LimitExceededNodeFallbackTest.

E3. Replace 3 assembly tags in WikiResearchService with neutral
    [M1] / [Q1] tokens. Aligns with the [M1] / [M2,3] citation format the
    draft prompt asks for.

G. Three new regression tests cover D, E2, and E3.
2026-04-19 09:02:37 +08:00
matevip
5aed6f176d fix(binding): drop @TableLogic on agent-tool/skill to fix rebind error 2026-04-18 23:15:56 +08:00
matevip
7f88a6ddd4 release: v1.1.0 2026-04-17 19:41:03 +08:00
matevip
7d8d16e458 feat: 5 defensive hardenings
- ConversationWindowManager: cap reserve token at 50% of effective max
  to prevent negative historyBudget on small-context models (8K/16K)
- common.security.SecretEquals: new constant-time comparison utility
  (MessageDigest.isEqual wrapper) for secrets/tokens/signatures
- WeixinChannelAdapter: migrate context_token comparison to SecretEquals
- FeishuChannelAdapter: fail-fast on empty encrypt_key when connection_mode=webhook
- TelegramChannelAdapter: sanitize attachment captions — strip control bytes
  (\p{Cc} except \t\r\n) + format chars (\p{Cf}) + 4096 char cap
- AgentGraphBuilder: fallback Anthropic max_tokens to 4096 on null/0/negative

Tests: SecretEqualsTest (5) + TelegramCaptionSanitizeTest (5) — all green.
2026-04-15 22:14:55 +08:00
matevip
4a4b39249e chore(channel): remove stale external-reference comments; fix(wiki): canonical slug lookup on merge path 2026-04-15 16:44:02 +08:00
matevip
ef8120413c feat(wiki): real-time SSE progress + parallel page generation + partial-resume; fix concurrent slug collisions; fix skill overwrite + hub retry 2026-04-15 10:34:11 +08:00
matevip
99befe0d25 fix(agent): prevent ReAct degenerate repetition and harden loop termination 2026-04-05 22:34:03 +08:00
matevip
579d60125b Initial commit: MateClaw — Java + Vue 3 AI Assistant System
Full-stack AI assistant built on Spring AI Alibaba.
Features: ReAct Agent, Plan-and-Execute, MCP Protocol, Multi-Model, Multi-Channel.

Apache-2.0 License
2026-04-04 19:03:49 +08:00