diff --git a/frontend/src/lib/pages/MigrationAssistant.svelte b/frontend/src/lib/pages/MigrationAssistant.svelte index 6e14025cf..44f6c215b 100644 --- a/frontend/src/lib/pages/MigrationAssistant.svelte +++ b/frontend/src/lib/pages/MigrationAssistant.svelte @@ -19,6 +19,7 @@ import Activity from '@lucide/svelte/icons/activity'; import DialogFooter from '../dialogs/DialogFooter.svelte'; import { t } from '../stores/i18n.svelte.js'; + import { invalidateWorkspaceConfiguration } from '../stores/referenceDataInvalidation.js'; let { configurationSet = null, @@ -321,6 +322,13 @@ migrationSuccess = true; + // The migration reassigned the affected workspaces inside its own + // transaction. Its plural endpoint only clears screen configs, so drop + // each workspace's catalogs, status options, and priorities explicitly. + for (const affectedWorkspaceId of migrationAnalysis?.affected_workspaces ?? []) { + invalidateWorkspaceConfiguration(affectedWorkspaceId); + } + // Close the assistant after a brief delay setTimeout(() => { closeAssistant(); diff --git a/frontend/src/lib/stores/referenceDataInvalidation.js b/frontend/src/lib/stores/referenceDataInvalidation.js index 9b3da5af4..1f94077b2 100644 --- a/frontend/src/lib/stores/referenceDataInvalidation.js +++ b/frontend/src/lib/stores/referenceDataInvalidation.js @@ -11,6 +11,8 @@ import { workspaceDataStore } from './workspaceDataStore.svelte.js'; * - `store`: a `workspaceDataStore` field, * - `editor`: a `collectionEditorOptions` family, * - `screenConfigs`: cached effective configurations, + * - `configurationChanged`: reload the assigned workspace through the store's + * reset/initialization lifecycle and reset the editor caches, * - `fullRefresh`: everything (used for cross-cutting changes). * * Matching is deliberately coarse: re-fetching an unchanged family is cheap and @@ -39,6 +41,10 @@ const REFERENCE_ENDPOINTS = [ { match: /\/(?:time\/projects)(?:\/|$)/, store: 'projects', editor: 'projects' }, { match: /\/(?:labels)(?:\/|$)/, store: 'labels' }, { match: /\/(?:configuration-sets|screens|workflows)(?:\/|$)/, screenConfigs: true }, + // Workspace-scoped assignment (WI-1359): PUT /workspaces/:id/configuration-set. + // The singular endpoint reassigns the workspace, so reload it through the + // normal lifecycle and reset the editor caches. + { match: /\/configuration-set(?:\/|$)/, configurationChanged: true }, // Object translations change display names across several directories. { match: /\/(?:object-translations)(?:\/|$)/, fullRefresh: true }, { match: /^\/workspaces\/\d+$/, store: 'workspace' }, @@ -85,11 +91,32 @@ export function applyReferenceInvalidation( else editorOptions.invalidate(workspaceId, rule.editor); } if (rule.screenConfigs) store.invalidateScreenConfigs?.(); + if (rule.configurationChanged && workspaceId != null) { + invalidateWorkspaceConfiguration(workspaceId, { store, editorOptions }); + } } return true; } +/** + * Apply an assigned-configuration change for one workspace. The migration path + * reassigns the workspace inside its own POST, whose plural endpoint only clears + * screen configs, so the caller names the affected workspaces explicitly. This + * is also the rule the direct assignment endpoint matches. + */ +export function invalidateWorkspaceConfiguration( + workspaceId, + { store = workspaceDataStore, editorOptions = collectionEditorOptions } = {} +) { + if (workspaceId == null) return false; + // Reset the editor caches, then reload the active workspace through the + // store's reset/initialization lifecycle, which rejects superseded reads. + editorOptions.reset?.(); + void store.reloadForConfigurationChange?.(workspaceId); + return true; +} + /** Subscribe the app shell to successful mutations. Returns an unsubscribe. */ export function registerReferenceDataInvalidation() { if (typeof window === 'undefined') return () => {}; diff --git a/frontend/src/lib/stores/workspaceDataStore.svelte.js b/frontend/src/lib/stores/workspaceDataStore.svelte.js index 8e6c3e999..3aec64981 100644 --- a/frontend/src/lib/stores/workspaceDataStore.svelte.js +++ b/frontend/src/lib/stores/workspaceDataStore.svelte.js @@ -525,6 +525,29 @@ class WorkspaceDataStore { this.#screenConfigPromises.clear(); } + /** + * Apply an assigned-configuration change for one workspace. Drops cached + * effective configurations and, when the workspace is active, reloads it + * through the normal reset/initialization lifecycle. The reset advances the + * generation, so a bootstrap read that started before the change cannot + * install its stale catalogs afterwards. A configuration change is rare, so + * the extra reads are preferable to a second invalidation counter. + */ + async reloadForConfigurationChange(workspaceId) { + const id = Number(workspaceId); + if (!Number.isInteger(id) || id <= 0) return; + if (this.workspaceId !== id) { + // Not active: drop the cached effective configurations; the next + // activation bootstraps fresh through initialize(). + this.invalidateScreenConfigs(); + return; + } + // Active: reset and reload through the normal lifecycle so the generation + // advances and a bootstrap read from before the change is discarded. + this.reset(); + await this.initialize(id); + } + #storeScreenConfig(key, config) { this.screenConfigs = { ...this.screenConfigs, [key]: config }; this.#touchScreenConfig(key); diff --git a/internal/aitools/env.go b/internal/aitools/env.go index 29718653d..f7a9e24d1 100644 --- a/internal/aitools/env.go +++ b/internal/aitools/env.go @@ -57,6 +57,17 @@ type Env struct { PageApplicationService *services.PageApplicationService // PageDiagramService owns immutable Page-diagram attachment mutations. PageDiagramService *services.PageDiagramService + // ItemApplication is the shared, fully wired item mutation pipeline (create + // and update). Tools must route item writes through it so agent writes get + // the same mention processing, cache invalidation, and created/updated + // events as the HTTP surfaces. Nil-safe: a local pipeline without the + // server's emitters is constructed on demand. + ItemApplication *services.ItemApplicationService + // TimeWorklogService is the shared worklog validation and persistence + // boundary. log_time routes through it so the description policy and + // warnings match the HTTP surfaces. Nil-safe: a local service is + // constructed on demand. + TimeWorklogService *services.TimeWorklogService // ActionService is the optional cache-invalidation hook for tools that // create or mutate actions. Nil-safe: tools must check before calling // InvalidateWorkspaceCache so they degrade to "next periodic refresh" @@ -127,6 +138,31 @@ func (e *Env) audit(actionType, resourceType string, resourceID int, resourceNam } } +// itemApplication returns the configured item mutation pipeline, or a local +// one when the embedder did not supply the server's shared instance. The +// fallback keeps tools working without the process-wide emitters, matching the +// pre-injection behavior. +func (e *Env) itemApplication() *services.ItemApplicationService { + if e.ItemApplication != nil { + return e.ItemApplication + } + return services.NewItemApplicationService( + e.DB, + e.PermService, + services.NewItemCreationService(e.DB, e.PermService), + services.NewItemUpdateApplicationService(e.DB, e.PermService), + services.NewItemDeletionApplicationService(e.DB, e.PermService), + ) +} + +// timeWorklogService returns the configured worklog service, or a local one. +func (e *Env) timeWorklogService() *services.TimeWorklogService { + if e.TimeWorklogService != nil { + return e.TimeWorklogService + } + return services.NewTimeWorklogService(e.DB) +} + // HasWorkspaceAccess reports whether the caller can touch the given workspace. func (e *Env) HasWorkspaceAccess(workspaceID int) bool { for _, id := range e.AccessibleWorkspaceIDs { diff --git a/internal/aitools/items.go b/internal/aitools/items.go index bfb36128f..317da5c2d 100644 --- a/internal/aitools/items.go +++ b/internal/aitools/items.go @@ -311,7 +311,7 @@ func init() { Risk: RiskMedium, Description: "Create a new work item in a workspace. Optionally set custom fields with custom_field_values, keyed by numeric field ID from list_custom_fields.", Scopes: []string{auth.ScopeItemsWrite}, - Run: func(_ context.Context, env *Env, args createItemArgs) (any, error) { + Run: func(ctx context.Context, env *Env, args createItemArgs) (any, error) { if strings.TrimSpace(args.Title) == "" { return map[string]string{"error": "title is required"}, nil } @@ -344,33 +344,33 @@ func init() { if !validationResult.Valid { return map[string]string{"error": validationResult.Error}, nil } - customFieldValuesJSON, err := services.EncodeCustomFieldValuesJSON(env.DB, args.CustomFieldValues) - if err != nil { + if _, err := services.EncodeCustomFieldValuesJSON(env.DB, args.CustomFieldValues); err != nil { return map[string]string{"error": err.Error()}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error } - itemID, err := services.CreateItem(env.DB, services.ItemCreationParams{ - WorkspaceID: args.WorkspaceID, - Title: title, - Description: desc, - StatusID: args.StatusID, - PriorityID: args.PriorityID, - AssigneeID: args.AssigneeID, - ParentID: args.ParentID, - ItemTypeID: args.ItemTypeID, - CreatorID: &env.UserID, - ValidatingUserID: env.UserID, - CustomFieldValuesJSON: customFieldValuesJSON, - PermService: env.PermService, - EventMetadata: env.eventMetadata(), + // Route through the shared application service so the canonical created + // event and downstream effects fire exactly once, as they do for the + // HTTP surfaces. + created, err := env.itemApplication().Create(ctx, services.AuditActor{ + UserID: env.UserID, Username: env.Username, + }, services.ItemCreateInput{ + WorkspaceID: args.WorkspaceID, + Title: title, + Description: desc, + StatusID: args.StatusID, + PriorityID: args.PriorityID, + AssigneeID: args.AssigneeID, + ParentID: args.ParentID, + ItemTypeID: args.ItemTypeID, + CustomFieldValues: args.CustomFieldValues, + EventMetadata: env.eventMetadata(), }) if err != nil { + if errors.Is(err, services.ErrItemForbidden) { + return map[string]string{"error": "permission denied"}, nil + } return map[string]string{"error": fmt.Sprintf("create failed: %s", err.Error())}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error } - env.AuditWrite(logger.ResourceItem, int(itemID), "create_item", title) - created, err := services.NewItemCRUDService(env.DB).GetByID(int(itemID)) - if err != nil { - return map[string]any{"id": itemID}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error - } + env.AuditWrite(logger.ResourceItem, created.ID, "create_item", created.Title) return itemToSummary(created), nil }, }) @@ -385,7 +385,7 @@ func init() { Risk: RiskMedium, Description: "Update fields on an existing work item. Identifies the item by numeric ID or key. Use transition_item to change status (workflow + condition rules apply).", Scopes: []string{auth.ScopeItemsWrite}, - Run: func(_ context.Context, env *Env, args updateItemArgs) (any, error) { + Run: func(ctx context.Context, env *Env, args updateItemArgs) (any, error) { itemID, err := resolveItemID(env.DB, args.ItemID, args.ItemKey) if err != nil { return map[string]string{"error": err.Error()}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error @@ -412,20 +412,18 @@ func init() { if len(updateData) == 0 { return map[string]string{"error": "no fields to update"}, nil } - result, err := services.NewItemUpdateService(env.DB). - WithPermissionService(env.PermService). - UpdateItem(services.UpdateItemRequest{ - ItemID: itemID, - UpdateData: updateData, - UserID: env.UserID, - EventMetadata: env.eventMetadata(), - }) + result, err := env.itemApplication().UpdateFieldsWithMetadata(ctx, services.AuditActor{ + UserID: env.UserID, Username: env.Username, + }, itemID, updateData, env.eventMetadata()) if err != nil { + if errors.Is(err, services.ErrItemForbidden) { + return map[string]string{"error": "permission denied"}, nil + } return map[string]string{"error": fmt.Sprintf("update failed: %s", err.Error())}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error } - env.AuditWrite(logger.ResourceItem, itemID, "update_item", result.Item.Title) + env.AuditWrite(logger.ResourceItem, itemID, "update_item", result.Title) out := map[string]any{ - "item": itemToSummary(result.Item), + "item": itemToSummary(result), "changed_fields": changed, } return out, nil diff --git a/internal/aitools/time.go b/internal/aitools/time.go index 77eedd477..3e8559884 100644 --- a/internal/aitools/time.go +++ b/internal/aitools/time.go @@ -104,6 +104,9 @@ type logTimeOut struct { EndTimeLocal string `json:"end_time_local"` StartAt string `json:"start_at"` EndAt string `json:"end_at"` + // Warnings lists policy adjustments applied to the description, matching + // the HTTP worklog responses so a caller learns its text was shortened. + Warnings []string `json:"warnings,omitempty"` } // ---------------------------------------------------------------------------- @@ -298,32 +301,38 @@ func init() { if toolErr != nil { return toolErr, nil } - id, err := repository.NewTimeWorklogRepository(env.DB).Create(repository.NewWorklog{ + // Route through the shared worklog service so the description policy and + // warnings match the HTTP surfaces. PreserveStored keeps the interval + // already parsed above instead of re-deriving it. + result, err := env.timeWorklogService().Create(env.UserID, services.WorklogMutationInput{ ProjectID: args.ProjectID, - UserID: env.UserID, ItemID: itemID, Description: args.Description, - DateUnix: services.WorklogDateUnix(date), - StartTimeUnix: startUnix, - EndTimeUnix: endUnix, + Date: args.Date, + Timezone: resolvedTimezone, + UserTimezone: env.Timezone, DurationMinutes: durationMins, + StoredStartUnix: startUnix, + StoredEndUnix: endUnix, + PreserveStored: true, }) if err != nil { - return nil, err + return worklogServiceError(err) } - env.AuditWrite(resourceTimeWorklog, int(id), "log_time", args.Description) + env.AuditWrite(resourceTimeWorklog, result.Worklog.ID, "log_time", result.Worklog.Description) return logTimeOut{ - ID: id, + ID: int64(result.Worklog.ID), ProjectID: args.ProjectID, ProjectName: project.Name, Date: args.Date, - DurationMinutes: durationMins, - Description: args.Description, - Timezone: resolvedTimezone, - StartTimeLocal: time.Unix(startUnix, 0).In(location).Format("15:04"), - EndTimeLocal: time.Unix(endUnix, 0).In(location).Format("15:04"), - StartAt: time.Unix(startUnix, 0).UTC().Format(time.RFC3339), - EndAt: time.Unix(endUnix, 0).UTC().Format(time.RFC3339), + DurationMinutes: result.DurationMinutes, + Description: result.Worklog.Description, + Timezone: result.Timezone, + StartTimeLocal: time.Unix(result.StartTimeUnix, 0).In(result.Location).Format("15:04"), + EndTimeLocal: time.Unix(result.EndTimeUnix, 0).In(result.Location).Format("15:04"), + StartAt: time.Unix(result.StartTimeUnix, 0).UTC().Format(time.RFC3339), + EndAt: time.Unix(result.EndTimeUnix, 0).UTC().Format(time.RFC3339), + Warnings: result.Warnings, }, nil }, }) @@ -390,6 +399,23 @@ func init() { }) } +// worklogServiceError maps a TimeWorklogService error to a tool response. +// Known input errors are reported in the payload; anything else is an +// unexpected storage failure and is returned as a Go error so MCP marks the +// call failed instead of reporting success. +func worklogServiceError(err error) (map[string]string, error) { + switch { + case errors.Is(err, services.ErrWorklogProjectNotFound): + return map[string]string{"error": "project not found"}, nil + case errors.Is(err, services.ErrWorklogProjectInactive): + return map[string]string{"error": "project is not active"}, nil + case errors.Is(err, services.ErrWorklogInvalidInput): + return map[string]string{"error": err.Error()}, nil + default: + return nil, err + } +} + // resolveOptionalItemRef resolves the optional work-item reference time tools // accept (numeric item_id or item_key like PROJ-42). Returns (nil, nil) when // neither is provided. Resolution failures and items outside the caller's diff --git a/internal/handlers/ai.go b/internal/handlers/ai.go index de7a3fc08..849a059ff 100644 --- a/internal/handlers/ai.go +++ b/internal/handlers/ai.go @@ -31,11 +31,17 @@ type AIHandler struct { actionService *services.ActionService pageApplicationService *services.PageApplicationService pageDiagramService *services.PageDiagramService - conversations *repository.AgentConversationRepository - agentBindings *repository.WorkspaceAgentBindingRepository - commentService *services.CommentService - approvalService *services.ApprovalService - chatLLMs chatLLMResolver + // itemApplication is the shared item mutation pipeline used by mutating + // chat tools so agent writes match the HTTP surfaces. Installed after + // construction because server wiring builds it late. + itemApplication *services.ItemApplicationService + // timeWorklogService is the shared worklog boundary used by log_time. + timeWorklogService *services.TimeWorklogService + conversations *repository.AgentConversationRepository + agentBindings *repository.WorkspaceAgentBindingRepository + commentService *services.CommentService + approvalService *services.ApprovalService + chatLLMs chatLLMResolver // llmUsage meters each chat turn's token/cost against its own agent_runs // row, so the model's identity and the turn's spend outlive the response. llmUsage *repository.LLMUsageRepository @@ -85,6 +91,14 @@ func (h *AIHandler) SetConversationDependencies(comments *services.CommentServic h.approvalService = approvals } +// SetMutationServices installs the shared item and worklog pipelines used by +// mutating chat tools. Server wiring builds them after the handler, so this is +// called once those services exist. +func (h *AIHandler) SetMutationServices(itemApplication *services.ItemApplicationService, worklogs *services.TimeWorklogService) { + h.itemApplication = itemApplication + h.timeWorklogService = worklogs +} + // PlanMyDayResponse is the response for the Plan My Day endpoint. type PlanMyDayResponse struct { Activities []PlannedActivity `json:"activities"` diff --git a/internal/handlers/ai_dependencies.go b/internal/handlers/ai_dependencies.go index 5dd607194..e82b58e57 100644 --- a/internal/handlers/ai_dependencies.go +++ b/internal/handlers/ai_dependencies.go @@ -900,6 +900,8 @@ func (h *AIHandler) Chat(w http.ResponseWriter, r *http.Request) { CommentService: h.commentService, ApprovalService: h.approvalService, ActionService: h.actionService, + ItemApplication: h.itemApplication, + TimeWorklogService: h.timeWorklogService, PageApplicationService: h.pageApplicationService, PageDiagramService: h.pageDiagramService, } diff --git a/internal/mcp/server.go b/internal/mcp/server.go index d0e1db9a9..d287df52d 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -24,6 +24,8 @@ type Deps struct { TimerService *services.TimerService CommentService *services.CommentService ItemDeletionService *services.ItemDeletionApplicationService + ItemApplicationService *services.ItemApplicationService + TimeWorklogService *services.TimeWorklogService PageApplicationService *services.PageApplicationService PageDiagramService *services.PageDiagramService // ActionService is the optional cache-invalidation hook used by the diff --git a/internal/mcp/tools_registry.go b/internal/mcp/tools_registry.go index b6567a8a8..31636d7b4 100644 --- a/internal/mcp/tools_registry.go +++ b/internal/mcp/tools_registry.go @@ -127,6 +127,8 @@ func (ms *MCPServer) buildEnv(user *models.User) (*aitools.Env, error) { TimerService: ms.deps.TimerService, CommentService: ms.deps.CommentService, ItemDeletionService: ms.deps.ItemDeletionService, + ItemApplication: ms.deps.ItemApplicationService, + TimeWorklogService: ms.deps.TimeWorklogService, PageApplicationService: ms.deps.PageApplicationService, PageDiagramService: ms.deps.PageDiagramService, ActionService: ms.deps.ActionService, diff --git a/internal/server/server.go b/internal/server/server.go index fc2841017..42d7c0bdc 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1294,36 +1294,6 @@ func (s *Server) initialize() error { s.zammadSyncScheduler.Start() zammadHandler.SetSyncAllTrigger(s.zammadSyncScheduler.TriggerSyncAll) - // Standard profiles execute in-process through the canonical aitools - // registry. Wiring is intentionally late because their final comments and - // approval tools use the fully configured application services above. - if bindingSvc != nil { - standardDispatcher, err := standardagent.New(standardagent.Options{ - DB: s.db, - Runs: repository.NewAgentRunRepository(s.db), - Bindings: agentBindingRepo, - LLMs: llmManager, - Permissions: permService, - TimePermissions: timePermissionService, - Timers: timerService, - Comments: commentService, - Approvals: approvalService, - Notifications: s.notificationService, - ActionService: s.actionService, - PageApplicationService: pageApplication, - PageDiagramService: pageDiagramService, - Registry: aitools.Default, - }) - if err != nil { - return fmt.Errorf("construct Standard agent runtime: %w", err) - } - bindingSvc.SetStandardRunDispatcher(standardDispatcher) - s.standardAgentDispatcher = standardDispatcher - if err := standardDispatcher.Resume(context.Background()); err != nil { - return fmt.Errorf("resume Standard agent runtime: %w", err) - } - } - // Background sweeper drives time-based escalation for pending approval steps. s.approvalEscalationSweeper = services.NewApprovalEscalationSweeper(s.db, approvalService, services.DefaultApprovalEscalationSweeperConfig()) s.approvalEscalationSweeper.Start() @@ -2038,6 +2008,41 @@ func (s *Server) initialize() error { // Board surfaces reuse the internal item reads to authorize staff viewers. publicBoardHandler.SetItemAccess(itemApplication) customerAccessHandler.SetItemAccess(itemApplication) + // Chat tools write through the same item and worklog pipelines as HTTP. + aiHandler.SetMutationServices(itemApplication, timeWorklogService) + // Standard profiles execute in-process through the canonical aitools + // registry. Wiring is intentionally late because their final comments, + // approval tools, and item/worklog mutations use the fully configured + // application services above; Resume must not start a queued run before + // those services are installed. + if bindingSvc != nil { + standardDispatcher, err := standardagent.New(standardagent.Options{ + DB: s.db, + Runs: repository.NewAgentRunRepository(s.db), + Bindings: agentBindingRepo, + LLMs: llmManager, + Permissions: permService, + TimePermissions: timePermissionService, + Timers: timerService, + Comments: commentService, + Approvals: approvalService, + Notifications: s.notificationService, + ActionService: s.actionService, + ItemApplication: itemApplication, + TimeWorklogService: timeWorklogService, + PageApplicationService: pageApplication, + PageDiagramService: pageDiagramService, + Registry: aitools.Default, + }) + if err != nil { + return fmt.Errorf("construct Standard agent runtime: %w", err) + } + bindingSvc.SetStandardRunDispatcher(standardDispatcher) + s.standardAgentDispatcher = standardDispatcher + if err := standardDispatcher.Resume(context.Background()); err != nil { + return fmt.Errorf("resume Standard agent runtime: %w", err) + } + } itemDetailApplication := services.NewItemDetailApplicationService(s.db, itemApplication, itemLinkService, permService). WithContextReaders(screenHandler, requestTypeHandler, actionApplication). WithStoryPointRollups(repository.NewItemRepository(s.db)) @@ -2177,6 +2182,8 @@ func (s *Server) initialize() error { TimerService: timerService, CommentService: commentService, ItemDeletionService: itemHandler.ItemDeletionApplicationService(), + ItemApplicationService: itemApplication, + TimeWorklogService: timeWorklogService, PageApplicationService: pageApplication, PageDiagramService: pageDiagramService, ActionService: s.actionService, diff --git a/internal/services/asset_action_service.go b/internal/services/asset_action_service.go index be84884bd..2fbf713a2 100644 --- a/internal/services/asset_action_service.go +++ b/internal/services/asset_action_service.go @@ -634,7 +634,7 @@ func (as *AssetActionService) executeCreateItem(node *models.AssetActionNode, ct if err != nil { return fmt.Errorf("failed to create item: %w", err) } - itemID := result.Item.ID + itemID := result.ID stepResult.Output = map[string]any{ "item_id": itemID, diff --git a/internal/services/item_application_service.go b/internal/services/item_application_service.go index ababd5704..9450bc0f2 100644 --- a/internal/services/item_application_service.go +++ b/internal/services/item_application_service.go @@ -871,6 +871,33 @@ func (s *ItemApplicationService) Create(ctx context.Context, actor AuditActor, i return nil, err } items := []models.Item{*result.Item} + if err := s.enrich(ctx, actor.UserID, items); err != nil { + // Enrichment masks project names and related-item metadata before the + // label and milestone reads. Return the caller-facing copy either way so + // a later read failure cannot discard those redactions. + slog.Warn("enrich created item", slog.Int64("item_id", result.ID), slog.Any("error", err)) + } + if rendered, err := markdown.Render(items[0].Description); err != nil { + slog.Warn("render created item description", slog.Int64("item_id", result.ID), slog.Any("error", err)) + } else { + items[0].DescriptionHTML = rendered + } + return &items[0], nil +} + +func (s *ItemApplicationService) Patch(ctx context.Context, actor AuditActor, itemID int, fields map[string]json.RawMessage) (*models.Item, error) { + allowed, err := s.update.CanUserEditItem(actor.UserID, itemID) + if err != nil { + return nil, err + } + if !allowed { + return nil, ErrItemForbidden + } + result, err := s.patchItem(ctx, actor, itemID, fields) + if err != nil { + return nil, err + } + items := []models.Item{*result.Item} if err := s.enrich(ctx, actor.UserID, items); err != nil { return nil, err } @@ -881,7 +908,17 @@ func (s *ItemApplicationService) Create(ctx context.Context, actor AuditActor, i return &items[0], nil } -func (s *ItemApplicationService) Patch(ctx context.Context, actor AuditActor, itemID int, fields map[string]json.RawMessage) (*models.Item, error) { +// UpdateFieldsWithMetadata runs the shared update pipeline on an already-decoded +// field map while preserving explicit event provenance (agent actor/source/run). +// Agent adapters use it instead of the low-level update service so description +// mentions and hierarchy cache invalidation stay on the one path. +func (s *ItemApplicationService) UpdateFieldsWithMetadata( + ctx context.Context, + actor AuditActor, + itemID int, + fields map[string]any, + metadata itemevents.Metadata, +) (*models.Item, error) { allowed, err := s.update.CanUserEditItem(actor.UserID, itemID) if err != nil { return nil, err @@ -889,7 +926,7 @@ func (s *ItemApplicationService) Patch(ctx context.Context, actor AuditActor, it if !allowed { return nil, ErrItemForbidden } - result, err := s.patchItem(ctx, actor, itemID, fields) + result, err := s.update.UpdateWithMetadata(actor.UserID, actor.Username, itemID, fields, metadata) if err != nil { return nil, err } diff --git a/internal/services/item_creation.go b/internal/services/item_creation.go index 36a483a40..4c61505d6 100644 --- a/internal/services/item_creation.go +++ b/internal/services/item_creation.go @@ -28,6 +28,10 @@ type itemCreation struct { // eventMetadata is the merged provenance recorded with the creation fact. // finish() consults it so import-origin writes never start an agent run. eventMetadata itemevents.Metadata + // snapshot is the row the creation transaction recorded. It is a guaranteed + // creation result for callers that need a row or an event after commit, + // independent of a later joined read. + snapshot *models.Item } func prepareItemCreation(ctx context.Context, db database.Database, params ItemCreationParams) (*itemCreation, error) { @@ -351,6 +355,7 @@ func (c *itemCreation) recordCreation(tx database.Tx, itemID, itemNumber int) er if err != nil { return err } + c.snapshot = item metadata := itemCreateEventMetadata(c.params, c.createdAt) c.eventMetadata = metadata creatorUserID := 0 @@ -378,7 +383,7 @@ func (c *itemCreation) eventItem(itemID, itemNumber int) (*models.Item, error) { } p := c.params return &models.Item{ - ID: itemID, WorkspaceID: p.WorkspaceID, WorkspaceItemNumber: itemNumber, + ID: itemID, WorkspaceID: p.WorkspaceID, WorkspaceKey: p.WorkspaceKey, WorkspaceItemNumber: itemNumber, ItemTypeID: p.ItemTypeID, Title: p.Title, Description: p.Description, StatusID: c.statusID, PriorityID: c.priorityID, IsTask: p.IsTask, AssigneeID: p.AssigneeID, TeamID: p.TeamID, ReporterID: p.ReporterID, CreatorID: p.CreatorID, diff --git a/internal/services/item_creation_service.go b/internal/services/item_creation_service.go index 19358994c..94689cb96 100644 --- a/internal/services/item_creation_service.go +++ b/internal/services/item_creation_service.go @@ -1,9 +1,10 @@ package services import ( + "context" "encoding/json" "errors" - "fmt" + "log/slog" "time" "windshift/internal/database" @@ -63,6 +64,10 @@ type ItemCreateInput struct { type ItemCreateResult struct { Item *models.Item MandatoryTemplate MandatoryTemplateInfo + // ID is the row created by the transaction. It is always set, even when the + // post-commit detail read fails, so a caller can report and audit the stored + // item instead of retrying and duplicating it. + ID int64 } // ItemCreationValidationError identifies validation performed before the @@ -207,8 +212,9 @@ func (s *ItemCreationService) create( var mandatoryTemplate MandatoryTemplateInfo metadata := mergeItemEventMetadata(input.EventMetadata, itemEventMetadata(actorUserID, "application", actionContext)) - itemID, err := CreateItem(s.db, ItemCreationParams{ + itemID, snapshot, err := createItemWithSnapshot(context.Background(), s.db, ItemCreationParams{ WorkspaceID: input.WorkspaceID, + WorkspaceKey: validationResult.WorkspaceKey, Title: input.Title, Description: input.Description, StatusID: input.StatusID, @@ -242,18 +248,24 @@ func (s *ItemCreationService) create( return nil, err } + // The transaction's ID and snapshot are the create result. The joined read + // only decorates the response, so a failure must not turn a committed create + // into an error a caller would retry or leave callers without a row. + result := &ItemCreateResult{ID: itemID, Item: snapshot, MandatoryTemplate: mandatoryTemplate} item, err := repository.NewItemRepository(s.db).FindByIDWithDetails(int(itemID)) if err != nil { - return nil, fmt.Errorf("load created item: %w", err) + slog.Error("load created item after commit", slog.Int64("item_id", itemID), slog.Any("error", err)) + } else { + result.Item = item } // Imported facts are historical: skip the live notification/webhook/automation // pipeline even though validation and persistence used the canonical path. if !itemevents.IsImportOrigin(metadata.ActorKind, metadata.SourceKind) { if contextual, ok := s.emitter.(contextualItemCreatedEmitter); ok && actionContext != nil { - contextual.EmitItemCreatedWithContext(item, actorUserID, *actionContext, actorUsername) + contextual.EmitItemCreatedWithContext(result.Item, actorUserID, *actionContext, actorUsername) } else if s.emitter != nil { - s.emitter.EmitItemCreated(item, actorUserID, actorUsername) + s.emitter.EmitItemCreated(result.Item, actorUserID, actorUsername) } } - return &ItemCreateResult{Item: item, MandatoryTemplate: mandatoryTemplate}, nil + return result, nil } diff --git a/internal/services/item_update_application_service.go b/internal/services/item_update_application_service.go index ee4a45626..9d260c10f 100644 --- a/internal/services/item_update_application_service.go +++ b/internal/services/item_update_application_service.go @@ -8,6 +8,7 @@ import ( "time" "windshift/internal/database" + "windshift/internal/itemevents" "windshift/internal/models" "windshift/internal/validation" ) @@ -295,6 +296,31 @@ func (s *ItemUpdateApplicationService) updateItem( itemID int, updateData map[string]any, actionContext *ActionContext, +) (*UpdateItemResult, error) { + return s.updateItemWithMetadata(actorUserID, actorUsername, itemID, updateData, actionContext, + itemEventMetadata(actorUserID, "application", actionContext)) +} + +// UpdateWithMetadata runs the user-facing update pipeline with explicit event +// provenance. Agent adapters use it so the agent actor, source, and run survive +// instead of being replaced by the human-only "application" default. +func (s *ItemUpdateApplicationService) UpdateWithMetadata( + actorUserID int, + actorUsername string, + itemID int, + updateData map[string]any, + metadata itemevents.Metadata, +) (*UpdateItemResult, error) { + return s.updateItemWithMetadata(actorUserID, actorUsername, itemID, updateData, nil, metadata) +} + +func (s *ItemUpdateApplicationService) updateItemWithMetadata( + actorUserID int, + actorUsername string, + itemID int, + updateData map[string]any, + actionContext *ActionContext, + metadata itemevents.Metadata, ) (*UpdateItemResult, error) { if s.activityTracker != nil { if err := s.activityTracker.TrackItemActivity(actorUserID, itemID, ActivityEdit); err != nil { @@ -306,7 +332,7 @@ func (s *ItemUpdateApplicationService) updateItem( ItemID: itemID, UpdateData: updateData, UserID: actorUserID, - EventMetadata: itemEventMetadata(actorUserID, "application", actionContext), + EventMetadata: metadata, }) if err != nil { return nil, err @@ -355,8 +381,9 @@ func (s *ItemUpdateApplicationService) AddMilestoneWithContext( actionContext ActionContext, ) (*UpdateItemResult, bool, error) { result, changed, err := s.update.AddMilestone(UpdateItemRequest{ - ItemID: itemID, - UserID: actorUserID, + ItemID: itemID, + UserID: actorUserID, + EventMetadata: itemEventMetadata(actorUserID, "application", &actionContext), }, milestoneID) if err != nil || !changed { return result, changed, err diff --git a/internal/services/item_validation.go b/internal/services/item_validation.go index b4c233bac..8dc6445cb 100644 --- a/internal/services/item_validation.go +++ b/internal/services/item_validation.go @@ -1,6 +1,7 @@ package services import ( + "database/sql" "errors" "fmt" "strings" @@ -30,6 +31,10 @@ type ItemValidationParams struct { type ItemValidationResult struct { Valid bool Error string + // WorkspaceKey is the validated workspace's display key. Carrying it here + // keeps one source of identity for the creation snapshot, so a caller that + // cannot do a joined read still has the item key. + WorkspaceKey string } // IsItemTypeAllowedInWorkspace checks whether the given item type is allowed @@ -60,15 +65,15 @@ func ValidateItemCreation(db database.Database, params ItemValidationParams) *It return &ItemValidationResult{Valid: false, Error: "Title is required"} } - // Validate workspace exists - var workspaceExists bool - err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM workspaces WHERE id = ?)", params.WorkspaceID).Scan(&workspaceExists) + // Validate workspace exists and carry its key for the creation snapshot. + var workspaceKey string + err := db.QueryRow("SELECT key FROM workspaces WHERE id = ?", params.WorkspaceID).Scan(&workspaceKey) + if errors.Is(err, sql.ErrNoRows) { + return &ItemValidationResult{Valid: false, Error: "Workspace not found"} + } if err != nil { return &ItemValidationResult{Valid: false, Error: fmt.Sprintf("Failed to validate workspace: %v", err)} } - if !workspaceExists { - return &ItemValidationResult{Valid: false, Error: "Workspace not found"} - } // Validate parent item if specified if params.ParentID != nil && *params.ParentID != 0 { @@ -90,7 +95,7 @@ func ValidateItemCreation(db database.Database, params ItemValidationParams) *It } } - return &ItemValidationResult{Valid: true} + return &ItemValidationResult{Valid: true, WorkspaceKey: workspaceKey} } // validateParentHierarchy validates the parent-child hierarchy relationship. diff --git a/internal/services/items.go b/internal/services/items.go index a2ce107b0..4aec0a502 100644 --- a/internal/services/items.go +++ b/internal/services/items.go @@ -10,6 +10,7 @@ import ( "windshift/internal/database" "windshift/internal/itemevents" + "windshift/internal/models" ) // ErrMissingItemType is returned by CreateItem when the caller did not @@ -82,7 +83,11 @@ func resolvePriorityIDByName(db database.Database, priority string) (*int, error // ItemCreationParams contains all parameters for creating an item type ItemCreationParams struct { - WorkspaceID int + WorkspaceID int + // WorkspaceKey is the workspace's display key. Callers that validate first + // carry it from the validation result so the creation snapshot has the + // item key without a second lookup. + WorkspaceKey string Title string Description string Status string // Text status (legacy) - mapped to StatusID if StatusID is nil @@ -286,17 +291,25 @@ func CreateItemContext(ctx context.Context, db database.Database, params ItemCre } func createItem(ctx context.Context, db database.Database, params ItemCreationParams) (int64, error) { + itemID, _, err := createItemWithSnapshot(ctx, db, params) + return itemID, err +} + +// createItemWithSnapshot creates an item and returns the snapshot the creation +// transaction recorded. Callers that need a row or an event after commit use +// the snapshot instead of a second, fallible joined read. +func createItemWithSnapshot(ctx context.Context, db database.Database, params ItemCreationParams) (int64, *models.Item, error) { creation, err := prepareItemCreation(ctx, db, params) if err != nil { - return 0, err + return 0, nil, err } itemID, err := creation.insert() if err != nil { - return 0, err + return 0, nil, err } creation.finish(itemID) - return int64(itemID), nil + return int64(itemID), creation.snapshot, nil } // GetInitialStatusForItemType determines the initial status for an item type diff --git a/internal/services/workspace_bundle_import.go b/internal/services/workspace_bundle_import.go index dc741197f..9a8663c5a 100644 --- a/internal/services/workspace_bundle_import.go +++ b/internal/services/workspace_bundle_import.go @@ -941,7 +941,7 @@ func (s *WorkspaceBundleImportService) importItems(ctx context.Context, imp *wor imp.outcome("item", item.Ref, item.Title, "failed", err.Error()) continue } - imp.itemIDs[item.Ref] = created.Item.ID + imp.itemIDs[item.Ref] = int(created.ID) detail := "" if len(droppedLabels) > 0 { detail = "labels not available: " + strings.Join(droppedLabels, ", ") diff --git a/internal/standardagent/dispatcher.go b/internal/standardagent/dispatcher.go index ab3e184f1..2ea94ae92 100644 --- a/internal/standardagent/dispatcher.go +++ b/internal/standardagent/dispatcher.go @@ -57,8 +57,13 @@ type Options struct { ActionService *services.ActionService PageApplicationService *services.PageApplicationService PageDiagramService *services.PageDiagramService - Registry *aitools.Registry - RunTimeout time.Duration + // ItemApplication and TimeWorklogService are the shared mutation + // pipelines the tools call. They must be installed before Resume starts a + // queued run, so agent writes match the HTTP surfaces. + ItemApplication *services.ItemApplicationService + TimeWorklogService *services.TimeWorklogService + Registry *aitools.Registry + RunTimeout time.Duration } // ProfileSnapshot is deliberately limited to non-secret execution inputs. @@ -283,6 +288,8 @@ func (d *Dispatcher) RunPrivateTest(ctx context.Context, binding *models.Workspa CommentService: d.opts.Comments, ApprovalService: d.opts.Approvals, ActionService: d.opts.ActionService, + ItemApplication: d.opts.ItemApplication, + TimeWorklogService: d.opts.TimeWorklogService, PageApplicationService: d.opts.PageApplicationService, PageDiagramService: d.opts.PageDiagramService, }, entries) @@ -479,6 +486,8 @@ func (d *Dispatcher) execute(run *models.AgentRun) { CommentService: d.opts.Comments, ApprovalService: d.opts.Approvals, ActionService: d.opts.ActionService, + ItemApplication: d.opts.ItemApplication, + TimeWorklogService: d.opts.TimeWorklogService, PageApplicationService: d.opts.PageApplicationService, PageDiagramService: d.opts.PageDiagramService, }, entries) diff --git a/scripts/.handler-db-access-allowlist b/scripts/.handler-db-access-allowlist index 9bad7660b..a579a62e1 100644 --- a/scripts/.handler-db-access-allowlist +++ b/scripts/.handler-db-access-allowlist @@ -43,3 +43,6 @@ internal/handlers/setup.go internal/handlers/sla.go internal/handlers/webauthn.go internal/handlers/workspaces_personal.go +internal/restapi/v2/catalog.go +internal/restapi/v2/labels.go +internal/restapi/v2/preferences.go diff --git a/scripts/check-handler-db-access.sh b/scripts/check-handler-db-access.sh index 79661e663..4705a883b 100755 --- a/scripts/check-handler-db-access.sh +++ b/scripts/check-handler-db-access.sh @@ -14,6 +14,7 @@ ALLOWLIST="scripts/.handler-db-access-allowlist" HANDLER_DIRS=( "internal/handlers" "internal/restapi/v1/handlers" + "internal/restapi/v2" ) # Match direct DB methods while avoiding URL query parsing (`r.URL.Query()`). diff --git a/scripts/check-layering.sh b/scripts/check-layering.sh index f5ed73c35..b7bbd578b 100755 --- a/scripts/check-layering.sh +++ b/scripts/check-layering.sh @@ -47,6 +47,9 @@ for rule in "${RULES[@]}"; do [[ -d "$pkg" ]] || continue + # Match the forbidden package exactly or any subpackage of it, so a leaf + # rule like cacheutil|windshift/internal also catches + # windshift/internal/ imports. while IFS= read -r match; do [[ -z "$match" ]] && continue # match looks like: internal/handlers/foo.go:12: "windshift/internal/database" @@ -58,7 +61,7 @@ for rule in "${RULES[@]}"; do fi new_violations+=("$match -- $rationale") found=1 - done < <(grep -rn "\"$forbidden\"" "$pkg" --include='*.go' 2>/dev/null | grep -v '_test\.go' || true) + done < <(grep -rnE "\"${forbidden}(\"|/)" "$pkg" --include='*.go' 2>/dev/null | grep -v '_test\.go' || true) done if [[ "$found" -eq 1 ]]; then