Files
pad/internal/items/validate.go
T
xarmian c38b3bf5cd feat(playbooks): add invocation_slug + arguments schema fields (TASK-1378) (#517)
* feat(playbooks): add invocation_slug + arguments schema fields (TASK-1378)

Foundational change for PLAN-1377 — playbooks become first-class invokable
procedures. Two new optional fields land on the Playbooks collection
schema:

- `invocation_slug` (text, kebab-case, unique-per-workspace among non-null
  values): enables `/pad <slug>` direct invocation. Nullable so
  trigger-only playbooks (e.g. on-release checklists) don't need one.
- `arguments` (json, array of {name, type, required, default, description}):
  declares the playbook's argument contract; mirrors the body's
  `## Arguments` section in queryable form.

Plumbing pieces:

- `models.FieldDef` grows two general-purpose options — `Pattern` for
  regex validation and `UniqueScope` for collection-level uniqueness.
  Both are opt-in; existing schemas are unaffected.
- `items.ValidateFields` learns the `json` field type (accepts any
  JSON-decodable value) and applies `Pattern` to string-typed values.
- `handlers_items.checkUniqueFields` queries `Store.ListItems` to enforce
  `UniqueScope == "workspace_collection"` on create + update.
- Two migrations (SQLite 054, Postgres 033) JSON-patch the playbooks
  schema on existing workspaces so the new fields show up without a
  workspace re-init.
- TypeScript `FieldDef` mirrors the Go side.

Parent: PLAN-1377.

* fix(playbooks): address Codex review round 1 findings (TASK-1378)

P1 — EditCollectionModal now round-trips opaque pattern/unique_scope
metadata. EditableField carries the new keys; the load + save paths
preserve them so re-saving the playbooks collection from the UI doesn't
strip server-side validation rules the modal doesn't yet expose
dedicated controls for. fieldFromDef mirrors the change for templates.

P2 — checkUniqueFields' pre-write ListItems check is now backed by a
partial unique index (idx_items_invocation_slug_per_collection,
SQLite + Postgres) scoped to non-empty, non-deleted rows. The pre-check
still gives users a friendly error message in the common case; the
index closes the TOCTOU race between two concurrent writers. The
create-conflict error message is now generic enough to cover both the
slug constraint and the new invocation_slug index.

P2 — `json` field type now rejects raw strings, numbers, and bools. Only
objects, arrays, and null are accepted, so a generic web text input
can't silently corrupt a structured field by emitting "[]" instead of
an actual array. FieldEditor.svelte routes `json` fields to a
read-only summary in both readonly and edit modes; dedicated editors
(like TASK-1384's playbook editor that owns `arguments`) own the
structured form.

P3 — invocation_slug regex now requires a minimum of two characters
(`^[a-z0-9][a-z0-9-]*[a-z0-9]$`) in the Go const, the SQLite migration,
the Postgres migration, and the validate tests. Single-letter slugs
would shadow plausible NL tokens (e.g. `/pad a ...`) and the doc
comment already claimed the two-char floor; this aligns code with
intent.

Parent: PLAN-1377.

* fix(playbooks): address Codex review round 2 findings (TASK-1378)

P2.1 — checkUniqueFields no longer passes IncludeArchived=true. The
application-layer pre-check now matches the partial unique index's
`deleted_at IS NULL` predicate so a soft-deleted playbook releases its
slug back to the pool and reclaiming it succeeds instead of 409'ing.

P2.2 — handleUpdateItem now maps UNIQUE constraint / duplicate key
errors from UpdateItem to HTTP 409, mirroring the create path. A true
concurrent-update race that slips past checkUniqueFields and trips the
partial unique index used to surface as a misleading 500.

(Not addressed in this round: Codex's third finding — concern about the
partial unique index applying to "every collection" — is, on close
reading, not what the index does. `ON items(collection_id, json_extract(...))`
scopes uniqueness to the (collection_id, slug) pair, so two items in
different collections with the same `invocation_slug` value coexist
fine. The migration-failure risk is theoretical: `invocation_slug` is
a brand-new field key, so no pre-existing items can have it set, and
no migration-time duplicates can exist. If a future custom collection
adopts the same field name, opting into per-collection uniqueness is
exactly the intended semantic of FieldDef.UniqueScope.)

Parent: PLAN-1377.

* fix(playbooks): map restore-path UNIQUE violations to 409 (TASK-1378)

Codex round 3: restoring an archived playbook can hit the partial
unique index on invocation_slug if a replacement item already claimed
the slug. Map UNIQUE constraint / duplicate key errors from RestoreItem
to HTTP 409 with a targeted message, matching the create + update paths.

Parent: PLAN-1377.

* fix(playbooks): map collab-snapshot UNIQUE violations to 409 (TASK-1378)

Codex round 4: the collab-snapshot PATCH branch under
`s.collab.UnderItemLock` ran its own UpdateItem call and fell through
to writeInternalError on any non-stale-snapshot error. A concurrent
edit racing the invocation_slug partial unique index would surface as
500 instead of 409. Mirror the main UpdateItem error mapping.

Codex's other round-4 finding — the partial unique index applying to
"every collection" — is not addressed because the index IS already
collection-scoped: `ON items(collection_id, json_extract(fields,
'$.invocation_slug'))`. Two items in different collections with the
same slug coexist; only same-collection duplicates conflict. Migration
duplicates are impossible because `invocation_slug` is a brand-new
field key with no pre-existing items setting it. A custom collection
that later adopts the same field name opts into per-collection
uniqueness, matching the FieldDef.UniqueScope="workspace_collection"
semantic.

Parent: PLAN-1377.
2026-05-12 17:17:56 -04:00

195 lines
4.9 KiB
Go

package items
import (
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/PerpetualSoftware/pad/internal/models"
)
// patternCache memoizes compiled regexes so repeat validations don't pay the
// re-compile cost. Schemas change rarely; the entries are tiny.
var (
patternCache = make(map[string]*regexp.Regexp)
patternCacheMu sync.RWMutex
)
func compilePattern(pat string) (*regexp.Regexp, error) {
patternCacheMu.RLock()
re, ok := patternCache[pat]
patternCacheMu.RUnlock()
if ok {
return re, nil
}
re, err := regexp.Compile(pat)
if err != nil {
return nil, err
}
patternCacheMu.Lock()
patternCache[pat] = re
patternCacheMu.Unlock()
return re, nil
}
// ValidateFields checks field values against the collection schema.
// It validates required fields are present, types are correct, and select
// values are within the allowed options. It applies defaults for missing
// optional fields, mutating the fields map in place.
func ValidateFields(fields map[string]any, schema models.CollectionSchema) error {
var errs []string
for _, def := range schema.Fields {
val, exists := fields[def.Key]
// Apply default if field is missing and a default is defined
if !exists || val == nil {
if def.Required {
if def.Default != nil {
fields[def.Key] = def.Default
continue
}
errs = append(errs, fmt.Sprintf("field %q is required", def.Key))
continue
}
if def.Default != nil {
fields[def.Key] = def.Default
}
continue
}
// Validate by type
if err := validateFieldType(def, val); err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) > 0 {
return fmt.Errorf("field validation failed: %s", strings.Join(errs, "; "))
}
return nil
}
func validateFieldType(def models.FieldDef, val any) error {
switch def.Type {
case "text", "url":
if _, ok := val.(string); !ok {
return fmt.Errorf("field %q must be a string", def.Key)
}
case "number":
switch val.(type) {
case float64, int, int64, float32:
// ok
default:
return fmt.Errorf("field %q must be a number", def.Key)
}
case "checkbox":
if _, ok := val.(bool); !ok {
return fmt.Errorf("field %q must be a boolean", def.Key)
}
case "date":
s, ok := val.(string)
if !ok {
return fmt.Errorf("field %q must be a date string (ISO 8601)", def.Key)
}
if s != "" {
// Accept YYYY-MM-DD or full RFC3339
if _, err := time.Parse("2006-01-02", s); err != nil {
if _, err := time.Parse(time.RFC3339, s); err != nil {
return fmt.Errorf("field %q has invalid date format (expected YYYY-MM-DD or RFC3339)", def.Key)
}
}
}
case "select":
s, ok := val.(string)
if !ok {
return fmt.Errorf("field %q must be a string", def.Key)
}
if s != "" && len(def.Options) > 0 {
found := false
for _, opt := range def.Options {
if opt == s {
found = true
break
}
}
if !found {
return fmt.Errorf("field %q value %q is not in allowed options %v", def.Key, s, def.Options)
}
}
case "multi_select":
// Accept a slice of strings
switch v := val.(type) {
case []any:
for i, item := range v {
s, ok := item.(string)
if !ok {
return fmt.Errorf("field %q item %d must be a string", def.Key, i)
}
if len(def.Options) > 0 {
found := false
for _, opt := range def.Options {
if opt == s {
found = true
break
}
}
if !found {
return fmt.Errorf("field %q value %q is not in allowed options %v", def.Key, s, def.Options)
}
}
}
case []string:
for _, s := range v {
if len(def.Options) > 0 {
found := false
for _, opt := range def.Options {
if opt == s {
found = true
break
}
}
if !found {
return fmt.Errorf("field %q value %q is not in allowed options %v", def.Key, s, def.Options)
}
}
}
default:
return fmt.Errorf("field %q must be an array of strings", def.Key)
}
case "relation":
if _, ok := val.(string); !ok {
return fmt.Errorf("field %q must be a string (item ID)", def.Key)
}
case "json":
// Accept only structured JSON values (object, array, null). Raw
// strings / numbers / bools are rejected so a generic text input in
// the UI can't silently corrupt a structured field (e.g. emitting
// the string "[]" instead of an actual array). Callers that want a
// scalar field should use "text", "number", or "checkbox".
switch val.(type) {
case map[string]any, []any, nil:
// ok
default:
return fmt.Errorf("field %q must be a JSON object, array, or null", def.Key)
}
}
// Pattern check applies to string-typed values (text, url, and JSON strings).
if def.Pattern != "" {
s, ok := val.(string)
if ok && s != "" {
re, err := compilePattern(def.Pattern)
if err != nil {
return fmt.Errorf("field %q has an invalid pattern in its schema: %v", def.Key, err)
}
if !re.MatchString(s) {
return fmt.Errorf("field %q value %q does not match required pattern %q", def.Key, s, def.Pattern)
}
}
}
return nil
}