+ path is relative to the v2 REST root (for example
+ /items/123). Alternate hosts, redirects, path escapes, and
+ unsupported routes are rejected. Requests run with a short-lived token
+ scoped to this executor and are audited with the action, execution, and
+ node that produced them.
+
+
+ console.log/info/warn/error/debug write bounded lines to the
+ execution trace.
+
+
+
+
+
diff --git a/frontend/src/lib/features/actions/nodes/ExecuteScriptNode.svelte b/frontend/src/lib/features/actions/nodes/ExecuteScriptNode.svelte
new file mode 100644
index 000000000..e691022b9
--- /dev/null
+++ b/frontend/src/lib/features/actions/nodes/ExecuteScriptNode.svelte
@@ -0,0 +1,10 @@
+
+
+
diff --git a/frontend/src/lib/locales/ar/actions.js b/frontend/src/lib/locales/ar/actions.js
index effbc6319..c8e9e9b83 100644
--- a/frontend/src/lib/locales/ar/actions.js
+++ b/frontend/src/lib/locales/ar/actions.js
@@ -61,6 +61,7 @@ export default {
transitionItem: 'نقل العنصر',
roundRobinAssign: 'تعيين بالتناوب',
createMilestone: 'إنشاء معلم',
+ executeScript: 'تشغيل البرنامج النصي',
},
aiUpdated: 'تم تحديث الإجراء بواسطة الذكاء الاصطناعي',
@@ -165,6 +166,7 @@ export default {
completed: 'مكتمل',
failed: 'فشل',
skipped: 'تم تخطيه',
+ reconciliationRequired: 'مطلوب تسوية',
startedAt: 'بدأ في',
completedAt: 'اكتمل في',
error: 'خطأ',
diff --git a/frontend/src/lib/locales/de/actions.js b/frontend/src/lib/locales/de/actions.js
index f41b077b8..a06024c15 100644
--- a/frontend/src/lib/locales/de/actions.js
+++ b/frontend/src/lib/locales/de/actions.js
@@ -67,6 +67,7 @@ export default {
transitionItem: 'Vorgang überführen',
roundRobinAssign: 'Round-Robin zuweisen',
createMilestone: 'Meilenstein erstellen',
+ executeScript: 'Skript ausführen',
},
aiUpdated: 'Aktion durch KI aktualisiert',
@@ -168,6 +169,7 @@ export default {
completed: 'Abgeschlossen',
failed: 'Fehlgeschlagen',
skipped: 'Übersprungen',
+ reconciliationRequired: 'Abgleich erforderlich',
startedAt: 'Gestartet um',
completedAt: 'Abgeschlossen um',
error: 'Fehler',
diff --git a/frontend/src/lib/locales/en/actions.js b/frontend/src/lib/locales/en/actions.js
index d855cfc03..043e2569a 100644
--- a/frontend/src/lib/locales/en/actions.js
+++ b/frontend/src/lib/locales/en/actions.js
@@ -82,6 +82,7 @@ export default {
notifyCustomer: 'Notify customer',
insertCannedResponse: 'Insert canned response',
adjustLabels: 'Adjust labels',
+ executeScript: 'Run script',
},
// Toast shown when the AI chat updates the open action via update_action.
@@ -266,6 +267,7 @@ export default {
completed: 'Completed',
failed: 'Failed',
skipped: 'Skipped',
+ reconciliationRequired: 'Reconciliation required',
startedAt: 'Started At',
completedAt: 'Completed At',
error: 'Error',
diff --git a/frontend/src/lib/locales/es/actions.js b/frontend/src/lib/locales/es/actions.js
index 09d6fb77a..3fdbb6af5 100644
--- a/frontend/src/lib/locales/es/actions.js
+++ b/frontend/src/lib/locales/es/actions.js
@@ -62,6 +62,7 @@ export default {
transitionItem: 'Transicionar elemento',
roundRobinAssign: 'Asignar por turno rotativo',
createMilestone: 'Crear hito',
+ executeScript: 'Ejecutar script',
},
aiUpdated: 'Acción actualizada por IA',
@@ -167,6 +168,7 @@ export default {
completed: 'Completado',
failed: 'Fallido',
skipped: 'Omitido',
+ reconciliationRequired: 'Se requiere reconciliación',
startedAt: 'Iniciado a las',
completedAt: 'Completado a las',
error: 'Error',
diff --git a/frontend/src/lib/locales/fa/actions.js b/frontend/src/lib/locales/fa/actions.js
index f99d0d160..dd67b0aec 100644
--- a/frontend/src/lib/locales/fa/actions.js
+++ b/frontend/src/lib/locales/fa/actions.js
@@ -64,6 +64,7 @@ export default {
"transitionItem": "مورد انتقال",
"roundRobinAssign": "تخصیص نوبتی",
"createMilestone": "نقطه عطف ایجاد کنید",
+ "executeScript": "اجرای اسکریپت",
"notifyCustomer": "به مشتری اطلاع دهید",
"insertCannedResponse": "درج پاسخ آماده",
"adjustLabels": "برچسب ها را تنظیم کنید"
@@ -225,6 +226,7 @@ export default {
"completed": "تکمیل شد",
"failed": "شکست خورد",
"skipped": "رد شد",
+ "reconciliationRequired": "نیاز به تطبیق",
"startedAt": "شروع شده در",
"completedAt": "تکمیل شده در",
"error": "خطا",
diff --git a/frontend/src/lib/locales/fr/actions.js b/frontend/src/lib/locales/fr/actions.js
index ce62cdec8..b3af12735 100644
--- a/frontend/src/lib/locales/fr/actions.js
+++ b/frontend/src/lib/locales/fr/actions.js
@@ -73,6 +73,7 @@ export default {
transitionItem: 'Faire évoluer l’élément',
roundRobinAssign: 'Attribution à tour de rôle',
createMilestone: 'Créer un jalon',
+ executeScript: 'Exécuter le script',
},
// Toast shown when the AI chat updates the open action via update_action.
@@ -235,6 +236,7 @@ export default {
completed: 'Terminé',
failed: 'Échoué',
skipped: 'Ignoré',
+ reconciliationRequired: 'Réconciliation requise',
startedAt: 'Démarré le',
completedAt: 'Terminé le',
error: 'Erreur',
diff --git a/frontend/src/lib/locales/it/actions.js b/frontend/src/lib/locales/it/actions.js
index be6eca255..34b3a81e5 100644
--- a/frontend/src/lib/locales/it/actions.js
+++ b/frontend/src/lib/locales/it/actions.js
@@ -71,6 +71,7 @@ export default {
transitionItem: 'Transizione elemento',
roundRobinAssign: 'Assegnazione a rotazione',
createMilestone: 'Crea milestone',
+ executeScript: 'Esegui script',
notifyCustomer: 'Notifica cliente',
insertCannedResponse: 'Inserisci risposta predefinita',
adjustLabels: 'Modifica etichette',
@@ -257,6 +258,7 @@ export default {
completed: 'Completata',
failed: 'Non riuscita',
skipped: 'Saltata',
+ reconciliationRequired: 'Riconciliazione richiesta',
startedAt: 'Avviata il',
completedAt: 'Completata il',
error: 'Errore',
diff --git a/frontend/src/lib/locales/ko/actions.js b/frontend/src/lib/locales/ko/actions.js
index 69bdca7a1..a04517e53 100644
--- a/frontend/src/lib/locales/ko/actions.js
+++ b/frontend/src/lib/locales/ko/actions.js
@@ -53,7 +53,8 @@ export default {
"relatedItems": "각 관련 작업에 대해 실행",
"transitionItem": "작업 상태 전환",
"roundRobinAssign": "순환 배정",
- "createMilestone": "마일스톤 만들기"
+ "createMilestone": "마일스톤 만들기",
+ "executeScript": "스크립트 실행"
},
"aiUpdated": "AI가 자동화를 수정했습니다",
"runAs": "실행 사용자",
@@ -191,6 +192,7 @@ export default {
"completed": "완료",
"failed": "실패",
"skipped": "건너뜀",
+ "reconciliationRequired": "조정 필요",
"startedAt": "시작 시각",
"completedAt": "완료 시각",
"error": "오류",
diff --git a/frontend/src/lib/locales/pl/actions.js b/frontend/src/lib/locales/pl/actions.js
index 425951808..6acba7f4e 100644
--- a/frontend/src/lib/locales/pl/actions.js
+++ b/frontend/src/lib/locales/pl/actions.js
@@ -77,6 +77,7 @@ export default {
transitionItem: 'Przejście elementu',
roundRobinAssign: 'Przypisanie rotacyjne',
createMilestone: 'Utwórz kamień milowy',
+ executeScript: 'Uruchom skrypt',
notifyCustomer: 'Powiadom klienta',
insertCannedResponse: 'Wstaw gotową odpowiedź',
adjustLabels: 'Dostosuj etykiety',
@@ -266,6 +267,7 @@ export default {
completed: 'Zakończone',
failed: 'Niepowodzenie',
skipped: 'Pominięte',
+ reconciliationRequired: 'Wymagane uzgodnienie',
startedAt: 'Rozpoczęto',
completedAt: 'Zakończono',
error: 'Błąd',
diff --git a/frontend/src/lib/locales/pt-BR/actions.js b/frontend/src/lib/locales/pt-BR/actions.js
index c58ff4680..29bd70a8b 100644
--- a/frontend/src/lib/locales/pt-BR/actions.js
+++ b/frontend/src/lib/locales/pt-BR/actions.js
@@ -62,6 +62,7 @@ export default {
transitionItem: 'Transicionar item',
roundRobinAssign: 'Atribuir em rodízio',
createMilestone: 'Criar marco',
+ executeScript: 'Executar script',
},
aiUpdated: 'Ação atualizada pela IA',
@@ -167,6 +168,7 @@ export default {
completed: 'Concluído',
failed: 'Falhou',
skipped: 'Ignorado',
+ reconciliationRequired: 'Reconciliação necessária',
startedAt: 'Iniciado em',
completedAt: 'Concluído em',
error: 'Erro',
diff --git a/frontend/src/lib/locales/ru/actions.js b/frontend/src/lib/locales/ru/actions.js
index 336a683e4..4c7c8dfcc 100644
--- a/frontend/src/lib/locales/ru/actions.js
+++ b/frontend/src/lib/locales/ru/actions.js
@@ -76,6 +76,7 @@ export default {
transitionItem: 'Изменить статус элемента',
roundRobinAssign: 'Назначить по очереди',
createMilestone: 'Создать этап',
+ executeScript: 'Запустить скрипт',
notifyCustomer: 'Уведомить клиента',
insertCannedResponse: 'Вставить шаблон ответа',
adjustLabels: 'Изменить метки',
@@ -252,6 +253,7 @@ export default {
completed: 'Завершено',
failed: 'Ошибка',
skipped: 'Пропущено',
+ reconciliationRequired: 'Требуется сверка',
startedAt: 'Начало',
completedAt: 'Окончание',
error: 'Ошибка',
diff --git a/frontend/src/lib/locales/zh-CN/actions.js b/frontend/src/lib/locales/zh-CN/actions.js
index b421d4658..ee7e1c0df 100644
--- a/frontend/src/lib/locales/zh-CN/actions.js
+++ b/frontend/src/lib/locales/zh-CN/actions.js
@@ -57,6 +57,7 @@ export default {
transitionItem: '过渡项目',
roundRobinAssign: '轮询分配',
createMilestone: '创建里程碑',
+ executeScript: '运行脚本',
},
aiUpdated: 'AI 已更新动作',
addNodes: '添加节点',
@@ -147,6 +148,7 @@ export default {
completed: '已完成',
failed: '失败',
skipped: '已跳过',
+ reconciliationRequired: '需要核对',
startedAt: '开始时间',
completedAt: '完成时间',
error: '错误',
diff --git a/internal/models/integration.go b/internal/models/integration.go
index 4bdde5d55..ed7f9d60c 100644
--- a/internal/models/integration.go
+++ b/internal/models/integration.go
@@ -894,6 +894,12 @@ const (
// ActionNodeAdjustLabels adds and removes item labels on the trigger
// item (WI-1132).
ActionNodeAdjustLabels ActionNodeType = "adjust_labels"
+ // ActionNodeExecuteScript runs an author-supplied JavaScript function body
+ // through Sobek with the effective action executor's identity (WI-2174).
+ // The script may call the canonical v2 REST API through a server-minted,
+ // short-lived bearer token scoped to that executor; it never chooses its
+ // own identity or credentials.
+ ActionNodeExecuteScript ActionNodeType = "execute_script"
)
// IsIterator reports whether this node type fans out — i.e. the engine must
@@ -910,6 +916,10 @@ const (
ActionStatusCompleted ActionExecutionStatus = "completed"
ActionStatusFailed ActionExecutionStatus = "failed"
ActionStatusSkipped ActionExecutionStatus = "skipped"
+ // ActionStatusReconciliationRequired marks an execution that committed a
+ // partial side effect (an execute_script write) and then failed. Durable
+ // replay must not rerun it; an operator reconciles the partial write.
+ ActionStatusReconciliationRequired ActionExecutionStatus = "reconciliation_required"
)
// Action represents a workspace-scoped automation definition
@@ -1128,6 +1138,21 @@ type ExecutionContext struct {
// engine's per-flow step budget so a misconfigured nested iterator can't
// fan out into millions of executions before the cascade-depth guard fires.
TotalSteps int `json:"-"`
+ // ExecutionLogID is the persisted action_execution_logs row for this run,
+ // when one exists. Script REST calls carry it as trusted provenance.
+ ExecutionLogID int `json:"-"`
+ // DefinitionRevisionID is the immutable definition revision this execution
+ // is bound to, when known. Script REST calls carry it as trusted provenance.
+ DefinitionRevisionID *int `json:"-"`
+ // ReconciliationRequired is set when an execute_script node committed a
+ // mutating REST call and the flow later failed. Durable replay must not
+ // rerun the flow, because the committed write would be repeated.
+ ReconciliationRequired bool `json:"-"`
+ // ScriptWriteMarked records that the write-ahead reconciliation marker has
+ // already been persisted for this execution. It is shared across every
+ // script node and iterator pass in the flow so repeated marking of the same
+ // log is a no-op rather than an invalid-state failure.
+ ScriptWriteMarked bool `json:"-"`
}
// StepResult holds the result of executing a single node
@@ -1282,6 +1307,19 @@ type AdjustLabelsNodeConfig struct {
RemoveLabelIDs []int `json:"remove_label_ids,omitempty"`
}
+// ExecuteScriptNodeConfig configures an execute_script node (WI-2174). Source
+// is a JavaScript function body; an explicit return value becomes the node's
+// JSON output. OutputVariable names the execution-context variable that
+// downstream nodes read; it may not shadow reserved actor/context variables.
+// TimeoutMs and MaxAPICalls narrow the server-enforced budgets and are clamped
+// to the hard caps so a definition can never widen them.
+type ExecuteScriptNodeConfig struct {
+ Source string `json:"source"`
+ OutputVariable string `json:"output_variable,omitempty"`
+ TimeoutMs int `json:"timeout_ms,omitempty"`
+ MaxAPICalls int `json:"max_api_calls,omitempty"`
+}
+
// NotifyUserNodeConfig configures a notify_user node
type NotifyUserNodeConfig struct {
Recipients []string `json:"recipients,omitempty"` // "assignee", "creator", or specific user IDs
diff --git a/internal/repository/action_repository.go b/internal/repository/action_repository.go
index 43415fd75..af49830c7 100644
--- a/internal/repository/action_repository.go
+++ b/internal/repository/action_repository.go
@@ -733,6 +733,33 @@ func (r *ActionRepository) UpdateExecutionLog(log *models.ActionExecutionLog) er
return nil
}
+// MarkExecutionReconciliationRequired persists the write-ahead marker for an
+// execution whose script may commit a side effect. It promotes a running or
+// previously failed attempt to reconciliation_required, so a crash after the
+// commit leaves the log non-replayable. A no-op update is an error: the caller
+// must not dispatch a write whose marker was not persisted. It never overwrites
+// a terminal completed/reconciliation_required/skipped status.
+func (r *ActionRepository) MarkExecutionReconciliationRequired(logID int) error {
+ result, err := r.db.ExecWrite(`
+ UPDATE action_execution_logs
+ SET status = ?, error_message = ?
+ WHERE id = ? AND status IN (?, ?)
+ `, models.ActionStatusReconciliationRequired,
+ "requires reconciliation: a script write was in flight",
+ logID, models.ActionStatusRunning, models.ActionStatusFailed)
+ if err != nil {
+ return fmt.Errorf("failed to mark execution reconciliation required: %w", err)
+ }
+ affected, err := result.RowsAffected()
+ if err != nil {
+ return fmt.Errorf("failed to check execution marker rows affected: %w", err)
+ }
+ if affected == 0 {
+ return fmt.Errorf("execution log %d is not in a markable state", logID)
+ }
+ return nil
+}
+
// GetExecutionLogsByActionID retrieves execution logs for an action
func (r *ActionRepository) GetExecutionLogsByActionID(actionID, limit, offset int) ([]*models.ActionExecutionLog, error) {
rows, err := r.db.Query(`
diff --git a/internal/restapi/v2/comments.go b/internal/restapi/v2/comments.go
index 31108be64..6b03d59f5 100644
--- a/internal/restapi/v2/comments.go
+++ b/internal/restapi/v2/comments.go
@@ -237,7 +237,7 @@ func createComment(deps Deps) jsonOperation[commentCreateRequest, models.Comment
if err := requireCommentPermission(deps, user.ID, item.WorkspaceID, models.PermissionItemComment); err != nil {
return models.Comment{}, err
}
- result, err := deps.Comments.Create(services.CreateCommentParams{ItemID: item.ID, AuthorID: user.ID, Content: input.Content, IsPrivate: input.IsPrivate, ActorUserID: user.ID})
+ result, err := deps.Comments.CreateContext(r.Context(), services.CreateCommentParams{ItemID: item.ID, AuthorID: user.ID, Content: input.Content, IsPrivate: input.IsPrivate, ActorUserID: user.ID})
if err != nil {
return models.Comment{}, commentError(err)
}
diff --git a/internal/restapi/v2/router.go b/internal/restapi/v2/router.go
index 8fa1051e7..18013cfbc 100644
--- a/internal/restapi/v2/router.go
+++ b/internal/restapi/v2/router.go
@@ -500,6 +500,7 @@ type commentApplication interface {
CountFeedByItemID(int) (int, error)
UserCanReadItemAsApprover(context.Context, int, int) (bool, error)
Create(services.CreateCommentParams) (*services.CreateCommentResult, error)
+ CreateContext(context.Context, services.CreateCommentParams) (*services.CreateCommentResult, error)
UpdateWithEffects(services.UpdateCommentParams) (*models.Comment, error)
DeleteWithEffects(services.DeleteCommentParams) error
AttachReactions([]models.Comment) error
diff --git a/internal/server/server.go b/internal/server/server.go
index 8b9244194..becd37e1a 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -2127,6 +2127,15 @@ func (s *Server) initialize() error {
return fmt.Errorf("register REST API v2: %w", err)
}
+ // execute_script runs author-supplied JavaScript as the effective action
+ // executor. REST calls from the script go through the mounted v2 handler
+ // with a short-lived token minted for that executor, so bearer auth, token
+ // scopes, and every handler-level authorization check still apply.
+ s.actionService.RegisterNodeExecutor(
+ services.NewExecuteScriptExecutor(tokenManager, services.NewInProcessV2Dispatcher(mux, 0)).
+ WithWriteMarker(s.actionService),
+ )
+
// MCP Server (Model Context Protocol) — opt-in via --mcp or MCP_ENABLED=true
if cfg.MCPEnabled {
mcpServer := mcpserver.NewMCPServer(mcpserver.Deps{
diff --git a/internal/services/action_script_bridge.go b/internal/services/action_script_bridge.go
new file mode 100644
index 000000000..166d61c6b
--- /dev/null
+++ b/internal/services/action_script_bridge.go
@@ -0,0 +1,301 @@
+package services
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+// ScriptAPIRequest is the one request shape an execute_script node can make.
+// The script supplies method, path, and body only; the bridge supplies the
+// credential and every header, so a script cannot inject an Authorization
+// header, cookie, forwarding header, alternate host, or redirect target.
+type ScriptAPIRequest struct {
+ Method string
+ Path string
+ Body []byte
+}
+
+// ScriptAPIResponse is the bounded, detached result handed back to the script.
+// Truncated is true when the response body exceeded the per-call cap.
+type ScriptAPIResponse struct {
+ Status int
+ Body []byte
+ Truncated bool
+}
+
+// ScriptAPIDispatcher executes one validated request against the canonical v2
+// API. Implementations must preserve the bearer auth and scope middleware; the
+// in-process implementation does so by invoking the real mounted handler.
+type ScriptAPIDispatcher interface {
+ Dispatch(ctx context.Context, bearer string, req ScriptAPIRequest) (ScriptAPIResponse, error)
+}
+
+// ErrScriptAPIPolicy marks a request the bridge refuses before dispatch —
+// alternate hosts, path escapes, disallowed routes, or unsupported methods.
+// It is fatal to the node: a script cannot catch it and continue.
+type ErrScriptAPIPolicy struct{ Reason string }
+
+func (e *ErrScriptAPIPolicy) Error() string { return "script api policy violation: " + e.Reason }
+
+func scriptAPIPolicyErrorf(format string, args ...any) error {
+ return &ErrScriptAPIPolicy{Reason: fmt.Sprintf(format, args...)}
+}
+
+// actionScriptAllowedResources is the initial bridge allowlist of v2 top-level
+// resources. It deliberately excludes admin, actions, agent-runs, api-tokens,
+// oauth, mcp, configuration-sets, screens, workspace-roles, packs, assets, and
+// tests: those surfaces can mint credentials, delegate identity, or author
+// further automations, which a script must never reach even when the executor
+// could. Reads and writes inside the allowlist still require the matching
+// token scope and the executor's own resource permissions.
+var actionScriptAllowedResources = map[string]bool{
+ "items": true,
+ "comments": true,
+ "links": true,
+ "link-types": true,
+ "watchers": true,
+ "milestones": true,
+ "iterations": true,
+ "time": true,
+ "users": true,
+ "workspaces": true,
+ "statuses": true,
+ "status-categories": true,
+ "workflows": true,
+ "item-types": true,
+ "priorities": true,
+ "custom-fields": true,
+ "labels": true,
+ "planning": true,
+ "story-points": true,
+ "pages": true,
+ "attachments": true,
+}
+
+// actionScriptAllowedMethods excludes DELETE: destructive writes need explicit
+// scopes the action allowlist does not grant, and denying the method here is a
+// second, independent guard.
+var actionScriptAllowedMethods = map[string]bool{
+ http.MethodGet: true,
+ http.MethodHead: true,
+ http.MethodPost: true,
+ http.MethodPut: true,
+ http.MethodPatch: true,
+}
+
+// actionScriptDeniedPaths lists v2 routes whose mutation path does not preserve
+// the action cascade (bulk item writes emit update events without an
+// ActionContext), so they are excluded from the initial bridge even though
+// their top-level resource is allowed. Bulk transition is not listed: it flows
+// through the same per-item transition path that carries provenance.
+var actionScriptDeniedPaths = []string{
+ "/items/bulk-update",
+ "/items/bulk-patch",
+ "/items/bulk-delete",
+}
+
+// scriptMutationRule is one audited mutating route. A script may only change
+// state through routes whose persistence and emitted action events carry the
+// action cascade provenance. Every other mutation is denied: an unaudited
+// mutation would emit a fresh user-origin event and reset the chain, depth, and
+// private-trigger flag, which is the unbounded-loop vector WI-2174 closes.
+//
+// "*" matches one non-empty path segment. Reads are not governed by this list.
+type scriptMutationRule struct {
+ method string
+ segments []string
+}
+
+var actionScriptAllowedMutations = []scriptMutationRule{
+ {http.MethodPost, []string{"items"}}, // create item
+ {http.MethodPatch, []string{"items", "*"}}, // update item
+ {http.MethodPost, []string{"items", "*", "transition"}}, // workflow transition
+ {http.MethodPost, []string{"items", "*", "comments"}}, // comment on item
+ {http.MethodPost, []string{"items", "bulk-transition"}}, // per-item transition
+}
+
+func scriptMutationAllowed(method string, segments []string) bool {
+ for _, rule := range actionScriptAllowedMutations {
+ if rule.method != method || len(rule.segments) != len(segments) {
+ continue
+ }
+ matched := true
+ for i, segment := range rule.segments {
+ if segment != "*" && segment != segments[i] {
+ matched = false
+ break
+ }
+ }
+ if matched {
+ return true
+ }
+ }
+ return false
+}
+
+// ValidateScriptAPIRequest enforces the bridge policy on a script-supplied
+// method and path and returns the normalized path (leading slash, optional
+// query preserved) ready to prefix with the v2 REST root.
+func ValidateScriptAPIRequest(method, path string) (string, error) {
+ method = strings.ToUpper(strings.TrimSpace(method))
+ if !actionScriptAllowedMethods[method] {
+ return "", scriptAPIPolicyErrorf("method %q is not permitted", method)
+ }
+ if path == "" || !strings.HasPrefix(path, "/") {
+ return "", scriptAPIPolicyErrorf("path must be a relative v2 path starting with /")
+ }
+ if strings.ContainsAny(path, "\\\x00\r\n\t") {
+ return "", scriptAPIPolicyErrorf("path contains control or backslash characters")
+ }
+ if strings.Contains(path, "://") {
+ return "", scriptAPIPolicyErrorf("absolute URLs are not permitted")
+ }
+ if strings.HasPrefix(path, "//") {
+ return "", scriptAPIPolicyErrorf("protocol-relative paths are not permitted")
+ }
+ parsed, err := url.Parse(path)
+ if err != nil {
+ return "", scriptAPIPolicyErrorf("path is not a valid URL reference")
+ }
+ if parsed.IsAbs() || parsed.Host != "" || parsed.Scheme != "" {
+ return "", scriptAPIPolicyErrorf("absolute URLs and alternate hosts are not permitted")
+ }
+ if parsed.Fragment != "" {
+ return "", scriptAPIPolicyErrorf("URL fragments are not permitted")
+ }
+ if parsed.RawPath != "" && parsed.RawPath != parsed.Path {
+ // A distinct escaped path is the classic encoded-traversal vector.
+ return "", scriptAPIPolicyErrorf("escaped paths are not permitted")
+ }
+ segments := strings.Split(strings.Trim(parsed.Path, "/"), "/")
+ if len(segments) == 0 || segments[0] == "" {
+ return "", scriptAPIPolicyErrorf("path must name a v2 resource")
+ }
+ for _, segment := range segments {
+ switch segment {
+ case "", ".", "..":
+ return "", scriptAPIPolicyErrorf("path traversal is not permitted")
+ }
+ }
+ resource := segments[0]
+ if resource == "rest" || resource == "api" {
+ return "", scriptAPIPolicyErrorf("path must be relative to the v2 REST root")
+ }
+ if !actionScriptAllowedResources[resource] {
+ return "", scriptAPIPolicyErrorf("resource %q is not available to scripts", resource)
+ }
+ for _, denied := range actionScriptDeniedPaths {
+ if parsed.Path == denied || strings.HasPrefix(parsed.Path, denied+"/") {
+ return "", scriptAPIPolicyErrorf("route %q is not available to scripts", parsed.Path)
+ }
+ }
+ // Mutations are restricted to the audited provenance-preserving routes;
+ // reads are not, because they cannot reset the cascade.
+ if method != http.MethodGet && method != http.MethodHead && !scriptMutationAllowed(method, segments) {
+ return "", scriptAPIPolicyErrorf("mutation route %s %q is not available to scripts", method, parsed.Path)
+ }
+ if parsed.RawQuery != "" {
+ return parsed.Path + "?" + parsed.RawQuery, nil
+ }
+ return parsed.Path, nil
+}
+
+// InProcessV2Dispatcher runs script requests through the real mounted v2
+// handler, so bearer authentication, scope checks, rate limits, and every
+// handler-level authorization decision run exactly as they do for a normal
+// API client. It never uses net/http.Client, so redirects are impossible.
+type InProcessV2Dispatcher struct {
+ handler http.Handler
+ maxResponseBytes int
+}
+
+// NewInProcessV2Dispatcher wraps the server mux. maxResponseBytes caps how much
+// of a response is buffered; zero uses the default cap.
+func NewInProcessV2Dispatcher(handler http.Handler, maxResponseBytes int) *InProcessV2Dispatcher {
+ if maxResponseBytes <= 0 {
+ maxResponseBytes = defaultScriptAPIResponseBytes
+ }
+ return &InProcessV2Dispatcher{handler: handler, maxResponseBytes: maxResponseBytes}
+}
+
+// Dispatch invokes the mounted handler for /rest/api/v2. The request
+// carries only the minted bearer token; the script cannot influence headers.
+func (d *InProcessV2Dispatcher) Dispatch(ctx context.Context, bearer string, req ScriptAPIRequest) (ScriptAPIResponse, error) {
+ if d == nil || d.handler == nil {
+ return ScriptAPIResponse{}, errors.New("script api dispatcher is not configured")
+ }
+ normalized, err := ValidateScriptAPIRequest(req.Method, req.Path)
+ if err != nil {
+ return ScriptAPIResponse{}, err
+ }
+ var body io.Reader
+ if len(req.Body) > 0 {
+ body = bytes.NewReader(req.Body)
+ }
+ httpReq, err := http.NewRequestWithContext(ctx, strings.ToUpper(req.Method), "http://action-script.internal/rest/api/v2"+normalized, body)
+ if err != nil {
+ return ScriptAPIResponse{}, fmt.Errorf("build script api request: %w", err)
+ }
+ httpReq.Header.Set("Authorization", "Bearer "+bearer)
+ httpReq.Header.Set("Accept", "application/json")
+ if len(req.Body) > 0 {
+ httpReq.Header.Set("Content-Type", "application/json")
+ }
+ recorder := newBoundedRecorder(d.maxResponseBytes)
+ d.handler.ServeHTTP(recorder, httpReq)
+ status := recorder.status
+ if status == 0 {
+ status = http.StatusOK
+ }
+ return ScriptAPIResponse{Status: status, Body: recorder.body.Bytes(), Truncated: recorder.truncated}, nil
+}
+
+// boundedRecorder captures at most limit bytes of a response and reports
+// truncation instead of buffering an unbounded body into memory.
+type boundedRecorder struct {
+ header http.Header
+ status int
+ body bytes.Buffer
+ limit int
+ truncated bool
+}
+
+func newBoundedRecorder(limit int) *boundedRecorder {
+ return &boundedRecorder{header: make(http.Header), limit: limit}
+}
+
+func (r *boundedRecorder) Header() http.Header { return r.header }
+
+func (r *boundedRecorder) WriteHeader(statusCode int) {
+ if r.status == 0 {
+ r.status = statusCode
+ }
+}
+
+func (r *boundedRecorder) Write(p []byte) (int, error) {
+ if r.status == 0 {
+ r.status = http.StatusOK
+ }
+ remaining := r.limit - r.body.Len()
+ if remaining <= 0 {
+ r.truncated = true
+ return len(p), nil
+ }
+ if len(p) > remaining {
+ _, _ = r.body.Write(p[:remaining])
+ r.truncated = true
+ return len(p), nil
+ }
+ _, _ = r.body.Write(p)
+ return len(p), nil
+}
+
+// Flush satisfies http.Flusher for handlers that stream; the bounded buffer
+// makes it a no-op.
+func (r *boundedRecorder) Flush() {}
diff --git a/internal/services/action_script_credentials.go b/internal/services/action_script_credentials.go
new file mode 100644
index 000000000..e3e7b5083
--- /dev/null
+++ b/internal/services/action_script_credentials.go
@@ -0,0 +1,103 @@
+package services
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "windshift/internal/auth"
+ "windshift/internal/models"
+)
+
+// ActionScriptTokenTTL bounds the lifetime of the temporary bearer token minted
+// for one execute_script node execution. It only needs to outlive the node's
+// runtime budget (a few seconds), so a short window keeps a leaked token's
+// value near zero even though the token is revoked in cleanup.
+const ActionScriptTokenTTL = 60 * time.Second
+
+// ActionScriptScopes is the explicit, server-owned scope allowlist for tokens
+// minted on behalf of a script executor. It deliberately omits every delete,
+// admin, action-authoring, asset, test, agent-run, and MCP scope: scripts run
+// with the executor's permissions but cannot delegate, author further
+// automations, or reach surfaces that would let them widen their own reach.
+// Scopes constrain the token, they never grant permissions the executor lacks.
+var ActionScriptScopes = []string{
+ auth.ScopeItemsRead, auth.ScopeItemsWrite,
+ auth.ScopeLinksRead, auth.ScopeLinksWrite,
+ auth.ScopeWorkspacesRead,
+ auth.ScopeUsersRead,
+ auth.ScopeStatusesRead,
+ auth.ScopeWorkflowsRead,
+ auth.ScopeItemTypesRead,
+ auth.ScopePrioritiesRead,
+ auth.ScopeCustomFieldsRead,
+ auth.ScopeMilestonesRead, auth.ScopeMilestonesWrite,
+ auth.ScopeIterationsRead, auth.ScopeIterationsWrite,
+ auth.ScopePagesRead, auth.ScopePagesWrite,
+ auth.ScopeTimeRead, auth.ScopeTimeWrite,
+ auth.ScopeApprovalsRead,
+}
+
+// ActionScriptTokenManager is the narrow slice of *auth.TokenManager the
+// execute_script executor needs. Keeping it an interface lets tests inject a
+// fake that fails closed without standing up the token cache and database.
+type ActionScriptTokenManager interface {
+ CreateToken(userID int, request models.APITokenCreate) (*models.APITokenResponse, error)
+ RevokeToken(tokenID, userID int) error
+}
+
+// ActionScriptCredential is one minted temporary credential. The raw Token
+// value must never be written to logs, execution traces, node output, or
+// persisted definitions; it lives only in the bridge closure for the duration
+// of a single node execution.
+type ActionScriptCredential struct {
+ Token string
+ TokenID int
+ ExpiresAt time.Time
+}
+
+// MintActionScriptCredential issues a short-lived temporary token for the
+// effective executor with the fixed action scope allowlist. It fails closed on
+// an unidentified or inactive user (CreateToken rejects inactive users) so a
+// script can never run as creator/admin/system.
+func MintActionScriptCredential(_ context.Context, tm ActionScriptTokenManager, actorUserID int) (*ActionScriptCredential, error) {
+ if tm == nil {
+ return nil, errors.New("action script: token manager is required")
+ }
+ if actorUserID <= 0 {
+ return nil, errors.New("action script: no effective executor identity")
+ }
+ if err := auth.ValidateScopes(ActionScriptScopes); err != nil {
+ return nil, fmt.Errorf("action script: invalid scope allowlist: %w", err)
+ }
+ expiresAt := time.Now().UTC().Add(ActionScriptTokenTTL)
+ resp, err := tm.CreateToken(actorUserID, models.APITokenCreate{
+ Name: fmt.Sprintf("action-script:%d", actorUserID),
+ Permissions: ActionScriptScopes,
+ ExpiresAt: &expiresAt,
+ IsTemporary: true,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("action script: mint executor credential: %w", err)
+ }
+ return &ActionScriptCredential{
+ Token: resp.Token,
+ TokenID: resp.APIToken.ID,
+ ExpiresAt: expiresAt,
+ }, nil
+}
+
+// RevokeActionScriptCredential removes a minted credential during node cleanup.
+// Revocation failure is returned so the executor can log it, but the token's
+// short expiry is the crash fallback: even a failed revoke cannot outlive
+// ActionScriptTokenTTL.
+func RevokeActionScriptCredential(tm ActionScriptTokenManager, cred *ActionScriptCredential, actorUserID int) error {
+ if tm == nil || cred == nil {
+ return nil
+ }
+ if err := tm.RevokeToken(cred.TokenID, actorUserID); err != nil {
+ return fmt.Errorf("action script: revoke executor credential: %w", err)
+ }
+ return nil
+}
diff --git a/internal/services/action_script_executor.go b/internal/services/action_script_executor.go
new file mode 100644
index 000000000..5a3f75be3
--- /dev/null
+++ b/internal/services/action_script_executor.go
@@ -0,0 +1,708 @@
+package services
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/grafana/sobek"
+
+ "windshift/internal/models"
+)
+
+// Budgets for one execute_script node. Source length reuses maxScriptLength
+// (10 KB) from the shared script engine. The values are server-enforced hard
+// caps; node config may narrow them but never widen them.
+const (
+ defaultScriptAPITimeoutMs = 5000
+ maxScriptAPITimeoutMs = 30000
+ maxScriptAPICalls = 50
+ defaultScriptAPIResponseBytes = 256 * 1024
+ maxScriptRequestBodyBytes = 256 * 1024
+ maxScriptResultBytes = 64 * 1024
+ maxScriptResultDepth = 20
+ maxScriptConsoleBytes = 16 * 1024
+ maxScriptConsoleEntries = 200
+ maxScriptConsoleEntryBytes = 1024
+ defaultScriptOutputVariable = "script_result"
+)
+
+// reservedScriptGlobals are names a script must not shadow: they carry the
+// host identity, the read-only context, or the bindings themselves.
+var reservedScriptGlobals = map[string]bool{
+ "windshift": true,
+ "console": true,
+ "context": true,
+ "item_id": true,
+ "workspace_id": true,
+ "actor_user_id": true,
+ "trigger_user_id": true,
+}
+
+// ActionScriptWriteMarker persists a write-ahead marker before a potentially
+// mutating script request is dispatched. If the worker dies between the commit
+// and the terminal execution-log update, the durable log then reads
+// reconciliation_required instead of running, so recovery blocks automatic
+// replay of an already-applied write.
+type ActionScriptWriteMarker interface {
+ MarkScriptWritePending(executionLogID int) error
+}
+
+// ExecuteScriptExecutor implements the execute_script node type. Each run gets
+// a fresh Sobek runtime bound to the effective action executor; REST calls go
+// through a short-lived bearer token minted for that executor and revoked in
+// cleanup.
+//
+// Trusted authors only: Sobek runs in-process and has no hard per-script heap
+// limit, so time and output budgets do not make a hostile allocation safe.
+// Restricting authorship to action managers and requiring action.set_actor for
+// executable edits of privileged actions is the current mitigation; process
+// isolation would be a prerequisite before accepting untrusted authors.
+//
+// Side effects are not transactional. A script that mutates state and then
+// fails has already committed those writes, matching every other action node.
+// Durable replay reuses the first attempt's execution log, but a crash between
+// a write and the log completion can replay the script; operators must treat
+// partial script side effects as reconciliation-required rather than assume
+// whole-script atomicity.
+type ExecuteScriptExecutor struct {
+ tokens ActionScriptTokenManager
+ dispatcher ScriptAPIDispatcher
+ marker ActionScriptWriteMarker
+ logger *slog.Logger
+}
+
+// NewExecuteScriptExecutor wires the executor with the shared token manager
+// and the canonical v2 dispatcher. Both are required; Execute fails closed when
+// either is missing.
+func NewExecuteScriptExecutor(tokens ActionScriptTokenManager, dispatcher ScriptAPIDispatcher) *ExecuteScriptExecutor {
+ return &ExecuteScriptExecutor{
+ tokens: tokens,
+ dispatcher: dispatcher,
+ logger: slog.Default(),
+ }
+}
+
+// WithWriteMarker wires the write-ahead reconciliation marker. Without one,
+// crash recovery cannot distinguish an in-flight write from an untouched
+// running execution, so mutating scripts fail closed.
+func (e *ExecuteScriptExecutor) WithWriteMarker(marker ActionScriptWriteMarker) *ExecuteScriptExecutor {
+ e.marker = marker
+ return e
+}
+
+// NodeType pins the dispatch key.
+func (e *ExecuteScriptExecutor) NodeType() models.ActionNodeType {
+ return models.ActionNodeExecuteScript
+}
+
+// scriptRun holds the mutable state of one node execution. It is created per
+// Execute call and never shared across executions, so scripts cannot observe
+// each other's state.
+type scriptRun struct {
+ vm *sobek.Runtime
+ runCtx context.Context
+ tokens ActionScriptTokenManager
+ dispatcher ScriptAPIDispatcher
+ marker ActionScriptWriteMarker
+ executionLogID int
+ actorUserID int
+ maxAPICalls int
+ apiCalls int
+ console []string
+ consoleBytes int
+ consoleCut bool
+ fatal error
+ reconciliation *bool
+ writeMarked *bool
+ cred *ActionScriptCredential
+ credOnce sync.Once
+ credErr error
+}
+
+// Execute runs the configured function body exactly once. There is no
+// execute-then-retry fallback: a retry after a runtime error could repeat host
+// side effects.
+func (e *ExecuteScriptExecutor) Execute(node *models.ActionNode, ctx *models.ExecutionContext, stepResult *models.StepResult) error {
+ if e == nil || e.tokens == nil {
+ return errors.New("execute_script: token manager is not configured")
+ }
+ if e.dispatcher == nil {
+ return errors.New("execute_script: api dispatcher is not configured")
+ }
+ if ctx == nil {
+ return errors.New("execute_script: execution context is required")
+ }
+ var config models.ExecuteScriptNodeConfig
+ if err := json.Unmarshal([]byte(node.NodeConfig), &config); err != nil {
+ return fmt.Errorf("execute_script: invalid config: %w", err)
+ }
+ source := strings.TrimSpace(config.Source)
+ if source == "" {
+ return errors.New("execute_script: source is required")
+ }
+ if len(config.Source) > maxScriptLength {
+ return fmt.Errorf("execute_script: source exceeds %d bytes", maxScriptLength)
+ }
+ outputVar := strings.TrimSpace(config.OutputVariable)
+ if outputVar == "" {
+ outputVar = defaultScriptOutputVariable
+ }
+ if err := validateScriptOutputVariable(outputVar); err != nil {
+ return err
+ }
+ if ctx.EffectiveActorID <= 0 {
+ return errors.New("execute_script: no effective executor identity; configure an actor override or trigger with an authenticated user")
+ }
+ if ctx.Variables == nil {
+ ctx.Variables = make(map[string]any)
+ }
+
+ timeoutMs := config.TimeoutMs
+ if timeoutMs <= 0 || timeoutMs > maxScriptAPITimeoutMs {
+ timeoutMs = defaultScriptAPITimeoutMs
+ }
+ maxCalls := config.MaxAPICalls
+ if maxCalls <= 0 || maxCalls > maxScriptAPICalls {
+ maxCalls = maxScriptAPICalls
+ }
+
+ wrapped := "(function() {\n" + source + "\n})()"
+ program, err := sobek.Compile("action_script", wrapped, false)
+ if err != nil {
+ return fmt.Errorf("execute_script: syntax error: %w", err)
+ }
+
+ timeoutCtx, cancel := context.WithTimeout(actionRequestContext(ctx), time.Duration(timeoutMs)*time.Millisecond)
+ defer cancel()
+
+ run := &scriptRun{
+ tokens: e.tokens,
+ dispatcher: e.dispatcher,
+ marker: e.marker,
+ executionLogID: ctx.ExecutionLogID,
+ actorUserID: ctx.EffectiveActorID,
+ maxAPICalls: maxCalls,
+ runCtx: WithActionScriptProvenance(timeoutCtx, provenanceFromExecution(ctx, node.ID)),
+ reconciliation: &ctx.ReconciliationRequired,
+ writeMarked: &ctx.ScriptWriteMarked,
+ }
+
+ vm := sobek.New()
+ run.vm = vm
+ if err := bindScriptGlobals(vm, run, ctx); err != nil {
+ return fmt.Errorf("execute_script: bind runtime: %w", err)
+ }
+
+ // Revocation is deferred so it runs even if result conversion panics. A
+ // getter evaluated while converting the return value is still script code
+ // and must not outlive the credential.
+ defer func() {
+ if run.cred == nil {
+ return
+ }
+ if revokeErr := RevokeActionScriptCredential(e.tokens, run.cred, ctx.EffectiveActorID); revokeErr != nil {
+ actionID := 0
+ if ctx.Action != nil {
+ actionID = ctx.Action.ID
+ }
+ e.logger.Warn("failed to revoke execute_script credential",
+ slog.String("component", "actions"),
+ slog.Int("action_id", actionID),
+ slog.Any("error", revokeErr),
+ )
+ }
+ }()
+
+ output, runErr := runScriptProgram(vm, program, timeoutCtx)
+
+ if run.fatal != nil {
+ return run.fatal
+ }
+ if runErr != nil {
+ var interrupted *sobek.InterruptedError
+ if errors.As(runErr, &interrupted) && interrupted.Value() == errScriptTimeout {
+ return fmt.Errorf("execute_script: timed out after %dms", timeoutMs)
+ }
+ return fmt.Errorf("execute_script: %w", runErr)
+ }
+
+ ctx.Variables[outputVar] = output
+ if stepResult.Output == nil {
+ stepResult.Output = make(map[string]any)
+ }
+ stepResult.Output[outputVar] = output
+ stepResult.Output["result"] = output
+ stepResult.Output["api_calls"] = run.apiCalls
+ stepResult.Output["console"] = run.console
+ if run.consoleCut {
+ stepResult.Output["console_truncated"] = true
+ }
+ return nil
+}
+
+// bindScriptGlobals installs the explicit, closed set of bindings a script can
+// reach. No Go service, pointer, or shared execution map is exposed.
+func bindScriptGlobals(vm *sobek.Runtime, run *scriptRun, ctx *models.ExecutionContext) error {
+ bindings := map[string]any{
+ "windshift": map[string]any{
+ "api": map[string]any{
+ "request": run.apiRequest,
+ },
+ },
+ "console": map[string]any{
+ "log": run.consoleFn("log"),
+ "info": run.consoleFn("info"),
+ "warn": run.consoleFn("warn"),
+ "error": run.consoleFn("error"),
+ "debug": run.consoleFn("debug"),
+ },
+ "context": scriptContextView(ctx),
+ }
+ for name, value := range bindings {
+ if err := vm.Set(name, value); err != nil {
+ return fmt.Errorf("set %s: %w", name, err)
+ }
+ }
+ if ctx.Event != nil {
+ if err := vm.Set("item_id", ctx.Event.ItemID); err != nil {
+ return err
+ }
+ if err := vm.Set("workspace_id", ctx.Event.WorkspaceID); err != nil {
+ return err
+ }
+ if err := vm.Set("trigger_user_id", ctx.Event.ActorUserID); err != nil {
+ return err
+ }
+ }
+ return vm.Set("actor_user_id", ctx.EffectiveActorID)
+}
+
+// scriptContextView is the read-only, detached JSON view of the execution. It
+// deliberately excludes the raw user model, item model, and event payload so
+// private trigger content cannot leak into the VM.
+func scriptContextView(ctx *models.ExecutionContext) map[string]any {
+ view := map[string]any{"actor_user_id": ctx.EffectiveActorID}
+ if ctx.Event != nil {
+ view["event_type"] = string(ctx.Event.EventType)
+ view["item_id"] = ctx.Event.ItemID
+ view["workspace_id"] = ctx.Event.WorkspaceID
+ view["trigger_user_id"] = ctx.Event.ActorUserID
+ }
+ if ctx.Item != nil {
+ view["item"] = map[string]any{
+ "id": ctx.Item.ID,
+ "key": fmt.Sprintf("%s-%d", ctx.Item.WorkspaceKey, ctx.Item.WorkspaceItemNumber),
+ "title": ctx.Item.Title,
+ "workspace_id": ctx.Item.WorkspaceID,
+ "status_id": ctx.Item.StatusID,
+ "item_type_id": ctx.Item.ItemTypeID,
+ "assignee_id": ctx.Item.AssigneeID,
+ "priority_id": ctx.Item.PriorityID,
+ }
+ }
+ return view
+}
+
+// apiRequest is the single host call exposed to scripts. It validates the
+// method and path, enforces the call budget, lazily mints the executor
+// credential, and dispatches through the canonical v2 handler. Policy
+// violations are fatal: they interrupt the VM so a try/catch cannot swallow
+// them.
+func (r *scriptRun) apiRequest(call sobek.FunctionCall) sobek.Value {
+ if r.fatal != nil {
+ return sobek.Undefined()
+ }
+ options := call.Argument(0)
+ if scriptValueMissing(options) {
+ panic(r.vm.NewTypeError("windshift.api.request(options) requires an options object"))
+ }
+ obj := options.ToObject(r.vm)
+ methodVal := scriptObjectGet(obj, "method")
+ pathVal := scriptObjectGet(obj, "path")
+ if scriptValueMissing(methodVal) || scriptValueMissing(pathVal) {
+ panic(r.vm.NewTypeError("windshift.api.request requires method and path"))
+ }
+ method := strings.TrimSpace(methodVal.String())
+ path := pathVal.String()
+
+ var body []byte
+ if bodyVal := scriptObjectGet(obj, "body"); !scriptValueMissing(bodyVal) {
+ encoded, err := json.Marshal(bodyVal.Export())
+ if err != nil {
+ panic(r.vm.NewTypeError("body must be JSON-serializable: " + err.Error()))
+ }
+ if len(encoded) > maxScriptRequestBodyBytes {
+ r.fail(scriptAPIPolicyErrorf("request body exceeds %d bytes", maxScriptRequestBodyBytes))
+ return sobek.Undefined()
+ }
+ body = encoded
+ }
+
+ r.apiCalls++
+ if r.apiCalls > r.maxAPICalls {
+ r.fail(scriptAPIPolicyErrorf("api call budget of %d exceeded", r.maxAPICalls))
+ return sobek.Undefined()
+ }
+
+ // Validate before minting or dispatching so a disallowed route fails closed
+ // without spending a credential or a network round trip.
+ if _, err := ValidateScriptAPIRequest(method, path); err != nil {
+ r.fail(err)
+ return sobek.Undefined()
+ }
+
+ // Persist the write-ahead marker and mark the execution non-replayable
+ // before a mutating dispatch. A mutating call can commit a side effect even
+ // when it returns an error or the worker dies mid-call, so replay must be
+ // blocked from this point unless the flow later completes successfully.
+ if isMutatingScriptMethod(method) {
+ if err := r.markWritePending(); err != nil {
+ r.fail(fmt.Errorf("execute_script: persist write marker: %w", err))
+ return sobek.Undefined()
+ }
+ if r.reconciliation != nil {
+ *r.reconciliation = true
+ }
+ }
+
+ cred, err := r.ensureCredential()
+ if err != nil {
+ r.fail(err)
+ return sobek.Undefined()
+ }
+
+ response, err := r.dispatcher.Dispatch(r.runCtx, cred.Token, ScriptAPIRequest{Method: method, Path: path, Body: body})
+ if err != nil {
+ var policy *ErrScriptAPIPolicy
+ if errors.As(err, &policy) {
+ r.fail(err)
+ return sobek.Undefined()
+ }
+ panic(r.vm.NewGoError(fmt.Errorf("windshift.api.request failed: %w", err)))
+ }
+ return r.responseValue(response)
+}
+
+// isMutatingScriptMethod reports whether a permitted bridge method changes
+// state. DELETE is rejected by the path policy, so it is not listed.
+func isMutatingScriptMethod(method string) bool {
+ switch strings.ToUpper(strings.TrimSpace(method)) {
+ case http.MethodPost, http.MethodPut, http.MethodPatch:
+ return true
+ default:
+ return false
+ }
+}
+
+// ensureCredential mints at most one credential per node execution, lazily so a
+// script that makes no API calls pays no token cost.
+func (r *scriptRun) ensureCredential() (*ActionScriptCredential, error) {
+ r.credOnce.Do(func() {
+ r.cred, r.credErr = MintActionScriptCredential(r.runCtx, r.tokens, r.actorUserID)
+ })
+ return r.cred, r.credErr
+}
+
+// markWritePending persists the reconciliation marker once per execution. The
+// marker is shared across every script node and iterator pass, so the second
+// mutating node in a flow reuses the first node's persisted marker instead of
+// re-updating a log that is already reconciliation_required. It is a no-op when
+// there is no durable execution log to recover.
+func (r *scriptRun) markWritePending() error {
+ if r.marker == nil || r.executionLogID <= 0 {
+ return nil
+ }
+ if r.writeMarked != nil && *r.writeMarked {
+ return nil
+ }
+ if err := r.marker.MarkScriptWritePending(r.executionLogID); err != nil {
+ return err
+ }
+ if r.writeMarked != nil {
+ *r.writeMarked = true
+ }
+ return nil
+}
+
+// fail records the first fatal policy error and interrupts the VM. Interrupts
+// are uncatchable, so an authorization or budget violation cannot be turned
+// into a successful step.
+func (r *scriptRun) fail(err error) {
+ if r.fatal == nil {
+ r.fatal = err
+ }
+ r.vm.Interrupt(err)
+}
+
+// responseValue converts a bounded API response into a detached JS object.
+func (r *scriptRun) responseValue(response ScriptAPIResponse) sobek.Value {
+ result := r.vm.NewObject()
+ _ = result.Set("status", response.Status)
+ _ = result.Set("ok", response.Status >= 200 && response.Status < 300)
+ _ = result.Set("truncated", response.Truncated)
+ var decoded any
+ if len(response.Body) > 0 && json.Unmarshal(response.Body, &decoded) == nil {
+ _ = result.Set("body", decoded)
+ } else {
+ _ = result.Set("body", string(response.Body))
+ }
+ return result
+}
+
+// consoleFn returns a bounded console sink. Output is truncated rather than
+// dropped silently once the byte budget is exhausted.
+func (r *scriptRun) consoleFn(level string) func(sobek.FunctionCall) sobek.Value {
+ return func(call sobek.FunctionCall) sobek.Value {
+ parts := make([]string, 0, len(call.Arguments))
+ for _, arg := range call.Arguments {
+ parts = append(parts, scriptValueString(arg))
+ }
+ r.appendConsole(level + ": " + strings.Join(parts, " "))
+ return sobek.Undefined()
+ }
+}
+
+func (r *scriptRun) appendConsole(line string) {
+ if len(line) > maxScriptConsoleEntryBytes {
+ line = line[:maxScriptConsoleEntryBytes] + "…[truncated]"
+ }
+ if len(r.console) >= maxScriptConsoleEntries || r.consoleBytes+len(line) > maxScriptConsoleBytes {
+ r.consoleCut = true
+ return
+ }
+ r.console = append(r.console, line)
+ r.consoleBytes += len(line)
+}
+
+// scriptValueString renders a console argument as bounded text. Objects are
+// JSON-encoded so a log line is useful without exposing Go representations.
+func scriptValueString(value sobek.Value) string {
+ if value == nil {
+ return "undefined"
+ }
+ exported := value.Export()
+ if s, ok := exported.(string); ok {
+ return s
+ }
+ if encoded, err := json.Marshal(exported); err == nil {
+ return string(encoded)
+ }
+ return value.String()
+}
+
+// runScriptProgram executes the compiled program and converts its return value
+// while the watchdog is still armed. Returned getters are evaluated by sobek's
+// export, so conversion is script execution too: it must stay inside the
+// timeout budget and inside the credential window.
+func runScriptProgram(vm *sobek.Runtime, program *sobek.Program, timeoutCtx context.Context) (output any, err error) {
+ done := make(chan struct{})
+ exited := make(chan struct{})
+ go func() {
+ defer close(exited)
+ select {
+ case <-timeoutCtx.Done():
+ vm.Interrupt(errScriptTimeout)
+ case <-done:
+ }
+ }()
+ defer func() {
+ // Convert panics and runtime errors to inert Go text while the watchdog
+ // is still armed: formatting a Sobek exception can invoke a script
+ // toString, which is itself script code and must stay under the budget.
+ if r := recover(); r != nil {
+ err = inertScriptPanic(r)
+ }
+ close(done)
+ <-exited
+ }()
+ result, runErr := vm.RunProgram(program)
+ if runErr != nil {
+ return nil, inertScriptError(runErr)
+ }
+ return strictScriptOutput(result)
+}
+
+// maxScriptErrorBytes bounds the inert error text a script can influence.
+const maxScriptErrorBytes = 1024
+
+// inertScriptError converts a runtime error to a plain Go error without
+// retaining any script-backed value whose later formatting could evaluate
+// script code. It must be called while the watchdog is armed.
+func inertScriptError(runErr error) (err error) {
+ var interrupted *sobek.InterruptedError
+ if errors.As(runErr, &interrupted) {
+ return interrupted
+ }
+ defer func() {
+ if r := recover(); r != nil {
+ if ie, ok := r.(*sobek.InterruptedError); ok {
+ err = ie
+ return
+ }
+ err = errors.New("script execution error")
+ }
+ }()
+ return errors.New(boundedScriptText(runErr.Error()))
+}
+
+// inertScriptPanic converts a recovered panic value to a plain Go error. It
+// must be called while the watchdog is armed.
+func inertScriptPanic(recovered any) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ if ie, ok := r.(*sobek.InterruptedError); ok {
+ err = ie
+ return
+ }
+ err = errors.New("script result conversion failed")
+ }
+ }()
+ switch value := recovered.(type) {
+ case *sobek.InterruptedError:
+ return value
+ case *sobek.Object:
+ return errors.New(boundedScriptText(value.String()))
+ case error:
+ return errors.New(boundedScriptText(value.Error()))
+ default:
+ return fmt.Errorf("script result conversion failed: %v", value)
+ }
+}
+
+func boundedScriptText(text string) string {
+ if len(text) > maxScriptErrorBytes {
+ return text[:maxScriptErrorBytes] + "…[truncated]"
+ }
+ return text
+}
+
+// strictScriptOutput converts a script's return value into detached JSON,
+// rejecting promises, functions, and other unsupported values. Depth and size
+// are bounded so a hostile result cannot exhaust memory or blow the trace.
+func strictScriptOutput(result sobek.Value) (any, error) {
+ if scriptValueMissing(result) {
+ return nil, nil
+ }
+ exported := result.Export()
+ if _, ok := exported.(*sobek.Promise); ok {
+ return nil, errors.New("result is a Promise; asynchronous scripts are not supported")
+ }
+ safe, err := toJSONValue(exported, 0)
+ if err != nil {
+ return nil, err
+ }
+ encoded, err := json.Marshal(safe)
+ if err != nil {
+ return nil, fmt.Errorf("result is not JSON-serializable: %w", err)
+ }
+ if len(encoded) > maxScriptResultBytes {
+ return nil, fmt.Errorf("result exceeds %d bytes", maxScriptResultBytes)
+ }
+ var detached any
+ if err := json.Unmarshal(encoded, &detached); err != nil {
+ return nil, fmt.Errorf("result is not valid JSON: %w", err)
+ }
+ return detached, nil
+}
+
+func toJSONValue(value any, depth int) (any, error) {
+ if depth > maxScriptResultDepth {
+ return nil, fmt.Errorf("result exceeds maximum depth of %d", maxScriptResultDepth)
+ }
+ switch v := value.(type) {
+ case nil, bool, string, int, int64, float64, json.Number:
+ return v, nil
+ case []any:
+ out := make([]any, len(v))
+ for i, item := range v {
+ converted, err := toJSONValue(item, depth+1)
+ if err != nil {
+ return nil, err
+ }
+ out[i] = converted
+ }
+ return out, nil
+ case map[string]any:
+ out := make(map[string]any, len(v))
+ for key, item := range v {
+ converted, err := toJSONValue(item, depth+1)
+ if err != nil {
+ return nil, err
+ }
+ out[key] = converted
+ }
+ return out, nil
+ default:
+ return nil, fmt.Errorf("result contains unsupported value of type %T", value)
+ }
+}
+
+// scriptValueMissing treats a nil sobek.Value as missing. sobek's Object.Get
+// returns a nil interface for an absent property, which the IsUndefined /
+// IsNull predicates do not catch.
+func scriptValueMissing(value sobek.Value) bool {
+ return value == nil || sobek.IsUndefined(value) || sobek.IsNull(value)
+}
+
+// scriptObjectGet reads a property and normalizes an absent property to
+// undefined so callers never call methods on a nil value.
+func scriptObjectGet(obj *sobek.Object, name string) sobek.Value {
+ value := obj.Get(name)
+ if value == nil {
+ return sobek.Undefined()
+ }
+ return value
+}
+
+// validateScriptOutputVariable rejects names that would shadow host bindings or
+// that are not simple identifiers.
+func validateScriptOutputVariable(name string) error {
+ if len(name) > 64 {
+ return errors.New("execute_script: output_variable is too long")
+ }
+ if !isScriptIdentifier(name) {
+ return fmt.Errorf("execute_script: output_variable %q is not a valid identifier", name)
+ }
+ if reservedScriptGlobals[name] {
+ return fmt.Errorf("execute_script: output_variable %q is reserved", name)
+ }
+ return nil
+}
+
+func isScriptIdentifier(name string) bool {
+ if name == "" {
+ return false
+ }
+ for i, r := range name {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r == '_':
+ case i > 0 && r >= '0' && r <= '9':
+ default:
+ return false
+ }
+ }
+ return true
+}
+
+// ValidateScriptSourceSyntax compiles a function-body script without running
+// it. Save-time validation uses this so a stored definition never contains
+// code that cannot be compiled.
+func ValidateScriptSourceSyntax(source string) error {
+ if strings.TrimSpace(source) == "" {
+ return errors.New("source is required")
+ }
+ if len(source) > maxScriptLength {
+ return fmt.Errorf("source exceeds %d bytes", maxScriptLength)
+ }
+ if _, err := sobek.Compile("action_script", "(function() {\n"+source+"\n})()", false); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/internal/services/action_script_provenance.go b/internal/services/action_script_provenance.go
new file mode 100644
index 000000000..934faafed
--- /dev/null
+++ b/internal/services/action_script_provenance.go
@@ -0,0 +1,81 @@
+package services
+
+import (
+ "context"
+
+ "windshift/internal/models"
+)
+
+// ActionScriptProvenance carries the trusted automation context for REST calls
+// a script makes. The execute_script bridge stamps it on the in-process request
+// so the domain services that emit action events keep the same cascade depth,
+// execution chain, and private-trigger provenance as the node that caused them.
+// It is server-side metadata: scripts cannot set, read, or override it, and it
+// is what keeps a script-driven mutation from resetting the cascade depth to
+// zero and looping forever.
+type ActionScriptProvenance struct {
+ ActionID int
+ ExecutionLogID int
+ NodeID int
+ DefinitionRevisionID *int
+ ExecutionChainID string
+ CascadeDepth int
+ TriggerCommentIsPrivate bool
+ SourceApplication string
+}
+
+type actionScriptProvenanceKey struct{}
+
+// WithActionScriptProvenance attaches trusted provenance to a request context.
+func WithActionScriptProvenance(ctx context.Context, p ActionScriptProvenance) context.Context {
+ return context.WithValue(ctx, actionScriptProvenanceKey{}, p)
+}
+
+// ActionScriptProvenanceFrom returns the trusted provenance, if the request
+// originated from an execute_script node.
+func ActionScriptProvenanceFrom(ctx context.Context) (ActionScriptProvenance, bool) {
+ if ctx == nil {
+ return ActionScriptProvenance{}, false
+ }
+ p, ok := ctx.Value(actionScriptProvenanceKey{}).(ActionScriptProvenance)
+ return p, ok
+}
+
+// ActionContext renders the provenance as the cascade context the domain
+// services already understand, so script side effects stay inside the action
+// cascade budget instead of looking like a fresh user action.
+func (p ActionScriptProvenance) ActionContext() ActionContext {
+ source := p.SourceApplication
+ if source == "" {
+ source = "automation"
+ }
+ return ActionContext{
+ TriggeredByAction: true,
+ ExecutionChainID: p.ExecutionChainID,
+ CascadeDepth: p.CascadeDepth,
+ SourceApplication: source,
+ TriggerCommentIsPrivate: p.TriggerCommentIsPrivate,
+ }
+}
+
+// provenanceFromExecution builds the provenance for a node in the given
+// execution. The script's REST calls are one cascade step below the trigger
+// that started the action, matching how in-process node mutations are stamped.
+func provenanceFromExecution(ctx *models.ExecutionContext, nodeID int) ActionScriptProvenance {
+ p := ActionScriptProvenance{NodeID: nodeID}
+ if ctx == nil {
+ return p
+ }
+ if ctx.Action != nil {
+ p.ActionID = ctx.Action.ID
+ }
+ p.ExecutionLogID = ctx.ExecutionLogID
+ p.DefinitionRevisionID = ctx.DefinitionRevisionID
+ p.ExecutionChainID = ctx.ChainID
+ p.TriggerCommentIsPrivate = ctx.TriggerCommentIsPrivate
+ p.SourceApplication = "automation"
+ if ctx.Event != nil {
+ p.CascadeDepth = ctx.Event.CascadeDepth + 1
+ }
+ return p
+}
diff --git a/internal/services/action_service.go b/internal/services/action_service.go
index a8347d902..ecec6d0dc 100644
--- a/internal/services/action_service.go
+++ b/internal/services/action_service.go
@@ -47,6 +47,11 @@ type AssetSetPermissionChecker interface {
// contains the actionable failure details.
var ErrActionCompletedWithFailedSteps = errors.New("action completed with failed steps")
+// ErrActionReconciliationRequired means execution committed a partial side
+// effect (an execute_script write) and then failed. Durable replay must not
+// rerun the flow; an operator reconciles the committed write.
+var ErrActionReconciliationRequired = errors.New("action execution requires reconciliation")
+
// ActionServiceConfig represents configuration for the action service
type ActionServiceConfig struct {
RefreshInterval time.Duration // How often to refresh action cache
@@ -252,6 +257,16 @@ func (as *ActionService) EmitActionEventInTx(ctx context.Context, tx database.Tx
return as.durableIngress.EmitInTx(ctx, tx, event)
}
+// MarkScriptWritePending implements ActionScriptWriteMarker. It persists the
+// write-ahead reconciliation marker on the execution log before a mutating
+// script call is dispatched, so a crash after the commit is not replayed.
+func (as *ActionService) MarkScriptWritePending(executionLogID int) error {
+ if executionLogID <= 0 {
+ return nil
+ }
+ return as.repo.MarkExecutionReconciliationRequired(executionLogID)
+}
+
// Stop gracefully shuts down the action service
func (as *ActionService) Stop() {
close(as.stopChan)
@@ -661,7 +676,7 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
if durableEventKey != "" {
existing, loadErr := as.repo.GetExecutionLogByDurableTarget(durableEventKey, action.ID)
if loadErr == nil {
- if existing.Status == models.ActionStatusCompleted {
+ if existing.Status == models.ActionStatusCompleted || existing.Status == models.ActionStatusReconciliationRequired {
return nil
}
log.ID = existing.ID
@@ -712,14 +727,16 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
}
ctx := &models.ExecutionContext{
- Context: executionCtx,
- DurableEventKey: durableEventKey,
- Action: action,
- Event: event,
- EffectiveActorID: effectiveActorID,
- Variables: make(map[string]any),
- StepResults: []models.StepResult{},
- ChainID: chainID,
+ Context: executionCtx,
+ DurableEventKey: durableEventKey,
+ Action: action,
+ Event: event,
+ EffectiveActorID: effectiveActorID,
+ Variables: make(map[string]any),
+ StepResults: []models.StepResult{},
+ ChainID: chainID,
+ ExecutionLogID: log.ID,
+ DefinitionRevisionID: log.DefinitionRevisionID,
}
// Expose the effective actor to template expansion.
@@ -784,6 +801,12 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
as.cleanupActionContainers(ctx.StepResults)
log.Status = models.ActionStatusFailed
log.ErrorMessage = err.Error()
+ if ctx.ReconciliationRequired {
+ // A script already committed a write; rerunning the flow would
+ // repeat it, so block durable replay and surface reconciliation.
+ log.Status = models.ActionStatusReconciliationRequired
+ log.ErrorMessage = "requires reconciliation: " + err.Error()
+ }
log.CompletedAt = &completedAt
if trace, marshalErr := json.Marshal(ctx.StepResults); marshalErr == nil {
log.ExecutionTrace = string(trace)
@@ -791,6 +814,9 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
if logErr := as.repo.UpdateExecutionLog(log); logErr != nil {
slog.Error("failed to cancel action execution log", slog.Any("error", logErr), slog.Int("action_id", action.ID))
}
+ if log.Status == models.ActionStatusReconciliationRequired {
+ return fmt.Errorf("%w: %w: action %d", ErrActionCompletedWithFailedSteps, ErrActionReconciliationRequired, action.ID)
+ }
return err
}
if run.BudgetExceeded {
@@ -814,6 +840,14 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
break
}
}
+ if log.Status == models.ActionStatusFailed && ctx.ReconciliationRequired {
+ // A script committed a write before a later step failed: the trace is
+ // final, but durable replay must not repeat the committed write.
+ log.Status = models.ActionStatusReconciliationRequired
+ if log.ErrorMessage == "" {
+ log.ErrorMessage = "requires reconciliation: a script step committed a write before the action failed"
+ }
+ }
if trace, err := json.Marshal(ctx.StepResults); err == nil {
log.ExecutionTrace = string(trace)
@@ -847,6 +881,9 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
if log.Status == models.ActionStatusFailed {
return fmt.Errorf("%w: action %d", ErrActionCompletedWithFailedSteps, action.ID)
}
+ if log.Status == models.ActionStatusReconciliationRequired {
+ return fmt.Errorf("%w: %w: action %d", ErrActionCompletedWithFailedSteps, ErrActionReconciliationRequired, action.ID)
+ }
return nil
}
diff --git a/internal/services/actioncatalog/catalog.go b/internal/services/actioncatalog/catalog.go
index ed38fada3..06e289886 100644
--- a/internal/services/actioncatalog/catalog.go
+++ b/internal/services/actioncatalog/catalog.go
@@ -354,6 +354,14 @@ func Build() (*Catalog, error) {
}); err != nil {
return nil, err
}
+ if err := registerNode[models.ExecuteScriptNodeConfig](c, nodeSpec{
+ Type: models.ActionNodeExecuteScript,
+ Label: "Run script",
+ Description: "Run a JavaScript function body with the effective executor's identity. The script can call the v2 REST API through a server-minted, short-lived token; the return value is stored in the configured output variable.",
+ Category: CategoryIntegration,
+ }); err != nil {
+ return nil, err
+ }
// Drift detector: every ActionNodeType constant must be registered.
// AllActionNodeTypes is the authoritative list (kept next to the
@@ -502,6 +510,7 @@ var AllActionNodeTypes = []models.ActionNodeType{
models.ActionNodeTransitionItem,
models.ActionNodeRelatedItems,
models.ActionNodeCreateMilestone,
+ models.ActionNodeExecuteScript,
}
// AllActionTriggerTypes is the trigger counterpart of AllActionNodeTypes.
diff --git a/internal/services/actioncatalog/validate.go b/internal/services/actioncatalog/validate.go
index 42e5caa39..c2c47996e 100644
--- a/internal/services/actioncatalog/validate.go
+++ b/internal/services/actioncatalog/validate.go
@@ -8,11 +8,16 @@ import (
"strings"
"github.com/google/jsonschema-go/jsonschema"
+ "github.com/grafana/sobek"
"windshift/internal/models"
"windshift/internal/repository/actionutil"
)
+// maxExecuteScriptSourceBytes mirrors the executor's 10 KB source cap so a
+// definition that validates is also one the runtime will accept.
+const maxExecuteScriptSourceBytes = 10240
+
// ValidationError is one structured grievance against an action definition.
// Code is a short machine-readable tag clients can switch on; Path points at
// the offending element (`trigger`, `nodes[2].node_config.field_name`,
@@ -444,9 +449,40 @@ func validateNodeConfigValues(n models.ActionNode) (msg, field string) {
}
}
}
+ // Script source is validated for syntax only; saving never executes it and
+ // never makes a live API call.
+ if n.NodeType == models.ActionNodeExecuteScript {
+ var cfg models.ExecuteScriptNodeConfig
+ if err := json.Unmarshal([]byte(n.NodeConfig), &cfg); err == nil {
+ if strings.TrimSpace(cfg.Source) == "" {
+ return "source is required", "source"
+ }
+ if len(cfg.Source) > maxExecuteScriptSourceBytes {
+ return fmt.Sprintf("source exceeds %d bytes", maxExecuteScriptSourceBytes), "source"
+ }
+ if _, err := sobek.Compile("action_script", "(function() {\n"+cfg.Source+"\n})()", false); err != nil {
+ return fmt.Sprintf("source has a syntax error: %v", err), "source"
+ }
+ if cfg.OutputVariable != "" && !isScriptIdentifier(cfg.OutputVariable) {
+ return fmt.Sprintf("output_variable %q is not a valid identifier", cfg.OutputVariable), "output_variable"
+ }
+ }
+ }
return "", ""
}
+func isScriptIdentifier(name string) bool {
+ for i, r := range name {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r == '_':
+ case i > 0 && r >= '0' && r <= '9':
+ default:
+ return false
+ }
+ }
+ return name != ""
+}
+
func nodeCapabilityAvailable(caps CapabilityResolver, workspaceID, capabilityID int, nodeType models.ActionNodeType) bool {
if typed, ok := caps.(typedCapabilityResolver); ok {
switch nodeType {
diff --git a/internal/services/comment_service.go b/internal/services/comment_service.go
index 2900f2978..d51b76469 100644
--- a/internal/services/comment_service.go
+++ b/internal/services/comment_service.go
@@ -510,6 +510,17 @@ func (s *CommentService) create(ctx context.Context, params CreateCommentParams)
if err := ctx.Err(); err != nil {
return nil, err
}
+ // Script-driven comments carry trusted automation provenance. A private
+ // trigger must not produce a public comment, and an automation-authored
+ // comment must not re-enter the comment_created trigger.
+ var scriptProvenance *ActionScriptProvenance
+ if prov, ok := ActionScriptProvenanceFrom(ctx); ok {
+ scriptProvenance = &prov
+ if prov.TriggerCommentIsPrivate {
+ params.IsPrivate = true
+ }
+ params.SuppressActionEvents = true
+ }
// 2. Get item details for notifications and the webhook payload
item, err := repository.NewItemRepository(s.db).FindByIDWithDetails(params.ItemID)
if err != nil {
@@ -579,6 +590,17 @@ func (s *CommentService) create(ctx context.Context, params CreateCommentParams)
}
fallback.OccurredAt = now
metadata := mergeItemEventMetadata(params.EventMetadata, fallback)
+ if scriptProvenance != nil {
+ ac := scriptProvenance.ActionContext()
+ metadata.SourceKind = "automation"
+ metadata.CorrelationID = ac.ExecutionChainID
+ metadata.Automation = &itemevents.AutomationContext{
+ TriggeredByAction: ac.TriggeredByAction,
+ ExecutionChainID: ac.ExecutionChainID,
+ CascadeDepth: ac.CascadeDepth,
+ SourceApplication: ac.SourceApplication,
+ }
+ }
// Imported comments are historical. They keep the canonical fact and the
// support first-response metric, but must not drive live operational side
// effects such as per-comment audit entries or presence tracking.
@@ -745,7 +767,7 @@ func (s *CommentService) create(ctx context.Context, params CreateCommentParams)
// its siblings, which is the one unbounded helpdesk loop (WI-1142).
if s.actionEvents != nil && !params.SuppressActionEvents {
fromCustomer := params.PortalCustomerID != nil
- s.actionEvents.EmitActionEvent(&models.ActionEvent{
+ event := &models.ActionEvent{
EventType: models.ActionTriggerCommentCreated,
WorkspaceID: item.WorkspaceID,
ItemID: params.ItemID,
@@ -756,7 +778,16 @@ func (s *CommentService) create(ctx context.Context, params CreateCommentParams)
"comment_is_private": params.IsPrivate,
"comment_from_customer": fromCustomer,
},
- })
+ }
+ if scriptProvenance != nil {
+ ac := scriptProvenance.ActionContext()
+ event.TriggeredByAction = ac.TriggeredByAction
+ event.ExecutionChainID = ac.ExecutionChainID
+ event.CascadeDepth = ac.CascadeDepth
+ event.SourceApplication = ac.SourceApplication
+ event.TriggerCommentIsPrivate = ac.TriggerCommentIsPrivate
+ }
+ s.actionEvents.EmitActionEvent(event)
}
// Fresh comment activity re-arms item_inactive triggers for the item.
if s.inactivityMarks != nil {
diff --git a/internal/services/durable_action_consumer.go b/internal/services/durable_action_consumer.go
index 383460460..668f5f893 100644
--- a/internal/services/durable_action_consumer.go
+++ b/internal/services/durable_action_consumer.go
@@ -195,7 +195,7 @@ func (c *DurableActionConsumer) Handle(ctx context.Context, event events.Event)
return actionevents.Callbacks{
Completed: func(actionID int) (bool, error) {
existing, err := c.actions.repo.GetExecutionLogByDurableTarget(event.Key, actionID)
- return err == nil && existing.Status == models.ActionStatusCompleted, err
+ return err == nil && (existing.Status == models.ActionStatusCompleted || existing.Status == models.ActionStatusReconciliationRequired), err
},
Execute: func(actionID int) (bool, error) {
action, err := c.actions.repo.GetByID(actionID)
@@ -203,6 +203,12 @@ func (c *DurableActionConsumer) Handle(ctx context.Context, event events.Event)
return errors.Is(err, sql.ErrNoRows), fmt.Errorf("load frozen action %d: %w", actionID, err)
}
if err := c.actions.executeActionForEvent(ctx, action, actionEvent, nil, event.Key); err != nil {
+ // A reconciliation-required failure already committed a partial
+ // write, so automatic replay would repeat it. Report it as
+ // permanent so the event is not redelivered.
+ if errors.Is(err, ErrActionReconciliationRequired) {
+ return true, fmt.Errorf("execute frozen action %d: %w", actionID, err)
+ }
return false, fmt.Errorf("execute frozen action %d: %w", actionID, err)
}
return false, nil
diff --git a/internal/services/event_coordinator.go b/internal/services/event_coordinator.go
index e14576a88..d2738d519 100644
--- a/internal/services/event_coordinator.go
+++ b/internal/services/event_coordinator.go
@@ -250,6 +250,17 @@ func (ec *EventCoordinator) EmitItemDeleted(item *models.Item, actorUserID, desc
// EmitStatusChanged emits events specifically for status changes.
func (ec *EventCoordinator) EmitStatusChanged(item *models.Item, oldStatusID, newStatusID *int, actorUserID int, actorUsername ...string) {
+ ec.emitStatusChanged(item, oldStatusID, newStatusID, actorUserID, nil, actorUsername...)
+}
+
+// EmitStatusChangedWithContext preserves automation cascade provenance for a
+// status change caused by an execute_script REST call, so a script-driven
+// transition stays inside the action cascade budget.
+func (ec *EventCoordinator) EmitStatusChangedWithContext(item *models.Item, oldStatusID, newStatusID *int, actorUserID int, actionContext ActionContext, actorUsername ...string) {
+ ec.emitStatusChanged(item, oldStatusID, newStatusID, actorUserID, &actionContext, actorUsername...)
+}
+
+func (ec *EventCoordinator) emitStatusChanged(item *models.Item, oldStatusID, newStatusID *int, actorUserID int, actionContext *ActionContext, actorUsername ...string) {
actorName := resolveActorName(actorUserID, actorUsername)
var newStatusName string
if newStatusID != nil {
@@ -285,7 +296,7 @@ func (ec *EventCoordinator) EmitStatusChanged(item *models.Item, oldStatusID, ne
if oldStatusID != nil && newStatusID != nil && *oldStatusID == *newStatusID {
eventType = models.ActionTriggerStatusLoop
}
- ec.actionService.EmitActionEvent(&models.ActionEvent{
+ event := &models.ActionEvent{
EventType: eventType,
WorkspaceID: item.WorkspaceID,
ItemID: item.ID,
@@ -301,7 +312,9 @@ func (ec *EventCoordinator) EmitStatusChanged(item *models.Item, oldStatusID, ne
"team_id": item.TeamID,
"creator_id": item.CreatorID,
},
- })
+ }
+ applyActionContext(event, actionContext)
+ ec.actionService.EmitActionEvent(event)
}
// Dispatch webhook event
diff --git a/internal/services/item_application_service.go b/internal/services/item_application_service.go
index ee9e2d965..962c44e69 100644
--- a/internal/services/item_application_service.go
+++ b/internal/services/item_application_service.go
@@ -864,7 +864,7 @@ func (s *ItemApplicationService) Create(ctx context.Context, actor AuditActor, i
if err := s.require(actor.UserID, input.WorkspaceID, models.PermissionItemCreate); err != nil {
return nil, err
}
- result, err := s.create.Create(actor.UserID, actor.Username, input)
+ result, err := s.createItem(ctx, actor, input)
if err != nil {
return nil, err
}
@@ -887,7 +887,7 @@ func (s *ItemApplicationService) Patch(ctx context.Context, actor AuditActor, it
if !allowed {
return nil, ErrItemForbidden
}
- result, err := s.update.UpdateJSONFields(actor.UserID, actor.Username, itemID, fields)
+ result, err := s.patchItem(ctx, actor, itemID, fields)
if err != nil {
return nil, err
}
@@ -902,6 +902,23 @@ func (s *ItemApplicationService) Patch(ctx context.Context, actor AuditActor, it
return &items[0], nil
}
+// createItem preserves execute_script cascade provenance when the call arrived
+// through the script REST bridge, so a script-created item stays inside the
+// action cascade budget instead of looking like a fresh user action.
+func (s *ItemApplicationService) createItem(ctx context.Context, actor AuditActor, input ItemCreateInput) (*ItemCreateResult, error) {
+ if prov, ok := ActionScriptProvenanceFrom(ctx); ok {
+ return s.create.CreateWithContext(actor.UserID, actor.Username, input, prov.ActionContext())
+ }
+ return s.create.Create(actor.UserID, actor.Username, input)
+}
+
+func (s *ItemApplicationService) patchItem(ctx context.Context, actor AuditActor, itemID int, fields map[string]json.RawMessage) (*UpdateItemResult, error) {
+ if prov, ok := ActionScriptProvenanceFrom(ctx); ok {
+ return s.update.UpdateJSONFieldsWithContext(actor.UserID, actor.Username, itemID, fields, prov.ActionContext())
+ }
+ return s.update.UpdateJSONFields(actor.UserID, actor.Username, itemID, fields)
+}
+
func (s *ItemApplicationService) Delete(actor AuditActor, itemID int) error {
result, err := s.delete.Delete(ItemDeletionRequest{
ItemID: itemID, ActorUserID: actor.UserID, ActorUsername: actor.Username, Mode: ItemDeletionSingle,
@@ -1179,10 +1196,14 @@ func (s *ItemApplicationService) transitionItem(ctx context.Context, actor Audit
return nil, err
}
if (!result.NoOp || result.Loop) && s.events != nil {
- s.events.EmitStatusChanged(result.Item, result.OldStatusID, result.NewStatusID, actor.UserID, actor.Username)
+ if prov, ok := ActionScriptProvenanceFrom(ctx); ok {
+ s.events.EmitStatusChangedWithContext(result.Item, result.OldStatusID, result.NewStatusID, actor.UserID, prov.ActionContext(), actor.Username)
+ } else {
+ s.events.EmitStatusChanged(result.Item, result.OldStatusID, result.NewStatusID, actor.UserID, actor.Username)
+ }
}
s.syncStatus(ctx, result.Item.ID, result.NewStatusID, result.NoOp)
- s.recordTransitionComment(itemID, actor.UserID, fields)
+ s.recordTransitionComment(ctx, itemID, actor.UserID, fields)
return &ItemTransitionResult{
Item: result.Item, OldStatusID: result.OldStatusID, NewStatusID: result.NewStatusID, NoOp: result.NoOp,
}, nil
@@ -1226,9 +1247,11 @@ func (s *ItemApplicationService) applyTransitionLabels(ctx context.Context, tx d
}
// recordTransitionComment persists the optional comment collected by a
-// transition screen. The move already committed, so a comment failure is
-// logged rather than reported as a failed transition.
-func (s *ItemApplicationService) recordTransitionComment(itemID, authorID int, fields map[string]any) {
+// transition screen. It forwards the request context so script provenance
+// (private-trigger protection and comment-trigger suppression) reaches the
+// comment service. The move already committed, so a comment failure is logged
+// rather than reported as a failed transition.
+func (s *ItemApplicationService) recordTransitionComment(ctx context.Context, itemID, authorID int, fields map[string]any) {
if s.comments == nil {
return
}
@@ -1236,7 +1259,7 @@ func (s *ItemApplicationService) recordTransitionComment(itemID, authorID int, f
if !ok || strings.TrimSpace(content) == "" {
return
}
- if _, err := s.comments.Create(CreateCommentParams{
+ if _, err := s.comments.CreateContext(ctx, CreateCommentParams{
ItemID: itemID, AuthorID: authorID, ActorUserID: authorID, Content: content,
}); err != nil {
slog.Error("failed to persist transition comment",
diff --git a/internal/services/item_update_application_service.go b/internal/services/item_update_application_service.go
index 2aa422e59..fce7de2ad 100644
--- a/internal/services/item_update_application_service.go
+++ b/internal/services/item_update_application_service.go
@@ -114,6 +114,16 @@ func (s *ItemUpdateApplicationService) CanUserEditItem(userID, itemID int) (bool
// presence/null distinction here means every HTTP surface uses the same
// coercion rules before reaching the transactional update service.
func (s *ItemUpdateApplicationService) UpdateJSONFields(actorUserID int, actorUsername string, itemID int, fields map[string]json.RawMessage) (*UpdateItemResult, error) {
+ return s.updateJSONFields(actorUserID, actorUsername, itemID, fields, nil)
+}
+
+// UpdateJSONFieldsWithContext applies the same patch format while preserving
+// the automation chain that caused the mutation (execute_script REST calls).
+func (s *ItemUpdateApplicationService) UpdateJSONFieldsWithContext(actorUserID int, actorUsername string, itemID int, fields map[string]json.RawMessage, actionContext ActionContext) (*UpdateItemResult, error) {
+ return s.updateJSONFields(actorUserID, actorUsername, itemID, fields, &actionContext)
+}
+
+func (s *ItemUpdateApplicationService) updateJSONFields(actorUserID int, actorUsername string, itemID int, fields map[string]json.RawMessage, actionContext *ActionContext) (*UpdateItemResult, error) {
if _, ok := fields["status_id"]; ok {
return nil, &validation.ValidationError{
Field: "status_id",
@@ -125,7 +135,7 @@ func (s *ItemUpdateApplicationService) UpdateJSONFields(actorUserID int, actorUs
if err != nil {
return nil, err
}
- return s.Update(actorUserID, actorUsername, itemID, updateData)
+ return s.updateItem(actorUserID, actorUsername, itemID, updateData, actionContext)
}
func itemUpdateData(fields map[string]json.RawMessage) (map[string]any, error) {