From 38540dce3dc9e33be745caeb2c1859495cd47425 Mon Sep 17 00:00:00 2001 From: crispinhu27 <353173575+crispinhu27@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:38:15 +0800 Subject: [PATCH] fix(assistant): recover from skill directory symlinks --- internal/domain/runner_workspace.go | 3 + internal/httpapi/assistant.go | 24 +++- internal/httpapi/assistant_diagnostics.go | 3 + internal/httpapi/assistant_failure.go | 18 ++- internal/httpapi/assistant_native_session.go | 17 ++- .../httpapi/assistant_native_session_test.go | 65 +++++++++- internal/httpapi/assistant_process.go | 29 ++++- internal/httpapi/assistant_subagents.go | 8 +- internal/httpapi/assistant_subagents_test.go | 6 +- internal/runner/conversation.go | 8 +- .../runner/conversation_process_guard_test.go | 26 +++- internal/runtime/conversation_assets.go | 117 ++++++++++++++++-- internal/runtime/conversation_assets_test.go | 77 ++++++++++++ internal/runtime/conversation_process.go | 23 ++-- 14 files changed, 378 insertions(+), 46 deletions(-) diff --git a/internal/domain/runner_workspace.go b/internal/domain/runner_workspace.go index bfe7ba5e1..ee2c322ee 100644 --- a/internal/domain/runner_workspace.go +++ b/internal/domain/runner_workspace.go @@ -175,6 +175,9 @@ const ( // WorkspaceErrorTerminalActive: an exclusive human terminal holds the // workspace; waiting does not help until the user closes it. WorkspaceErrorTerminalActive = "workspace_terminal_active" + // WorkspaceErrorConversationState carries a safe, conversation-relative + // preparation error from the execution machine. + WorkspaceErrorConversationState = "conversation_state" ) // WorkspaceRestoreStatus describes restoration separately from SOP execution. diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index a67652658..1030e9bc7 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -360,6 +360,8 @@ func (h *assistantHandlers) chat(c *gin.Context) { sess.Notify = func(kind string, value any) { if emit != nil { emit(kind, value) + } else if event, ok := value.(assistantStreamEvent); kind == "thought" && ok { + activity.add(publicAssistantEvent(event, user)) } } sess.mu.Lock() @@ -463,13 +465,20 @@ func (h *assistantHandlers) chat(c *gin.Context) { } c.JSON(status, payload) } + failSetup := func(err error) { + status, _ := assistantGenerationFailure(modelCtx, err) + failure := assistantDiagnosticsFrom(modelCtx).fail(modelCtx, err, user) + fail(status, failure.Message) + } var nativeSession *assistantNativeSession // Every conversation runs in its own CLI root; shared ones switch to the // native session root below. The root's home also carries the skills. cliRoot := assistantConversationRoot(ownerID, req.SessionID) - if err := runtime.ValidateConversationRoot(cliRoot); err != nil { - fail(409, err.Error()) - return + if !shared { + if _, err := runtime.ConversationSkillLinks(cliRoot); err != nil { + failSetup(err) + return + } } nativeContinuationReady := false var turnUsage assistantTurnUsage @@ -508,7 +517,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { var err error nativeSession, err = openAssistantNativeSession(req, saved, user, sourceRoot) if err != nil { - fail(409, "共享会话缓存不可用或正在使用,请稍后重试") + failSetup(err) return } defer nativeSession.Close() @@ -521,7 +530,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { turn = h.turnPrompt(req, sourceRoot, false) } if err = nativeSession.begin(); err != nil { - fail(500, "无法保存共享会话缓存") + failSetup(err) return } cliRoot = nativeSession.root @@ -545,12 +554,15 @@ func (h *assistantHandlers) chat(c *gin.Context) { // drains output and lets each CLI commit tool results to its native // journal before the next process is allowed to resume that journal. restarted := false + reportSkillLinks := func(paths []string) { + reportRemovedConversationSkillLinks(ctx, u, paths, toolSession.Notify) + } for switches := 0; switches < 8; switches++ { if !resume { workspaceRepositoryHash = "" } req.workspaceMode = toolSession.RuntimeMode == domain.AssistantModeWorkspace - if err := h.writeConversationAssets(cliRoot, req); err != nil { + if err := h.writeConversationAssets(cliRoot, req, reportSkillLinks); err != nil { return "", err } mcp, settings, err := stageConversationToolFiles(cliRoot, toolFiles) diff --git a/internal/httpapi/assistant_diagnostics.go b/internal/httpapi/assistant_diagnostics.go index e40530b34..e68f1e97c 100644 --- a/internal/httpapi/assistant_diagnostics.go +++ b/internal/httpapi/assistant_diagnostics.go @@ -85,6 +85,9 @@ func (d *assistantDiagnosticsCollector) checkpointSnapshot(g domain.AssistantGen func (d *assistantDiagnosticsCollector) fail(ctx context.Context, err error, user domain.User) domain.AssistantFailure { f := classifyAssistantFailure(ctx, err) + if f.Code == "CONVERSATION_STATE_ERROR" { + f.Message = sanitizeAssistantDiagnostic(f.Message, user, 2048) + } if d == nil { return f } diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.go index 75055eaf3..dba9de521 100644 --- a/internal/httpapi/assistant_failure.go +++ b/internal/httpapi/assistant_failure.go @@ -69,9 +69,14 @@ func assistantCLIStreamFailure(line string) error { func assistantGenerationFailure(ctx context.Context, err error) (int, string) { failure := classifyAssistantFailure(ctx, err) status := http.StatusBadGateway - if failure.Code == "EXECUTION_MACHINE_UNAVAILABLE" || failure.Code == "WORKSPACE_BOUND_ELSEWHERE" || failure.Code == "WORKSPACE_REBOUND" { + switch failure.Code { + case "SHARED_SESSION_BUSY": + status = http.StatusConflict + case "CONVERSATION_STATE_ERROR": + status = http.StatusInternalServerError + case "EXECUTION_MACHINE_UNAVAILABLE", "WORKSPACE_BOUND_ELSEWHERE", "WORKSPACE_REBOUND": status = http.StatusServiceUnavailable - } else if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + case "EXECUTION_CANCELLED", "EXECUTION_TIMEOUT": status = http.StatusGatewayTimeout } return status, failure.Message @@ -94,6 +99,15 @@ func classifyAssistantFailure(ctx context.Context, err error) domain.AssistantFa f.Code, f.Message = "EXECUTION_LIMIT", "AI 助手已达到执行轮数上限,未能完成回答,请重试" return f } + if errors.Is(err, errAssistantNativeBusy) { + f.Code, f.Phase, f.Message, f.Suggestion = "SHARED_SESSION_BUSY", "setup", errAssistantNativeBusy.Error(), "等待正在执行的请求结束后再发送消息。" + return f + } + var stateErr *runtime.ConversationStateError + if errors.As(err, &stateErr) { + f.Code, f.Phase, f.Message, f.Suggestion = "CONVERSATION_STATE_ERROR", "setup", stateErr.Error(), "请联系管理员检查提示中的会话路径。" + return f + } if errors.Is(err, errAssistantExecutionUnavailable) { f.Code, f.Phase, f.Message, f.Suggestion = "EXECUTION_MACHINE_UNAVAILABLE", "setup", "会话绑定的执行机器暂不可用,请等待原机器恢复后重试", "会话已固定在原执行机器上,请确认该 Runner 在线后再重试。" return f diff --git a/internal/httpapi/assistant_native_session.go b/internal/httpapi/assistant_native_session.go index 4786cb69b..889ceea42 100644 --- a/internal/httpapi/assistant_native_session.go +++ b/internal/httpapi/assistant_native_session.go @@ -57,22 +57,22 @@ func assistantMessageHashes(messages []assistantMessage) []string { func openAssistantNativeSession(req assistantRequest, saved domain.AssistantSession, user domain.User, sourceRoot string) (*assistantNativeSession, error) { root := assistantSharedSessionRoot(saved.ID) - if err := runtime.ValidateConversationRoot(root); err != nil { + if _, err := runtime.ConversationSkillLinks(root); err != nil { return nil, err } if err := os.MkdirAll(root, 0o700); err != nil { - return nil, err + return nil, runtime.NewConversationStateError("创建共享会话目录", ".", err) } lock, err := os.OpenFile(filepath.Join(root, "session.lock"), os.O_CREATE|os.O_RDWR, 0o600) if err != nil { - return nil, err + return nil, runtime.NewConversationStateError("打开共享会话锁", "session.lock", err) } if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { _ = lock.Close() if err == syscall.EWOULDBLOCK || err == syscall.EAGAIN { return nil, errAssistantNativeBusy } - return nil, err + return nil, runtime.NewConversationStateError("获取共享会话锁", "session.lock", err) } native := &assistantNativeSession{root: root, lock: lock} if data, err := os.ReadFile(filepath.Join(root, "session.json")); err == nil { @@ -81,7 +81,7 @@ func openAssistantNativeSession(req assistantRequest, saved domain.AssistantSess } } else if !os.IsNotExist(err) { native.Close() - return nil, err + return nil, runtime.NewConversationStateError("读取共享会话缓存", "session.json", err) } // Model settings, mode, approval and selected assets can change without // replacing the CLI journal. History edits explicitly bump its revision. @@ -116,7 +116,12 @@ func (n *assistantNativeSession) Close() { } } -func (n *assistantNativeSession) writeCheckpoint() error { +func (n *assistantNativeSession) writeCheckpoint() (err error) { + defer func() { + if err != nil { + err = runtime.NewConversationStateError("写入共享会话缓存", "session.json", err) + } + }() data, err := json.Marshal(n.checkpoint) if err != nil { return err diff --git a/internal/httpapi/assistant_native_session_test.go b/internal/httpapi/assistant_native_session_test.go index 787381330..d982a2efb 100644 --- a/internal/httpapi/assistant_native_session_test.go +++ b/internal/httpapi/assistant_native_session_test.go @@ -369,12 +369,73 @@ func TestSharedNativeSessionFencesAStaleWriter(t *testing.T) { t.Fatal(err) } defer writer.Close() + link := filepath.Join(writer.root, "home", ".agents", "skills", "waiting") + if err := os.MkdirAll(filepath.Dir(link), 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink("original", link); err != nil { + t.Fatal(err) + } messages := append(append([]assistantMessage(nil), session.Messages...), assistantMessage{Role: "user", Content: "不能抢写"}) body, _ := json.Marshal(assistantRequest{ProjectID: session.ProjectID, RunID: session.RunID, SessionID: session.ID, Messages: messages}) c, w := workbenchContext(b, "POST", "/api/assistant/chat", bytes.NewBuffer(body)) (&assistantHandlers{deps: h.deps}).chat(c) - if w.Code != 409 || len(calls()) != 1 { - t.Fatalf("stale writer was not fenced: %d", w.Code) + if w.Code != 409 || len(calls()) != 1 || !strings.Contains(w.Body.String(), "SHARED_SESSION_BUSY") || !strings.Contains(w.Body.String(), "另一进程中生成") { + t.Fatalf("stale writer was not fenced or reported accurately: %d %s", w.Code, w.Body.String()) + } + if target, err := os.Readlink(link); err != nil || target != "original" { + t.Fatalf("losing turn modified the locked conversation: %q %v", target, err) + } +} + +func TestSharedNativeSessionContinuesAfterSkillInstallSymlink(t *testing.T) { + h, a, b, _, session := sharedWorkbenchFixture(t) + _, calls := nativeCLIRecorder(t) + session = sendNativeTurn(t, h, a, session, "安装技能") + root := assistantSharedSessionRoot(session.ID) + const skillPath = "home/.agents/skills/@publisher/design/SKILL.md" + const linkPath = "home/.agents/skills/design" + skill := filepath.Join(root, skillPath) + if err := os.MkdirAll(filepath.Dir(skill), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(skill, []byte("installed skill"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink("@publisher/design", filepath.Join(root, linkPath)); err != nil { + t.Fatal(err) + } + session = sendNativeTurn(t, h, b, session, "继续上次的工作") + recorded := calls() + if len(recorded) != 2 || recorded[1].flag("--resume") != recorded[0].flag("--session-id") { + t.Fatalf("turn did not resume the original native session: %+v", recorded) + } + if data, err := os.ReadFile(skill); err != nil || string(data) != "installed skill" { + t.Fatalf("skill files changed: %q %v", data, err) + } + reply := session.Messages[len(session.Messages)-1] + for _, event := range reply.Activity { + if event.Kind == "status" && strings.Contains(event.Text, linkPath) && strings.Contains(event.Text, "符号链接") { + return + } + } + t.Fatalf("turn did not record which link was removed: %+v", reply.Activity) +} + +func TestSharedNativeSessionReportsCacheReadFailure(t *testing.T) { + h, a, _, _, session := sharedWorkbenchFixture(t) + _, calls := nativeCLIRecorder(t) + root := assistantSharedSessionRoot(session.ID) + if err := os.MkdirAll(filepath.Join(root, "session.json"), 0700); err != nil { + t.Fatal(err) + } + messages := append(session.Messages, assistantMessage{Role: "user", Content: "继续"}) + body, _ := json.Marshal(assistantRequest{ProjectID: session.ProjectID, RunID: session.RunID, SessionID: session.ID, Messages: messages}) + c, w := workbenchContext(a, "POST", "/api/assistant/chat", bytes.NewBuffer(body)) + h.chat(c) + got := w.Body.String() + if w.Code != 500 || len(calls()) > 0 || !strings.Contains(got, "CONVERSATION_STATE_ERROR") || !strings.Contains(got, "读取共享会话缓存") || !strings.Contains(got, "session.json") || !strings.Contains(got, "is a directory") || strings.Contains(got, root) { + t.Fatalf("cache read failure lost its specific cause: %d %s", w.Code, got) } } diff --git a/internal/httpapi/assistant_process.go b/internal/httpapi/assistant_process.go index 88c87c0ca..e4d0dbdb9 100644 --- a/internal/httpapi/assistant_process.go +++ b/internal/httpapi/assistant_process.go @@ -193,10 +193,14 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin return runtime.ConversationProcessResult{}, fmt.Errorf("%w: %w", errAssistantExecutionUnavailable, err) } if response.Error != "" { + responseErr := errors.New(response.Error) + if response.Code == domain.WorkspaceErrorConversationState { + responseErr = &runtime.ConversationStateError{Message: response.Error} + } if req.Operation == "start" { - return runtime.ConversationProcessResult{}, fmt.Errorf("%w: %s", runtime.ErrConversationNotStarted, response.Error) + return runtime.ConversationProcessResult{}, fmt.Errorf("%w: %w", runtime.ErrConversationNotStarted, responseErr) } - return runtime.ConversationProcessResult{}, fmt.Errorf("%s", response.Error) + return runtime.ConversationProcessResult{}, responseErr } var result runtime.ConversationProcessResult err = json.Unmarshal(response.Payload, &result) @@ -213,6 +217,7 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin if err != nil { return "", err } + reportRemovedConversationSkillLinks(ctx, s.User, prepared.RemovedSkillLinks, s.Notify) if input, ok := command.Stdin.(*assistantLimitedImageInput); ok { command, err = input.fit(command, root, prepared.Root) if err != nil { @@ -400,6 +405,26 @@ func assistantEngineBinary(kind string) string { } } +func reportRemovedConversationSkillLinks(ctx context.Context, user domain.User, paths []string, notify func(string, any)) { + if len(paths) == 0 { + return + } + const maxDisplayedPaths = 5 + names := make([]string, 0, min(len(paths), maxDisplayedPaths)) + for _, path := range paths[:min(len(paths), maxDisplayedPaths)] { + names = append(names, fmt.Sprintf("%q", truncateRunes(path, 250))) + } + summary := strings.Join(names, "、") + if len(paths) > maxDisplayedPaths { + summary += fmt.Sprintf(" 等 %d 项", len(paths)) + } + message := fmt.Sprintf("技能目录不支持符号链接。已移除链接并继续执行(%s)。", summary) + assistantDiagnosticsFrom(ctx).platform("conversation.skill_links_removed", message, user) + if notify != nil { + notify("thought", assistantStreamEvent{Kind: "status", Text: sanitizeAssistantDiagnostic(message, user, 2048)}) + } +} + // Synchronize generated configuration and selected assets, excluding native // transcripts and the credentials written by the execution host. func conversationInputFiles(root string) ([]runtime.ConversationFile, error) { diff --git a/internal/httpapi/assistant_subagents.go b/internal/httpapi/assistant_subagents.go index c407ebe21..4afb16872 100644 --- a/internal/httpapi/assistant_subagents.go +++ b/internal/httpapi/assistant_subagents.go @@ -185,10 +185,14 @@ var rolePromptPlaceholder = regexp.MustCompile(`\{\{[^{}]+\}\}`) // SKILL.md unless it is also the project's own, bound or mentioned. A turn // with no project, no shared skills and no mentioned roles gets empty // directories. -func (h *assistantHandlers) writeConversationAssets(root string, req assistantRequest) error { - if err := runtime.ValidateConversationRoot(root); err != nil { +func (h *assistantHandlers) writeConversationAssets(root string, req assistantRequest, reportSkillLinks func([]string)) error { + removed, err := runtime.RemoveConversationSkillLinks(root) + if err != nil { return err } + if len(removed) > 0 && reportSkillLinks != nil { + reportSkillLinks(removed) + } if err := writeConversationAttachments(root, req); err != nil { return err } diff --git a/internal/httpapi/assistant_subagents_test.go b/internal/httpapi/assistant_subagents_test.go index 7c2d7308b..bf2cac246 100644 --- a/internal/httpapi/assistant_subagents_test.go +++ b/internal/httpapi/assistant_subagents_test.go @@ -188,7 +188,7 @@ func TestSkillMentionsAreScopedHintedAndWrittenToHome(t *testing.T) { root := t.TempDir() // Sharing installs the skill on a project turn that never mentions it. plain := assistantRequest{ProjectID: "workbench", Messages: []assistantMessage{{Role: "user", Content: "写一下"}}} - if err := h.writeConversationAssets(root, plain); err != nil { + if err := h.writeConversationAssets(root, plain, nil); err != nil { t.Fatal(err) } for _, name := range []string{"lint", "shareddoc"} { @@ -257,7 +257,7 @@ func TestEverySharedSkillIsInstalledWithItsSkillMD(t *testing.T) { req.skills = []domain.SkillDefinition{stored} } root := t.TempDir() - if err := h.writeConversationAssets(root, req); err != nil { + if err := h.writeConversationAssets(root, req, nil); err != nil { t.Fatal(err) } dir := filepath.Join(root, "home", ".codebuddy", "skills") @@ -320,7 +320,7 @@ func TestEverySharedSkillIsInstalledHoweverManyAreShared(t *testing.T) { } for _, project := range []string{"workbench", ""} { root := t.TempDir() - if err := h.writeConversationAssets(root, assistantRequest{ProjectID: project}); err != nil { + if err := h.writeConversationAssets(root, assistantRequest{ProjectID: project}, nil); err != nil { t.Fatal(err) } entries, err := os.ReadDir(filepath.Join(root, "home", ".codebuddy", "skills")) diff --git a/internal/runner/conversation.go b/internal/runner/conversation.go index 9433b9d0f..fd036eaaf 100644 --- a/internal/runner/conversation.go +++ b/internal/runner/conversation.go @@ -6,6 +6,7 @@ import ( "agentflow/internal/runtime" "context" "encoding/json" + "errors" "fmt" "path/filepath" "regexp" @@ -118,7 +119,12 @@ func (d *Daemon) conversationProcess(ctx context.Context, request domain.RunnerW } result, err := d.conversationProcesses.Handle(ctx, root, workspace, request.Sandbox, req, forward, factory) if err != nil { - return runnerWorkspaceError(err) + response := runnerWorkspaceError(err) + var stateErr *runtime.ConversationStateError + if errors.As(err, &stateErr) { + response.Code = domain.WorkspaceErrorConversationState + } + return response } return runnerWorkspacePayload(result) } diff --git a/internal/runner/conversation_process_guard_test.go b/internal/runner/conversation_process_guard_test.go index 9cb3f10cd..55fdc6fd8 100644 --- a/internal/runner/conversation_process_guard_test.go +++ b/internal/runner/conversation_process_guard_test.go @@ -67,9 +67,10 @@ func TestConversationProcessPreparesNativeRootUnderWorkspaceRoot(t *testing.T) { d := &Daemon{cfg: Config{DefaultWorkspaceRoot: root}} d.conversationForward = func(context.Context, string, json.RawMessage) (json.RawMessage, error) { return nil, nil } - got := d.conversationProcess(context.Background(), domain.RunnerWorkspaceRequest{ + request := domain.RunnerWorkspaceRequest{ Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: key}), - }) + } + got := d.conversationProcess(t.Context(), request) if got.Status != 200 { t.Fatalf("prepare = %+v", got) } @@ -86,6 +87,27 @@ func TestConversationProcessPreparesNativeRootUnderWorkspaceRoot(t *testing.T) { t.Fatalf("%s not prepared: %v", dir, err) } } + const skillLink = "home/.agents/skills/alias" + link := filepath.Join(want, skillLink) + if err := os.MkdirAll(filepath.Dir(link), 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink("sample-skill", link); err != nil { + t.Fatal(err) + } + got = d.conversationProcess(t.Context(), request) + result = runtime.ConversationProcessResult{} + if err := json.Unmarshal(got.Payload, &result); err != nil || got.Status != 200 || len(result.RemovedSkillLinks) != 1 || result.RemovedSkillLinks[0] != skillLink { + t.Fatalf("runner did not report the recovered skill link: %+v %v", got, err) + } + + if err := os.Symlink(link, filepath.Join(want, "current-mcp.json")); err != nil { + t.Fatal(err) + } + got = d.conversationProcess(t.Context(), request) + if got.Code != domain.WorkspaceErrorConversationState || !strings.Contains(got.Error, "current-mcp.json") || !strings.Contains(got.Error, "不支持符号链接") || strings.Contains(got.Error, want) { + t.Fatalf("runner did not report the protected path: %+v", got) + } } func TestLockConversationWorkspace(t *testing.T) { diff --git a/internal/runtime/conversation_assets.go b/internal/runtime/conversation_assets.go index cd0288f4c..3b5d257fe 100644 --- a/internal/runtime/conversation_assets.go +++ b/internal/runtime/conversation_assets.go @@ -1,28 +1,105 @@ package runtime import ( + "errors" "fmt" + "io/fs" "os" "path/filepath" "strings" ) +// ConversationStateError describes a preparation failure without exposing the +// host path of the conversation. +type ConversationStateError struct { + Message string + cause error +} + +func NewConversationStateError(operation, path string, cause error) *ConversationStateError { + reason := cause + var pathErr *fs.PathError + var linkErr *os.LinkError + if errors.As(cause, &pathErr) { + reason = pathErr.Err + } else if errors.As(cause, &linkErr) { + reason = linkErr.Err + } + return &ConversationStateError{ + Message: fmt.Sprintf("%s %q 失败(%v)", operation, path, reason), + cause: cause, + } +} + +func (e *ConversationStateError) Error() string { return e.Message } +func (e *ConversationStateError) Unwrap() error { return e.cause } + // Only inspect paths used by platform-side materialization. Native CLIs own // their logs and caches (including debug/latest links); WalkDir never follows // those links, and the platform does not read or write through them. func ValidateConversationRoot(root string) error { - return filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { - if os.IsNotExist(err) && path == root { - return nil + _, err := scanConversationRoot(root, false) + return err +} + +// ConversationSkillLinks lists recoverable links and rejects invalid paths in +// the rest of the conversation. Use this for read-only checks before taking a +// lock. The links must be removed before writing assets or starting a CLI. +func ConversationSkillLinks(root string) ([]string, error) { + return scanConversationRoot(root, true) +} + +// RemoveConversationSkillLinks unlinks skill entries left by native installers. +// The installer may have pointed an entry anywhere; only the link itself is +// removed, using a root-scoped operation. Callers serialize asset preparation +// with the native process. +func RemoveConversationSkillLinks(root string) ([]string, error) { + links, err := ConversationSkillLinks(root) + if err != nil || len(links) == 0 { + return nil, err + } + dir, err := os.OpenRoot(root) + if err != nil { + return nil, NewConversationStateError("打开会话目录", ".", err) + } + defer dir.Close() + var removed []string + for _, link := range links { + info, err := dir.Lstat(link) + if errors.Is(err, fs.ErrNotExist) { + continue } if err != nil { - return err + return removed, NewConversationStateError("检查技能链接", link, err) + } + if info.Mode()&os.ModeSymlink == 0 { + continue + } + if err := dir.Remove(link); err != nil { + if errors.Is(err, fs.ErrNotExist) { + continue + } + return removed, NewConversationStateError("移除技能链接", link, err) } + removed = append(removed, link) + } + return removed, nil +} + +func scanConversationRoot(root string, collectSkillLinks bool) ([]string, error) { + var links []string + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error { rel, err := filepath.Rel(root, path) if err != nil { - return err + return NewConversationStateError("检查会话目录", ".", err) } rel = filepath.ToSlash(rel) + if walkErr != nil { + if os.IsNotExist(walkErr) && rel == "." { + return nil + } + return NewConversationStateError("检查会话路径", rel, walkErr) + } if !conversationManagedPath(rel) { if entry.IsDir() { return filepath.SkipDir @@ -30,13 +107,27 @@ func ValidateConversationRoot(root string) error { return nil } if entry.Type()&os.ModeSymlink != 0 { - return fmt.Errorf("会话状态包含符号链接,拒绝宿主访问:%s", path) + if collectSkillLinks && conversationSkillPath(rel) { + links = append(links, rel) + return nil + } + return NewConversationStateError("检查会话路径", rel, errors.New("不支持符号链接")) } if entry.IsDir() && path == filepath.Join(root, "ws") { return filepath.SkipDir } return nil }) + return links, err +} + +func conversationSkillPath(rel string) bool { + for _, tree := range conversationSkillTrees { + if rel == tree || strings.HasPrefix(rel, tree+"/") { + return true + } + } + return false } func conversationManagedPath(rel string) bool { @@ -71,16 +162,18 @@ var conversationManagedFiles = []string{ "home/.zcode/v2", "home/.codex/auth.json", "home/.claude/.credentials.json", } -// Only platform-generated inputs travel to the execution host. Native -// transcripts, session maps, locks and provider credentials never do. -var conversationAssetTrees = []string{ - "home/.codebuddy/skills", "home/.codebuddy/agents", - "home/.claude/skills", "home/.claude/agents", +var conversationSkillTrees = []string{ + "home/.codebuddy/skills", "home/.claude/skills", "home/.codex/skills", "home/.agents/skills", "home/.pi/agent/skills", "home/.gemini/config/skills", - "attachments", } +// Only platform-generated inputs travel to the execution host. Native +// transcripts, session maps, locks and provider credentials never do. +var conversationAssetTrees = append([]string{ + "home/.codebuddy/agents", "home/.claude/agents", "attachments", +}, conversationSkillTrees...) + var conversationAssetFiles = []string{ "current-mcp.json", "current-settings.json", "claude-mcp.json", "claude-settings.json", "mcp.json", "codex-native-guard.py", "kimi-agent.md", "home/.config/opencode/opencode.json", "home/.cursor/mcp.json", "home/.cursor/cli-config.json", "home/.gemini/config/mcp_config.json", "home/.kimi-code/mcp.json", "home/.pi/agent/mcp.json", "home/.dsh/agentflow-mcp.json", diff --git a/internal/runtime/conversation_assets_test.go b/internal/runtime/conversation_assets_test.go index 32939aa3d..51a94742e 100644 --- a/internal/runtime/conversation_assets_test.go +++ b/internal/runtime/conversation_assets_test.go @@ -2,8 +2,11 @@ package runtime import ( "context" + "errors" "os" "path/filepath" + "slices" + "strings" "testing" ) @@ -56,3 +59,77 @@ func TestConversationPlatformPathsRejectLinks(t *testing.T) { }) } } + +func TestConversationPrepareRemovesSkillLinksWithoutReadingTargets(t *testing.T) { + root, outside := t.TempDir(), t.TempDir() + const skill = "home/.agents/skills/@publisher/design/SKILL.md" + if err := os.MkdirAll(filepath.Dir(filepath.Join(root, skill)), 0700); err != nil { + t.Fatal(err) + } + original := map[string]string{filepath.Join(root, skill): "installed skill", filepath.Join(outside, "content"): "outside data"} + for path, content := range original { + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + } + links := map[string]string{ + "home/.agents/skills/design": "@publisher/design", + "home/.agents/skills/dangling": "missing-skill", + "home/.agents/skills/external": outside, + "home/.claude/skills": outside, + } + var want []string + for link, target := range links { + path := filepath.Join(root, link) + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, path); err != nil { + t.Fatal(err) + } + want = append(want, link) + } + slices.Sort(want) + pool := &ConversationProcessPool{} + prepare := ConversationProcessRequest{Operation: "prepare"} + result, err := pool.Handle(t.Context(), root, "", nil, prepare, nil) + if err != nil || !slices.Equal(result.RemovedSkillLinks, want) { + t.Fatalf("prepare removed %v, want %v: %v", result.RemovedSkillLinks, want, err) + } + if err := ValidateConversationRoot(root); err != nil { + t.Fatalf("the next turn is still blocked: %v", err) + } + for path, content := range original { + if got, err := os.ReadFile(path); err != nil || string(got) != content { + t.Fatalf("link target changed: %q %v", got, err) + } + } + if result, err = pool.Handle(t.Context(), root, "", nil, prepare, nil); err != nil || len(result.RemovedSkillLinks) > 0 { + t.Fatalf("repeated prepare reported removed links again: %+v %v", result, err) + } +} + +func TestConversationSkillPreparationKeepsProtectedPathChecks(t *testing.T) { + root, target := t.TempDir(), t.TempDir() + const skillLink = "home/.agents/skills/alias" + const guardLink = "home/.codex/auth.json" + for _, rel := range []string{skillLink, guardLink} { + path := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, path); err != nil { + t.Fatal(err) + } + } + var stateErr *ConversationStateError + removed, err := RemoveConversationSkillLinks(root) + if len(removed) != 0 || !errors.As(err, &stateErr) || !strings.Contains(err.Error(), guardLink) || !strings.Contains(err.Error(), "不支持符号链接") || strings.Contains(err.Error(), root) { + t.Fatalf("protected path did not block preparation with its relative path: %v %v", removed, err) + } + for _, rel := range []string{skillLink, guardLink} { + if got, err := os.Readlink(filepath.Join(root, rel)); err != nil || got != target { + t.Fatalf("rejected preparation changed a link: %q %v", got, err) + } + } +} diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go index e519759f4..60fa3f23e 100644 --- a/internal/runtime/conversation_process.go +++ b/internal/runtime/conversation_process.go @@ -83,6 +83,8 @@ type ConversationProcessResult struct { // GitScrubbed names the Git credentials the agent wrote by hand that were // removed when a workspace CLI finished; it never holds their values. GitScrubbed []string `json:"gitScrubbed,omitempty"` + // Only conversation-relative paths are sent back to the platform. + RemovedSkillLinks []string `json:"removedSkillLinks,omitempty"` } type ConversationSandboxFactory func(context.Context, string) (Sandbox, func(), error) @@ -174,6 +176,7 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st if req.Operation == "start" { return p.start(ctx, root, workspace, sandbox, req, forward, factories...) } + var removedSkillLinks []string if req.Operation == "prepare" || req.Operation == "sync" || req.Operation == "resetAssets" || req.Operation == "discard" { // Serialize asset writes with reservation of a new process. Checking // roots and releasing the fence before a write allows start to race it. @@ -188,7 +191,12 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st if active { return ConversationProcessResult{}, fmt.Errorf("会话原生进程仍在运行,不能替换资产或启动新进程") } - if err = ValidateConversationRoot(root); err != nil { + if req.Operation == "prepare" { + removedSkillLinks, err = RemoveConversationSkillLinks(root) + } else { + err = ValidateConversationRoot(root) + } + if err != nil { return ConversationProcessResult{}, err } if req.Operation == "discard" { @@ -197,15 +205,14 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st } return ConversationProcessResult{}, os.RemoveAll(root) } - if err = os.MkdirAll(filepath.Join(root, "home", "tmp"), 0700); err != nil { - return ConversationProcessResult{}, err - } - if err = os.MkdirAll(filepath.Join(root, "ws"), 0700); err != nil { - return ConversationProcessResult{}, err + for _, dir := range []string{"home/tmp", "ws"} { + if err = os.MkdirAll(filepath.Join(root, dir), 0700); err != nil { + return ConversationProcessResult{}, NewConversationStateError("创建会话目录", dir, err) + } } } if req.Operation == "prepare" { - return ConversationProcessResult{Root: root}, nil + return ConversationProcessResult{Root: root, RemovedSkillLinks: removedSkillLinks}, nil } if req.Operation == "resetAssets" { for _, dir := range conversationAssetTrees { @@ -544,7 +551,7 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str } for _, dir := range []string{"home/tmp", "ws"} { if err = os.MkdirAll(filepath.Join(root, dir), 0700); err != nil { - return ConversationProcessResult{}, err + return ConversationProcessResult{}, NewConversationStateError("创建会话目录", dir, err) } } if spec != nil {