feat(teams): team system v2 with bug fixes, workspace scope, versioning, and prompt optimization (#183)

* feat(workspace): add team shared workspace for file collaboration

- Add workspace_write and workspace_read tools for agents to share files across team members
- Create team_workspaces DB table with migration 000017 (file metadata, pinning, tags)
- Implement PostgreSQL store layer for workspace CRUD operations
- Add RPC handlers for workspace list/read/delete from web UI
- Build React workspace tab with file listing, content preview, and delete
- Propagate workspace channel/chatID scope through delegation chain
- Auto-allow workspace tools in agent tool policy when agent belongs to a team
- Inject team workspace guidance into system prompt for team agents
- Add /reset command handler for clearing session history
- Harden MCP bridge context middleware to reject headers when no gateway token
- Add i18n strings for workspace UI in en/vi/zh locales

* feat(teams): add comprehensive task management with followup reminders and recovery

- Add task followup/reminder system with auto-set on lead agent reply and auto-clear when user responds on channel
- Add task recovery ticker to re-dispatch stale/pending tasks periodically
- Add task scopes, filtering by status/channel/chatID, and task events
- Add WS RPC handlers for task CRUD, assignments, comments, events, and bulk operations (teams_tasks.go)
- Add task detail dialog, settings UI for followup config, and scope filtering in web dashboard
- Add migrations 000018 (team_tasks_v2) and 000019 (task_followup)
- Extend team_tasks_tool with await_reply, clear_followup actions
- Auto-complete/fail team tasks when delegate agent finishes
- Add workspace file listing and team tool manager enhancements

* docs(teams): add team system architecture and playbook ideas documentation

- Add TEAM_SYSTEM.md with full architecture design covering task management, shared workspace, and delegation engine subsystems
- Add TEAM_PLAYBOOK_IDEAS.md outlining future team coordination layers (playbook, member capabilities, auto-learned patterns)
- Document data models, status flows, tool actions, followup reminder system, task ticker, execution locking, and workspace scope model

* fix(teams): resolve 6 critical bugs in team task system

- Fix unblock SQL: check array_length after array_remove (not before)
- Enforce single-team leadership in team creation
- Add requireLead() for approve/reject tool actions
- Validate cross-team dependency references in blocked_by
- Add team_id to handoff route for multi-team isolation
- Set blocked_by DEFAULT '{}' to prevent NULL array issues

* refactor(workspace): use stable userID as scope key instead of connection UUID

Workspace scope changed from (team_id, channel, chat_id) to (team_id, userID).
Fixes workspace fragmentation across WS tab refreshes and reconnections.

* feat(teams): add V1/V2 versioning with feature gating and optimized prompts

- IsTeamV2() helper gates advanced features (locking, followup, review, audit)
- V2 tool actions rejected for V1 teams with clear error message
- Ticker, gateway consumer, delegation hooks respect version flag
- TEAM.md renders v1/v2 sections conditionally
- Tool descriptions and params optimized (~38% token reduction)
- UI: version toggle in settings, V2 Beta badge, conditional rendering
- i18n: version modal keys for en/vi/zh

* fix(migration): use VARCHAR(255) for user ID columns and add metadata JSONB

- assignee_user_id, user_id, actor_id: TEXT → VARCHAR(255)
- Add metadata JSONB to team_task_comments and team_task_attachments

---------

Co-authored-by: Nam Nguyen Ngoc <namnn.0911@gmail.com>
This commit is contained in:
Viet TranandNam Nguyen Ngoc authored and GitHub committed 2026-03-13 22:41:32 +07:00
1 parent 7bde3f2f7c
commit 1a42dc93a6
71 files changed
+7908 -790

No files matched your search

+198
View File
@@ -0,0 +1,198 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/google/uuid"
"github.com/nextlevelbuilder/goclaw/internal/store"
)
// Workspace limits shared across read/write tools.
const defaultQuotaMB = 500
// workspaceDir returns the disk directory for a team workspace scope.
// Pattern: {dataDir}/teams/{teamID}/{chatID}/
// chatID is the system-derived userID (stable across WS reconnects).
// Creates directory with 0750 if not exists.
func workspaceDir(dataDir string, teamID uuid.UUID, _, chatID string) (string, error) {
if chatID == "" {
chatID = "_default"
}
dir := filepath.Join(dataDir, "teams", teamID.String(), chatID)
if err := os.MkdirAll(dir, 0750); err != nil {
return "", fmt.Errorf("failed to create workspace dir: %w", err)
}
return dir, nil
}
// validFileName matches alphanumeric + "-_." only.
var validFileName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,253}[a-zA-Z0-9._]$`)
// sanitizeFileName validates file name: max 255 chars, no path separators,
// no null bytes, no "..", alphanumeric + "-_." only.
func sanitizeFileName(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("file_name is required")
}
if len(name) > 255 {
return "", fmt.Errorf("file_name exceeds 255 characters")
}
if strings.Contains(name, "\x00") {
return "", fmt.Errorf("file_name contains null bytes")
}
if strings.Contains(name, "..") {
return "", fmt.Errorf("file_name contains path traversal")
}
if strings.ContainsAny(name, "/\\") {
return "", fmt.Errorf("file_name contains path separators")
}
// Allow single-char names like "a" or "1"
if len(name) == 1 {
if (name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z') || (name[0] >= '0' && name[0] <= '9') {
return name, nil
}
return "", fmt.Errorf("file_name must be alphanumeric with hyphens, underscores, and dots only")
}
if !validFileName.MatchString(name) {
return "", fmt.Errorf("file_name must be alphanumeric with hyphens, underscores, and dots only")
}
return name, nil
}
// blockedExtensions lists executable file types that are not allowed.
var blockedExtensions = map[string]bool{
".exe": true, ".sh": true, ".bat": true, ".cmd": true,
".ps1": true, ".com": true, ".msi": true, ".scr": true,
}
// mimeTypes maps file extensions to MIME types (package-level to avoid re-allocation).
var mimeTypes = map[string]string{
".txt": "text/plain",
".md": "text/markdown",
".json": "application/json",
".csv": "text/csv",
".xml": "text/xml",
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".ts": "application/typescript",
".py": "text/x-python",
".go": "text/x-go",
".rs": "text/x-rust",
".java": "text/x-java",
".yaml": "application/x-yaml",
".yml": "application/x-yaml",
".toml": "application/toml",
".sql": "application/sql",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".pdf": "application/pdf",
".zip": "application/zip",
".tar": "application/x-tar",
".gz": "application/gzip",
}
// inferMimeType returns MIME type from file extension.
// Blocks executable types.
func inferMimeType(fileName string) (string, error) {
ext := strings.ToLower(filepath.Ext(fileName))
if blockedExtensions[ext] {
return "", fmt.Errorf("executable file type %q is not allowed", ext)
}
if mt, ok := mimeTypes[ext]; ok {
return mt, nil
}
return "application/octet-stream", nil
}
// isBinaryMime returns true if the MIME type represents binary content.
func isBinaryMime(mimeType string) bool {
if strings.HasPrefix(mimeType, "text/") {
return false
}
switch mimeType {
case "application/json", "application/javascript", "application/typescript",
"application/x-yaml", "application/toml", "application/sql",
"application/xml":
return false
}
return true
}
// resolveWorkspaceScope resolves the workspace scope (channel, chatID) for tools.
// Scope is (team_id, userID) where userID is the system-derived stable user ID.
// channel is always "" (kept for signature compatibility); chatID = userID.
// Priority: WorkspaceChatID context key (set during delegation) > store.UserIDFromContext
func resolveWorkspaceScope(ctx context.Context) (channel, chatID string) {
chatID = WorkspaceChatIDFromCtx(ctx)
if chatID == "" {
chatID = store.UserIDFromContext(ctx)
}
return "", chatID
}
// workspaceSettings parses workspace-related fields from team settings JSON once.
type workspaceSettings struct {
WorkspaceScope string `json:"workspace_scope"`
WorkspaceQuotaMB *int `json:"workspace_quota_mb"`
WorkspaceTemplates []workspaceTempl `json:"workspace_templates"`
}
type workspaceTempl struct {
FileName string `json:"file_name"`
Content string `json:"content"`
}
func parseWorkspaceSettings(raw json.RawMessage) workspaceSettings {
var ws workspaceSettings
if len(raw) > 0 {
_ = json.Unmarshal(raw, &ws)
}
return ws
}
func (ws workspaceSettings) isShared() bool {
return ws.WorkspaceScope == "shared"
}
func (ws workspaceSettings) quotaMB(defaultMB int) int {
if ws.WorkspaceQuotaMB != nil {
return *ws.WorkspaceQuotaMB
}
return defaultMB
}
// resolveWorkspaceScopeFromArgs resolves scope (channel, chatID) from tool args + context.
// Returns error result string if scope=team but team setting is isolated.
func resolveWorkspaceScopeFromArgs(ctx context.Context, args map[string]any, ws workspaceSettings) (channel, chatID, errMsg string) {
scope, _ := args["scope"].(string)
if scope == "" {
scope = "channel"
}
channel, chatID = resolveWorkspaceScope(ctx)
if scope == "team" {
if !ws.isShared() {
return "", "", "team workspace_scope is 'isolated' — set to 'shared' in team settings to use scope=team"
}
chatID = ""
}
return "", chatID, ""
}
// validTags is the set of allowed tag values.
var validTags = map[string]bool{
"deliverable": true,
"handoff": true,
"reference": true,
"draft": true,
}