mirror of
https://github.com/PerpetualSoftware/pad.git
synced 2026-09-22 02:23:46 +00:00
c38b3bf5cd
* 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.
366 lines
8.1 KiB
Go
366 lines
8.1 KiB
Go
package items
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/PerpetualSoftware/pad/internal/models"
|
|
)
|
|
|
|
func taskSchema() models.CollectionSchema {
|
|
return models.CollectionSchema{
|
|
Fields: []models.FieldDef{
|
|
{
|
|
Key: "status",
|
|
Label: "Status",
|
|
Type: "select",
|
|
Options: []string{"open", "in-progress", "done", "cancelled"},
|
|
Default: "open",
|
|
Required: true,
|
|
},
|
|
{
|
|
Key: "priority",
|
|
Label: "Priority",
|
|
Type: "select",
|
|
Options: []string{"low", "medium", "high", "critical"},
|
|
Default: "medium",
|
|
},
|
|
{
|
|
Key: "assignee",
|
|
Label: "Assignee",
|
|
Type: "text",
|
|
},
|
|
{
|
|
Key: "due_date",
|
|
Label: "Due Date",
|
|
Type: "date",
|
|
},
|
|
{
|
|
Key: "effort_hours",
|
|
Label: "Effort",
|
|
Type: "number",
|
|
},
|
|
{
|
|
Key: "done",
|
|
Label: "Done",
|
|
Type: "checkbox",
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_RequiredWithDefault(t *testing.T) {
|
|
schema := taskSchema()
|
|
fields := map[string]any{}
|
|
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error, got: %v", err)
|
|
}
|
|
|
|
// Required field "status" should have been filled with default
|
|
if fields["status"] != "open" {
|
|
t.Errorf("expected status default 'open', got %v", fields["status"])
|
|
}
|
|
// Optional field "priority" should have been filled with default
|
|
if fields["priority"] != "medium" {
|
|
t.Errorf("expected priority default 'medium', got %v", fields["priority"])
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_RequiredMissingNoDefault(t *testing.T) {
|
|
schema := models.CollectionSchema{
|
|
Fields: []models.FieldDef{
|
|
{Key: "name", Label: "Name", Type: "text", Required: true},
|
|
},
|
|
}
|
|
fields := map[string]any{}
|
|
|
|
err := ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for missing required field without default")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_SelectInvalid(t *testing.T) {
|
|
schema := taskSchema()
|
|
fields := map[string]any{
|
|
"status": "invalid-value",
|
|
}
|
|
|
|
err := ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for invalid select value")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_SelectValid(t *testing.T) {
|
|
schema := taskSchema()
|
|
fields := map[string]any{
|
|
"status": "done",
|
|
"priority": "high",
|
|
}
|
|
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error, got: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_NumberType(t *testing.T) {
|
|
schema := taskSchema()
|
|
|
|
// Valid number
|
|
fields := map[string]any{
|
|
"effort_hours": float64(5),
|
|
}
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error for valid number, got: %v", err)
|
|
}
|
|
|
|
// Invalid number
|
|
fields = map[string]any{
|
|
"effort_hours": "not-a-number",
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for string in number field")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_CheckboxType(t *testing.T) {
|
|
schema := taskSchema()
|
|
|
|
// Valid boolean
|
|
fields := map[string]any{
|
|
"done": true,
|
|
}
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error for valid checkbox, got: %v", err)
|
|
}
|
|
|
|
// Invalid boolean
|
|
fields = map[string]any{
|
|
"done": "yes",
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for string in checkbox field")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_DateType(t *testing.T) {
|
|
schema := taskSchema()
|
|
|
|
// Valid date
|
|
fields := map[string]any{
|
|
"due_date": "2026-03-25",
|
|
}
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error for valid date, got: %v", err)
|
|
}
|
|
|
|
// Valid RFC3339
|
|
fields = map[string]any{
|
|
"due_date": "2026-03-25T10:00:00Z",
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error for valid RFC3339, got: %v", err)
|
|
}
|
|
|
|
// Invalid date
|
|
fields = map[string]any{
|
|
"due_date": "not-a-date",
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for invalid date")
|
|
}
|
|
|
|
// Empty date is OK (optional)
|
|
fields = map[string]any{
|
|
"due_date": "",
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error for empty date, got: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_TextType(t *testing.T) {
|
|
schema := taskSchema()
|
|
|
|
// Valid
|
|
fields := map[string]any{
|
|
"assignee": "alice",
|
|
}
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error, got: %v", err)
|
|
}
|
|
|
|
// Invalid
|
|
fields = map[string]any{
|
|
"assignee": 42,
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for number in text field")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_MultiSelect(t *testing.T) {
|
|
schema := models.CollectionSchema{
|
|
Fields: []models.FieldDef{
|
|
{
|
|
Key: "labels",
|
|
Label: "Labels",
|
|
Type: "multi_select",
|
|
Options: []string{"bug", "feature", "docs"},
|
|
},
|
|
},
|
|
}
|
|
|
|
// Valid
|
|
fields := map[string]any{
|
|
"labels": []any{"bug", "feature"},
|
|
}
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error, got: %v", err)
|
|
}
|
|
|
|
// Invalid option
|
|
fields = map[string]any{
|
|
"labels": []any{"bug", "invalid"},
|
|
}
|
|
err = ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for invalid multi_select option")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_JSONType(t *testing.T) {
|
|
schema := models.CollectionSchema{
|
|
Fields: []models.FieldDef{
|
|
{Key: "arguments", Label: "Arguments", Type: "json"},
|
|
},
|
|
}
|
|
|
|
cases := []struct {
|
|
name string
|
|
val any
|
|
wantErr bool
|
|
}{
|
|
{"array", []any{"a", "b"}, false},
|
|
{"object", map[string]any{"k": "v"}, false},
|
|
{"nil", nil, false}, // optional + nil is allowed
|
|
// Scalars are rejected: a generic web text input would corrupt a
|
|
// structured field by emitting strings like `"[]"` instead of
|
|
// arrays. Use "text" / "number" / "checkbox" for scalars.
|
|
{"string-rejected", "hello", true},
|
|
{"number-rejected", float64(42), true},
|
|
{"bool-rejected", true, true},
|
|
{"struct-not-decoded", struct{ X int }{1}, true},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
fields := map[string]any{"arguments": tc.val}
|
|
err := ValidateFields(fields, schema)
|
|
if tc.wantErr && err == nil {
|
|
t.Fatalf("expected error, got nil")
|
|
}
|
|
if !tc.wantErr && err != nil {
|
|
t.Fatalf("expected no error, got: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_PatternMatch(t *testing.T) {
|
|
schema := models.CollectionSchema{
|
|
Fields: []models.FieldDef{
|
|
{
|
|
Key: "invocation_slug",
|
|
Label: "Invocation slug",
|
|
Type: "text",
|
|
Pattern: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`,
|
|
},
|
|
},
|
|
}
|
|
|
|
cases := []struct {
|
|
name string
|
|
val string
|
|
wantErr bool
|
|
}{
|
|
{"valid-kebab", "ship", false},
|
|
{"valid-with-digits", "ship-blog-2", false},
|
|
{"valid-min-two-chars", "ab", false},
|
|
{"empty-allowed", "", false},
|
|
{"single-char-rejected", "a", true},
|
|
{"uppercase", "Ship", true},
|
|
{"underscore", "ship_blog", true},
|
|
{"leading-dash", "-ship", true},
|
|
{"trailing-dash", "ship-", true},
|
|
{"space", "ship blog", true},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
fields := map[string]any{"invocation_slug": tc.val}
|
|
err := ValidateFields(fields, schema)
|
|
if tc.wantErr && err == nil {
|
|
t.Fatalf("expected error for %q, got nil", tc.val)
|
|
}
|
|
if !tc.wantErr && err != nil {
|
|
t.Fatalf("expected no error for %q, got: %v", tc.val, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_InvalidPattern(t *testing.T) {
|
|
schema := models.CollectionSchema{
|
|
Fields: []models.FieldDef{
|
|
{
|
|
Key: "field",
|
|
Label: "Field",
|
|
Type: "text",
|
|
Pattern: `[unclosed`,
|
|
},
|
|
},
|
|
}
|
|
fields := map[string]any{"field": "value"}
|
|
err := ValidateFields(fields, schema)
|
|
if err == nil {
|
|
t.Fatal("expected error for invalid schema pattern")
|
|
}
|
|
}
|
|
|
|
func TestValidateFields_DefaultsApplied(t *testing.T) {
|
|
schema := taskSchema()
|
|
fields := map[string]any{
|
|
"assignee": "bob",
|
|
}
|
|
|
|
err := ValidateFields(fields, schema)
|
|
if err != nil {
|
|
t.Fatalf("expected no error, got: %v", err)
|
|
}
|
|
|
|
// Defaults should be applied
|
|
if fields["status"] != "open" {
|
|
t.Errorf("expected status default, got %v", fields["status"])
|
|
}
|
|
if fields["priority"] != "medium" {
|
|
t.Errorf("expected priority default, got %v", fields["priority"])
|
|
}
|
|
// Explicitly set field should remain
|
|
if fields["assignee"] != "bob" {
|
|
t.Errorf("expected assignee 'bob', got %v", fields["assignee"])
|
|
}
|
|
}
|