feat(create): make every native issue field addressable from --graph JSON plans
Graph plan nodes previously exposed only a fraction of the issue model (title, type, description, assignee, priority, labels, metadata, parent). Nodes now address the full model surface using the types.Issue JSON tag names, so the same manifest can express anything single-issue bd create can (comments excepted): design, acceptance_criteria, notes, spec_id, external_ref, owner, estimated_minutes, due_at/defer_until (RFC3339), initial status, explicit id, per-node ephemeral/no_history overrides, wisp_type, mol_type, pinned, and event fields (event_kind/actor/target/ payload, gated to type=event). Node metadata accepts arbitrary JSON values instead of strings only. Edges gain waits-for fanout-gate metadata (gate, spawner_key/spawner_id, mirroring --waits-for-gate) and thread_id for conversation edges; the domain layer resolves spawner_key after IDs mint. Both execution paths (embedded executeGraphApply and the proxied-server domain plan) now materialize nodes through a shared graphApplyNodeIssue that reuses createIssueParams/buildCreateIssue, and a reflection test pins parity: any future createIssueParams field must be graph-addressable or explicitly excluded. Plan validation covers the new fields early (status incl. custom statuses, id format/duplicates, estimate sign, wisp/mol types, event gating, storage-class conflicts, gate rules), with storage remaining the authoritative backstop (closed_at auto-fill, ID prefix checks in-transaction). Behavior notes: - Embedded graph creates now stamp created_by/owner like bd create (previously left empty, diverging from the proxied path). - Proxied wisp routing keys off effective ephemeral||no_history per storage's IsWisp instead of --ephemeral alone; mixed per-node storage classes are rejected in proxied mode (embedded routes per node). - Graph children intentionally do not inherit parent labels; documented. Docs: add the full graph plan schema to docs/CLI_REFERENCE.md under bd create (the warning text referenced a schema doc that did not exist). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
38031c51d9
commit
3567866de9
8 changed files with 931 additions and 169 deletions
|
|
@ -566,6 +566,208 @@ func TestEmbeddedCreate(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
t.Run("graph_full_fields", func(t *testing.T) {
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "gff")
|
||||
plan := `{
|
||||
"nodes": [
|
||||
{
|
||||
"key": "main",
|
||||
"id": "gff-a1b2c3",
|
||||
"title": "Full-field node",
|
||||
"type": "task",
|
||||
"status": "in_progress",
|
||||
"description": "desc",
|
||||
"design": "the design",
|
||||
"acceptance_criteria": "the criteria",
|
||||
"notes": "the notes",
|
||||
"spec_id": "gff-spec1",
|
||||
"external_ref": "gh-42",
|
||||
"assignee": "worker",
|
||||
"owner": "owner@example.com",
|
||||
"priority": 1,
|
||||
"estimated_minutes": 45,
|
||||
"due_at": "2030-01-02T15:04:05Z",
|
||||
"labels": ["x", "y"],
|
||||
"metadata": {"str": "v", "num": 3},
|
||||
"mol_type": "swarm",
|
||||
"pinned": true
|
||||
},
|
||||
{
|
||||
"key": "deferred",
|
||||
"title": "Deferred node",
|
||||
"defer_until": "2030-01-01T00:00:00Z"
|
||||
},
|
||||
{
|
||||
"key": "done",
|
||||
"title": "Closed node",
|
||||
"status": "closed"
|
||||
},
|
||||
{
|
||||
"key": "evt",
|
||||
"title": "Event node",
|
||||
"type": "event",
|
||||
"event_kind": "agent.started",
|
||||
"actor": "agent://a",
|
||||
"target": "bead://b",
|
||||
"payload": "{\"k\":1}"
|
||||
}
|
||||
]
|
||||
}`
|
||||
planFile := filepath.Join(dir, "full-fields-plan.json")
|
||||
if err := os.WriteFile(planFile, []byte(plan), 0o600); err != nil {
|
||||
t.Fatalf("write graph plan: %v", err)
|
||||
}
|
||||
result := bdCreateGraph(t, bd, dir, planFile)
|
||||
|
||||
if result.IDs["main"] != "gff-a1b2c3" {
|
||||
t.Errorf("explicit id: got %q, want gff-a1b2c3", result.IDs["main"])
|
||||
}
|
||||
|
||||
issue := bdShow(t, bd, dir, result.IDs["main"])
|
||||
if issue.Status != types.StatusInProgress {
|
||||
t.Errorf("status: got %q, want in_progress", issue.Status)
|
||||
}
|
||||
if issue.Description != "desc" || issue.Design != "the design" || issue.AcceptanceCriteria != "the criteria" || issue.Notes != "the notes" {
|
||||
t.Errorf("content fields lost: %+v", issue)
|
||||
}
|
||||
if issue.SpecID != "gff-spec1" {
|
||||
t.Errorf("spec_id: got %q", issue.SpecID)
|
||||
}
|
||||
if issue.ExternalRef == nil || *issue.ExternalRef != "gh-42" {
|
||||
t.Errorf("external_ref: got %v", issue.ExternalRef)
|
||||
}
|
||||
if issue.Assignee != "worker" {
|
||||
t.Errorf("assignee: got %q", issue.Assignee)
|
||||
}
|
||||
if issue.Owner != "owner@example.com" {
|
||||
t.Errorf("owner: got %q", issue.Owner)
|
||||
}
|
||||
if issue.Priority != 1 {
|
||||
t.Errorf("priority: got %d, want 1", issue.Priority)
|
||||
}
|
||||
if issue.EstimatedMinutes == nil || *issue.EstimatedMinutes != 45 {
|
||||
t.Errorf("estimated_minutes: got %v, want 45", issue.EstimatedMinutes)
|
||||
}
|
||||
if issue.DueAt == nil || issue.DueAt.Format("2006-01-02") != "2030-01-02" {
|
||||
t.Errorf("due_at: got %v", issue.DueAt)
|
||||
}
|
||||
if issue.MolType != types.MolType("swarm") {
|
||||
t.Errorf("mol_type: got %q", issue.MolType)
|
||||
}
|
||||
if !issue.Pinned {
|
||||
t.Errorf("pinned not set")
|
||||
}
|
||||
var meta map[string]any
|
||||
if err := json.Unmarshal(issue.Metadata, &meta); err != nil {
|
||||
t.Fatalf("metadata not valid JSON: %v", err)
|
||||
}
|
||||
if meta["str"] != "v" || meta["num"] != float64(3) {
|
||||
t.Errorf("metadata round-trip wrong (non-string values must survive): %v", meta)
|
||||
}
|
||||
|
||||
deferred := bdShow(t, bd, dir, result.IDs["deferred"])
|
||||
if deferred.Status != types.StatusDeferred {
|
||||
t.Errorf("deferred status: got %q, want deferred", deferred.Status)
|
||||
}
|
||||
if deferred.DeferUntil == nil {
|
||||
t.Errorf("defer_until lost")
|
||||
}
|
||||
|
||||
done := bdShow(t, bd, dir, result.IDs["done"])
|
||||
if done.Status != types.StatusClosed {
|
||||
t.Errorf("closed status: got %q, want closed", done.Status)
|
||||
}
|
||||
if done.ClosedAt == nil {
|
||||
t.Errorf("closed node missing auto-filled closed_at")
|
||||
}
|
||||
|
||||
evt := bdShow(t, bd, dir, result.IDs["evt"])
|
||||
if evt.EventKind != "agent.started" || evt.Actor != "agent://a" || evt.Target != "bead://b" || evt.Payload != `{"k":1}` {
|
||||
t.Errorf("event fields lost: kind=%q actor=%q target=%q payload=%q", evt.EventKind, evt.Actor, evt.Target, evt.Payload)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("graph_waits_for_gate", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "gw")
|
||||
plan := `{
|
||||
"nodes": [
|
||||
{"key": "gate", "title": "Fanout gate"},
|
||||
{"key": "spawner", "title": "Spawner step"}
|
||||
],
|
||||
"edges": [
|
||||
{"from_key": "gate", "to_key": "spawner", "type": "waits-for", "gate": "any-children", "spawner_key": "spawner"}
|
||||
]
|
||||
}`
|
||||
planFile := filepath.Join(dir, "gate-plan.json")
|
||||
if err := os.WriteFile(planFile, []byte(plan), 0o600); err != nil {
|
||||
t.Fatalf("write graph plan: %v", err)
|
||||
}
|
||||
result := bdCreateGraph(t, bd, dir, planFile)
|
||||
gateID := result.IDs["gate"]
|
||||
spawnerID := result.IDs["spawner"]
|
||||
|
||||
dataDir := filepath.Join(beadsDir, "embeddeddolt")
|
||||
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, "gw", "main")
|
||||
if err != nil {
|
||||
t.Fatalf("OpenSQL: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
var metadata string
|
||||
err = db.QueryRowContext(t.Context(),
|
||||
"SELECT COALESCE(metadata, '') FROM dependencies WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ? AND type = 'waits-for'",
|
||||
gateID, spawnerID).Scan(&metadata)
|
||||
if err != nil {
|
||||
t.Fatalf("query waits-for dep: %v", err)
|
||||
}
|
||||
var meta types.WaitsForMeta
|
||||
if err := json.Unmarshal([]byte(metadata), &meta); err != nil {
|
||||
t.Fatalf("dep metadata not WaitsForMeta JSON (%q): %v", metadata, err)
|
||||
}
|
||||
if meta.Gate != types.WaitsForAnyChildren {
|
||||
t.Errorf("gate: got %q, want any-children", meta.Gate)
|
||||
}
|
||||
if meta.SpawnerID != spawnerID {
|
||||
t.Errorf("spawner: got %q, want resolved key %q", meta.SpawnerID, spawnerID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("graph_per_node_storage_class", func(t *testing.T) {
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "gs")
|
||||
plan := `{
|
||||
"nodes": [
|
||||
{"key": "durable", "title": "Durable node"},
|
||||
{"key": "wisp", "title": "Wisp node", "ephemeral": true}
|
||||
]
|
||||
}`
|
||||
planFile := filepath.Join(dir, "storage-plan.json")
|
||||
if err := os.WriteFile(planFile, []byte(plan), 0o600); err != nil {
|
||||
t.Fatalf("write graph plan: %v", err)
|
||||
}
|
||||
result := bdCreateGraph(t, bd, dir, planFile)
|
||||
|
||||
dataDir := filepath.Join(beadsDir, "embeddeddolt")
|
||||
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, "gs", "main")
|
||||
if err != nil {
|
||||
t.Fatalf("OpenSQL: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
var count int
|
||||
if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM issues WHERE id = ?", result.IDs["durable"]).Scan(&count); err != nil {
|
||||
t.Fatalf("query issues: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("durable node not in issues table")
|
||||
}
|
||||
if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM wisps WHERE id = ?", result.IDs["wisp"]).Scan(&count); err != nil {
|
||||
t.Fatalf("query wisps: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("per-node ephemeral override not routed to wisps table")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("estimate", func(t *testing.T) {
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "es")
|
||||
issue := bdCreate(t, bd, dir, "Estimated issue", "-e", "60")
|
||||
|
|
|
|||
|
|
@ -392,7 +392,7 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
|
|||
if err != nil {
|
||||
return HandleError("load create context: %v", err)
|
||||
}
|
||||
if err := validateGraphApplyPlan(&plan, resolveProxiedCustomTypes(cctx.CustomTypes)); err != nil {
|
||||
if err := validateGraphApplyPlan(&plan, resolveProxiedCustomTypes(cctx.CustomTypes), config.GetCustomStatusesFromYAML()); err != nil {
|
||||
return HandleError("invalid graph plan: %v", err)
|
||||
}
|
||||
if err := emitGraphApplyDryRun(&plan); err != nil {
|
||||
|
|
@ -401,7 +401,7 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
|
|||
return nil
|
||||
}
|
||||
|
||||
domainPlan, err := buildDomainGraphPlan(plan, in)
|
||||
domainPlan, useWisp, err := buildDomainGraphPlan(plan, in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -417,13 +417,13 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
|
|||
return nil, "", fmt.Errorf("load create context: %w", err)
|
||||
}
|
||||
|
||||
if err := validateGraphApplyPlan(&plan, resolveProxiedCustomTypes(cctx.CustomTypes)); err != nil {
|
||||
if err := validateGraphApplyPlan(&plan, resolveProxiedCustomTypes(cctx.CustomTypes), config.GetCustomStatusesFromYAML()); err != nil {
|
||||
return nil, "", fmt.Errorf("invalid graph plan: %w", err)
|
||||
}
|
||||
|
||||
var result domain.GraphApplyResult
|
||||
var applyErr error
|
||||
if in.ephemeral {
|
||||
if useWisp {
|
||||
result, applyErr = uw.IssueUseCase().ApplyWispGraph(ctx, domainPlan, in.createdBy)
|
||||
} else {
|
||||
result, applyErr = uw.IssueUseCase().ApplyIssueGraph(ctx, domainPlan, in.createdBy)
|
||||
|
|
@ -458,12 +458,25 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
|
|||
return nil
|
||||
}
|
||||
|
||||
func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) (domain.GraphPlan, error) {
|
||||
// buildDomainGraphPlan materializes every plan node through the shared
|
||||
// graphApplyNodeIssue path (full issue-model parity with `bd create`) and
|
||||
// returns whether the plan routes to the wisps table. Domain graph creation
|
||||
// routes the whole plan to a single table, so per-node storage-class
|
||||
// overrides must be uniform in proxied-server mode.
|
||||
func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) (domain.GraphPlan, bool, error) {
|
||||
opts := GraphApplyOptions{Ephemeral: in.ephemeral, NoHistory: in.noHistory}
|
||||
var useWisp bool
|
||||
nodes := make([]domain.GraphNode, 0, len(plan.Nodes))
|
||||
for _, n := range plan.Nodes {
|
||||
issue, err := materializeGraphNodeIssue(n, in)
|
||||
for i, n := range plan.Nodes {
|
||||
issue, err := graphApplyNodeIssue(n, opts, in.createdBy, in.owner)
|
||||
if err != nil {
|
||||
return domain.GraphPlan{}, err
|
||||
return domain.GraphPlan{}, false, fmt.Errorf("invalid graph plan: %w", err)
|
||||
}
|
||||
nodeWisp := issue.Ephemeral || issue.NoHistory
|
||||
if i == 0 {
|
||||
useWisp = nodeWisp
|
||||
} else if nodeWisp != useWisp {
|
||||
return domain.GraphPlan{}, false, fmt.Errorf("node %q: per-node ephemeral/no_history overrides must be uniform across the plan in proxied-server mode", n.Key)
|
||||
}
|
||||
nodes = append(nodes, domain.GraphNode{
|
||||
Key: n.Key,
|
||||
|
|
@ -479,44 +492,16 @@ func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) (domain.GraphPlan
|
|||
edges := make([]domain.GraphEdge, 0, len(plan.Edges))
|
||||
for _, e := range plan.Edges {
|
||||
edges = append(edges, domain.GraphEdge{
|
||||
FromKey: e.FromKey,
|
||||
FromID: e.FromID,
|
||||
ToKey: e.ToKey,
|
||||
ToID: e.ToID,
|
||||
Type: graphApplyDependencyType(e.Type),
|
||||
FromKey: e.FromKey,
|
||||
FromID: e.FromID,
|
||||
ToKey: e.ToKey,
|
||||
ToID: e.ToID,
|
||||
Type: graphApplyDependencyType(e.Type),
|
||||
Gate: e.Gate,
|
||||
SpawnerKey: e.SpawnerKey,
|
||||
SpawnerID: e.SpawnerID,
|
||||
ThreadID: e.ThreadID,
|
||||
})
|
||||
}
|
||||
return domain.GraphPlan{Nodes: nodes, Edges: edges}, nil
|
||||
}
|
||||
|
||||
func materializeGraphNodeIssue(n GraphApplyNode, in createInput) (*types.Issue, error) {
|
||||
issueType := types.IssueType(n.Type)
|
||||
if issueType == "" {
|
||||
issueType = types.TypeTask
|
||||
}
|
||||
priority := 2
|
||||
if n.Priority != nil {
|
||||
priority = *n.Priority
|
||||
}
|
||||
var metadataJSON json.RawMessage
|
||||
if len(n.Metadata) > 0 {
|
||||
raw, err := json.Marshal(n.Metadata)
|
||||
if err != nil {
|
||||
return nil, HandleError("node %q: marshaling metadata: %v", n.Key, err)
|
||||
}
|
||||
metadataJSON = raw
|
||||
}
|
||||
return &types.Issue{
|
||||
Title: n.Title,
|
||||
Description: n.Description,
|
||||
IssueType: issueType,
|
||||
Status: types.StatusOpen,
|
||||
Priority: priority,
|
||||
Labels: n.Labels,
|
||||
Metadata: metadataJSON,
|
||||
Ephemeral: in.ephemeral,
|
||||
NoHistory: in.noHistory,
|
||||
CreatedBy: in.createdBy,
|
||||
Owner: in.owner,
|
||||
}, nil
|
||||
return domain.GraphPlan{Nodes: nodes, Edges: edges}, useWisp, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,12 +117,20 @@ func TestBuildCreateIssueFromInput_ExplicitStatusWinsOverDefer(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
|
||||
// nodeIssueFromInput mirrors buildDomainGraphPlan's per-node materialization
|
||||
// so unit tests can exercise graphApplyNodeIssue with createInput-level opts.
|
||||
func nodeIssueFromInput(t *testing.T, node GraphApplyNode, in createInput) *types.Issue {
|
||||
t.Helper()
|
||||
issue, err := graphApplyNodeIssue(node, GraphApplyOptions{Ephemeral: in.ephemeral, NoHistory: in.noHistory}, in.createdBy, in.owner)
|
||||
if err != nil {
|
||||
t.Fatalf("graphApplyNodeIssue: %v", err)
|
||||
}
|
||||
return issue
|
||||
}
|
||||
|
||||
func TestGraphApplyNodeIssue_DefaultsAndOpts(t *testing.T) {
|
||||
t.Run("type and priority defaults", func(t *testing.T) {
|
||||
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{createdBy: "t"})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
}
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N"}, createInput{createdBy: "t"})
|
||||
if issue.IssueType != types.TypeTask {
|
||||
t.Errorf("type default = %q, want task", issue.IssueType)
|
||||
}
|
||||
|
|
@ -136,12 +144,9 @@ func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
|
|||
|
||||
t.Run("explicit priority and type", func(t *testing.T) {
|
||||
p := 0
|
||||
issue, err := materializeGraphNodeIssue(GraphApplyNode{
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{
|
||||
Key: "n", Title: "N", Type: "bug", Priority: &p,
|
||||
}, createInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
}
|
||||
if issue.IssueType != types.TypeBug {
|
||||
t.Errorf("type = %q, want bug", issue.IssueType)
|
||||
}
|
||||
|
|
@ -151,66 +156,122 @@ func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("ephemeral and no-history propagate", func(t *testing.T) {
|
||||
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N"}, createInput{
|
||||
ephemeral: true,
|
||||
noHistory: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
}
|
||||
if !issue.Ephemeral {
|
||||
t.Errorf("ephemeral not propagated")
|
||||
}
|
||||
issue2, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
|
||||
issue2 := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N"}, createInput{
|
||||
noHistory: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
}
|
||||
if !issue2.NoHistory {
|
||||
t.Errorf("no_history not propagated")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("metadata marshalled to JSON", func(t *testing.T) {
|
||||
issue, err := materializeGraphNodeIssue(GraphApplyNode{
|
||||
Key: "n", Title: "N",
|
||||
Metadata: map[string]string{"a": "1", "b": "2"},
|
||||
}, createInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
t.Run("per-node storage class overrides plan flags", func(t *testing.T) {
|
||||
off := false
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N", Ephemeral: &off}, createInput{
|
||||
ephemeral: true,
|
||||
})
|
||||
if issue.Ephemeral {
|
||||
t.Errorf("node-level ephemeral=false should override --ephemeral")
|
||||
}
|
||||
var roundTrip map[string]string
|
||||
on := true
|
||||
issue2 := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N", NoHistory: &on}, createInput{})
|
||||
if !issue2.NoHistory {
|
||||
t.Errorf("node-level no_history=true not applied")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("conflicting effective storage class errors", func(t *testing.T) {
|
||||
on := true
|
||||
_, err := graphApplyNodeIssue(GraphApplyNode{Key: "n", Title: "N", NoHistory: &on}, GraphApplyOptions{Ephemeral: true}, "", "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for effective ephemeral+no_history")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("metadata marshalled to JSON", func(t *testing.T) {
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{
|
||||
Key: "n", Title: "N",
|
||||
Metadata: map[string]json.RawMessage{"a": json.RawMessage(`"1"`), "b": json.RawMessage(`2`)},
|
||||
}, createInput{})
|
||||
var roundTrip map[string]any
|
||||
if err := json.Unmarshal(issue.Metadata, &roundTrip); err != nil {
|
||||
t.Fatalf("metadata not valid JSON: %v", err)
|
||||
}
|
||||
if roundTrip["a"] != "1" || roundTrip["b"] != "2" {
|
||||
if roundTrip["a"] != "1" || roundTrip["b"] != float64(2) {
|
||||
t.Errorf("metadata round-trip wrong: %v", roundTrip)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty metadata leaves Metadata nil", func(t *testing.T) {
|
||||
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
}
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N"}, createInput{})
|
||||
if issue.Metadata != nil {
|
||||
t.Errorf("Metadata = %s, want nil for empty input", string(issue.Metadata))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("identity fields copied", func(t *testing.T) {
|
||||
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N"}, createInput{
|
||||
createdBy: "alice",
|
||||
owner: "alice@example.com",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("materializeGraphNodeIssue: %v", err)
|
||||
}
|
||||
if issue.CreatedBy != "alice" || issue.Owner != "alice@example.com" {
|
||||
t.Errorf("identity copy wrong: %q / %q", issue.CreatedBy, issue.Owner)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("node owner overrides ambient owner", func(t *testing.T) {
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{Key: "n", Title: "N", Owner: "bob@example.com"}, createInput{
|
||||
owner: "alice@example.com",
|
||||
})
|
||||
if issue.Owner != "bob@example.com" {
|
||||
t.Errorf("Owner = %q, want node override", issue.Owner)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("native content and planning fields copied", func(t *testing.T) {
|
||||
est := 90
|
||||
issue := nodeIssueFromInput(t, GraphApplyNode{
|
||||
Key: "n", Title: "N",
|
||||
Design: "d",
|
||||
AcceptanceCriteria: "ac",
|
||||
Notes: "notes",
|
||||
SpecID: "spec-1",
|
||||
ExternalRef: "gh-9",
|
||||
EstimatedMinutes: &est,
|
||||
WispType: "heartbeat",
|
||||
MolType: "swarm",
|
||||
Pinned: true,
|
||||
Status: "in_progress",
|
||||
ID: "bd-abc123",
|
||||
}, createInput{})
|
||||
if issue.Design != "d" || issue.AcceptanceCriteria != "ac" || issue.Notes != "notes" || issue.SpecID != "spec-1" {
|
||||
t.Errorf("content fields lost: %+v", issue)
|
||||
}
|
||||
if issue.ExternalRef == nil || *issue.ExternalRef != "gh-9" {
|
||||
t.Errorf("ExternalRef = %v", issue.ExternalRef)
|
||||
}
|
||||
if issue.EstimatedMinutes == nil || *issue.EstimatedMinutes != 90 {
|
||||
t.Errorf("EstimatedMinutes = %v", issue.EstimatedMinutes)
|
||||
}
|
||||
if issue.WispType != types.WispType("heartbeat") || issue.MolType != types.MolType("swarm") {
|
||||
t.Errorf("wisp/mol type lost: %q %q", issue.WispType, issue.MolType)
|
||||
}
|
||||
if !issue.Pinned {
|
||||
t.Errorf("Pinned lost")
|
||||
}
|
||||
if issue.Status != types.StatusInProgress {
|
||||
t.Errorf("Status = %q, want in_progress", issue.Status)
|
||||
}
|
||||
if issue.ID != "bd-abc123" {
|
||||
t.Errorf("ID = %q, want explicit ID", issue.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildDomainGraphPlan(t *testing.T) {
|
||||
|
|
@ -227,11 +288,14 @@ func TestBuildDomainGraphPlan(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
got, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"})
|
||||
got, useWisp, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"})
|
||||
if err != nil {
|
||||
t.Fatalf("buildDomainGraphPlan: %v", err)
|
||||
}
|
||||
|
||||
if useWisp {
|
||||
t.Errorf("useWisp = true for a durable plan")
|
||||
}
|
||||
if len(got.Nodes) != 2 {
|
||||
t.Fatalf("nodes len = %d", len(got.Nodes))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,10 +7,12 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/validation"
|
||||
)
|
||||
|
||||
// GraphApplyPlan describes a symbolic bead graph to create atomically.
|
||||
|
|
@ -20,24 +22,45 @@ type GraphApplyPlan struct {
|
|||
Edges []GraphApplyEdge `json:"edges,omitempty"`
|
||||
}
|
||||
|
||||
// GraphApplyNode describes a single bead to create.
|
||||
// GraphApplyNode describes a single bead to create. Field names follow the
|
||||
// types.Issue JSON tags so a node addresses the same model surface as
|
||||
// JSONL import and `bd show --json`.
|
||||
type GraphApplyNode struct {
|
||||
Key string `json:"key"`
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Assignee string `json:"assignee,omitempty"`
|
||||
AssignAfterCreate bool `json:"assign_after_create,omitempty"`
|
||||
Priority *int `json:"priority,omitempty"` // nil defaults to P2
|
||||
Estimate *int `json:"estimate,omitempty"` // minutes
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
MetadataRefs map[string]string `json:"metadata_refs,omitempty"`
|
||||
ExternalRef string `json:"external_ref,omitempty"`
|
||||
Parent string `json:"parent,omitempty"` // alias for parent_key
|
||||
ParentKey string `json:"parent_key,omitempty"`
|
||||
ParentID string `json:"parent_id,omitempty"`
|
||||
Deps []GraphApplyNodeDep `json:"deps,omitempty"`
|
||||
Key string `json:"key"`
|
||||
ID string `json:"id,omitempty"` // explicit issue ID (default: generated)
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Status string `json:"status,omitempty"` // initial status (default: open, or deferred when defer_until is future)
|
||||
Description string `json:"description,omitempty"`
|
||||
Design string `json:"design,omitempty"`
|
||||
AcceptanceCriteria string `json:"acceptance_criteria,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
SpecID string `json:"spec_id,omitempty"`
|
||||
ExternalRef string `json:"external_ref,omitempty"`
|
||||
Assignee string `json:"assignee,omitempty"`
|
||||
AssignAfterCreate bool `json:"assign_after_create,omitempty"`
|
||||
Owner string `json:"owner,omitempty"`
|
||||
Priority *int `json:"priority,omitempty"` // nil defaults to P2
|
||||
Estimate *int `json:"estimate,omitempty"` // minutes (alias for estimated_minutes)
|
||||
EstimatedMinutes *int `json:"estimated_minutes,omitempty"` // minutes
|
||||
DueAt *time.Time `json:"due_at,omitempty"` // RFC3339
|
||||
DeferUntil *time.Time `json:"defer_until,omitempty"` // RFC3339
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
Metadata map[string]json.RawMessage `json:"metadata,omitempty"`
|
||||
MetadataRefs map[string]string `json:"metadata_refs,omitempty"`
|
||||
Parent string `json:"parent,omitempty"` // alias for parent_key
|
||||
ParentKey string `json:"parent_key,omitempty"`
|
||||
ParentID string `json:"parent_id,omitempty"`
|
||||
Deps []GraphApplyNodeDep `json:"deps,omitempty"`
|
||||
Ephemeral *bool `json:"ephemeral,omitempty"` // overrides --ephemeral for this node
|
||||
NoHistory *bool `json:"no_history,omitempty"` // overrides --no-history for this node
|
||||
WispType string `json:"wisp_type,omitempty"`
|
||||
MolType string `json:"mol_type,omitempty"`
|
||||
Pinned bool `json:"pinned,omitempty"`
|
||||
EventKind string `json:"event_kind,omitempty"` // type=event only
|
||||
Actor string `json:"actor,omitempty"` // type=event only
|
||||
Target string `json:"target,omitempty"` // type=event only
|
||||
Payload string `json:"payload,omitempty"` // type=event only
|
||||
}
|
||||
|
||||
// GraphApplyEdge describes a dependency edge.
|
||||
|
|
@ -47,6 +70,11 @@ type GraphApplyEdge struct {
|
|||
ToKey string `json:"to_key,omitempty"`
|
||||
ToID string `json:"to_id,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
// Gate and spawner apply to waits-for edges only (fanout gates).
|
||||
Gate string `json:"gate,omitempty"` // all-children | any-children
|
||||
SpawnerKey string `json:"spawner_key,omitempty"` // plan-local key of the spawning node
|
||||
SpawnerID string `json:"spawner_id,omitempty"` // existing issue ID of the spawner
|
||||
ThreadID string `json:"thread_id,omitempty"` // conversation threading (replies-to)
|
||||
}
|
||||
|
||||
// GraphApplyNodeDep describes an inline dependency on a single graph node.
|
||||
|
|
@ -89,8 +117,10 @@ type GraphApplyDryRun struct {
|
|||
// GraphApplyDryRunRow describes a single planned node in the dry-run preview.
|
||||
type GraphApplyDryRunRow struct {
|
||||
Key string `json:"key"`
|
||||
ID string `json:"id,omitempty"` // explicit ID, when the plan sets one
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status,omitempty"` // explicit initial status, when the plan sets one
|
||||
Priority int `json:"priority"`
|
||||
ParentKey string `json:"parent_key,omitempty"`
|
||||
ParentID string `json:"parent_id,omitempty"`
|
||||
|
|
@ -112,31 +142,54 @@ var knownGraphPlanFields = map[string]struct{}{
|
|||
// Kept in sync with the json tags on GraphApplyNode. (GH#3367)
|
||||
var knownGraphNodeFields = map[string]struct{}{
|
||||
"key": {},
|
||||
"id": {},
|
||||
"title": {},
|
||||
"type": {},
|
||||
"status": {},
|
||||
"description": {},
|
||||
"design": {},
|
||||
"acceptance_criteria": {},
|
||||
"notes": {},
|
||||
"spec_id": {},
|
||||
"external_ref": {},
|
||||
"assignee": {},
|
||||
"assign_after_create": {},
|
||||
"owner": {},
|
||||
"priority": {},
|
||||
"estimate": {},
|
||||
"estimated_minutes": {},
|
||||
"due_at": {},
|
||||
"defer_until": {},
|
||||
"labels": {},
|
||||
"metadata": {},
|
||||
"metadata_refs": {},
|
||||
"external_ref": {},
|
||||
"parent": {},
|
||||
"parent_key": {},
|
||||
"parent_id": {},
|
||||
"deps": {},
|
||||
"ephemeral": {},
|
||||
"no_history": {},
|
||||
"wisp_type": {},
|
||||
"mol_type": {},
|
||||
"pinned": {},
|
||||
"event_kind": {},
|
||||
"actor": {},
|
||||
"target": {},
|
||||
"payload": {},
|
||||
}
|
||||
|
||||
// knownGraphEdgeFields lists the JSON keys recognized on a GraphApplyEdge.
|
||||
// Kept in sync with the json tags on GraphApplyEdge. (GH#3367)
|
||||
var knownGraphEdgeFields = map[string]struct{}{
|
||||
"from_key": {},
|
||||
"from_id": {},
|
||||
"to_key": {},
|
||||
"to_id": {},
|
||||
"type": {},
|
||||
"from_key": {},
|
||||
"from_id": {},
|
||||
"to_key": {},
|
||||
"to_id": {},
|
||||
"type": {},
|
||||
"gate": {},
|
||||
"spawner_key": {},
|
||||
"spawner_id": {},
|
||||
"thread_id": {},
|
||||
}
|
||||
|
||||
// graphFieldHints maps unknown-field names to a corrective hint pointing at
|
||||
|
|
@ -145,9 +198,16 @@ var knownGraphEdgeFields = map[string]struct{}{
|
|||
// a "parent" string instead of "parent_key", or "blocks" arrays instead of
|
||||
// the top-level edges array). (GH#3367)
|
||||
var graphFieldHints = map[string]string{
|
||||
"blocks": "use the top-level 'edges' array or per-node 'deps', e.g. {\"deps\": [{\"target\": \"key\", \"type\": \"blocks\"}]}",
|
||||
"depends": "use the top-level 'edges' array or per-node 'deps' with type 'blocks'",
|
||||
"children": "set 'parent_key' or 'parent' on each child instead of listing children on the parent",
|
||||
"blocks": "use the top-level 'edges' array or per-node 'deps', e.g. {\"deps\": [{\"target\": \"key\", \"type\": \"blocks\"}]}",
|
||||
"depends": "use the top-level 'edges' array or per-node 'deps' with type 'blocks'",
|
||||
"children": "set 'parent_key' or 'parent' on each child instead of listing children on the parent",
|
||||
"acceptance": "use 'acceptance_criteria' (matching the issue model's JSON field)",
|
||||
"due": "use 'due_at' with an RFC3339 timestamp",
|
||||
"defer": "use 'defer_until' with an RFC3339 timestamp",
|
||||
"event_category": "use 'event_kind' (matching the issue model's JSON field)",
|
||||
"event_actor": "use 'actor' (matching the issue model's JSON field)",
|
||||
"event_target": "use 'target' (matching the issue model's JSON field)",
|
||||
"event_payload": "use 'payload' (matching the issue model's JSON field)",
|
||||
}
|
||||
|
||||
// detectUnknownGraphFields scans the raw plan JSON and returns unknown field
|
||||
|
|
@ -273,6 +333,20 @@ func loadEmbeddedCustomTypes() []string {
|
|||
return config.GetCustomTypesFromYAML()
|
||||
}
|
||||
|
||||
func loadEmbeddedCustomStatuses() []string {
|
||||
if store != nil {
|
||||
if cs, err := store.GetCustomStatuses(rootCtx); err == nil && len(cs) > 0 {
|
||||
return cs
|
||||
}
|
||||
}
|
||||
return config.GetCustomStatusesFromYAML()
|
||||
}
|
||||
|
||||
// createIssuesFromGraph handles `bd create --graph <plan-file>`.
|
||||
// When dryRun is true, the plan is parsed and validated but no writes occur;
|
||||
// a preview is emitted to stdout (JSON when jsonOutput is set, otherwise
|
||||
// human-readable). Unknown plan/node/edge fields are reported to stderr in
|
||||
// both modes so schema gaps are visible before any writes happen. (GH#3367)
|
||||
func createIssuesFromGraph(planFile string, dryRun bool, opts GraphApplyOptions) error {
|
||||
data, err := os.ReadFile(planFile) // #nosec G304 -- user-provided path is intentional
|
||||
if err != nil {
|
||||
|
|
@ -288,7 +362,7 @@ func createIssuesFromGraph(planFile string, dryRun bool, opts GraphApplyOptions)
|
|||
return HandleErrorRespectJSON("parsing graph plan: %v", err)
|
||||
}
|
||||
|
||||
if err := validateGraphApplyPlan(&plan, loadEmbeddedCustomTypes()); err != nil {
|
||||
if err := validateGraphApplyPlan(&plan, loadEmbeddedCustomTypes(), loadEmbeddedCustomStatuses()); err != nil {
|
||||
return HandleErrorRespectJSON("invalid graph plan: %v", err)
|
||||
}
|
||||
|
||||
|
|
@ -337,8 +411,10 @@ func emitGraphApplyDryRun(plan *GraphApplyPlan) error {
|
|||
}
|
||||
rows = append(rows, GraphApplyDryRunRow{
|
||||
Key: node.Key,
|
||||
ID: node.ID,
|
||||
Title: node.Title,
|
||||
Type: issueType,
|
||||
Status: node.Status,
|
||||
Priority: priority,
|
||||
ParentKey: effectiveParentKey,
|
||||
ParentID: node.ParentID,
|
||||
|
|
@ -362,24 +438,31 @@ func emitGraphApplyDryRun(plan *GraphApplyPlan) error {
|
|||
preview.NodeCount, preview.EdgeCount, preview.ParentDeps)
|
||||
fmt.Printf("Note: %s.\n", graphApplyDryRunTransactionValidationNote)
|
||||
for _, row := range rows {
|
||||
parent := ""
|
||||
extras := ""
|
||||
if row.ID != "" {
|
||||
extras += fmt.Sprintf(" id=%s", row.ID)
|
||||
}
|
||||
if row.Status != "" {
|
||||
extras += fmt.Sprintf(" status=%s", row.Status)
|
||||
}
|
||||
switch {
|
||||
case row.ParentKey != "":
|
||||
parent = fmt.Sprintf(" parent_key=%s", row.ParentKey)
|
||||
extras += fmt.Sprintf(" parent_key=%s", row.ParentKey)
|
||||
case row.ParentID != "":
|
||||
parent = fmt.Sprintf(" parent_id=%s", row.ParentID)
|
||||
extras += fmt.Sprintf(" parent_id=%s", row.ParentID)
|
||||
}
|
||||
fmt.Printf(" %s [%s] P%d %q%s\n", row.Key, row.Type, row.Priority, row.Title, parent)
|
||||
fmt.Printf(" %s [%s] P%d %q%s\n", row.Key, row.Type, row.Priority, row.Title, extras)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes []string) error {
|
||||
func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes, customStatuses []string) error {
|
||||
if len(plan.Nodes) == 0 {
|
||||
return fmt.Errorf("plan has no nodes")
|
||||
}
|
||||
|
||||
seenKeys := make(map[string]bool, len(plan.Nodes))
|
||||
seenIDs := make(map[string]bool)
|
||||
for i, node := range plan.Nodes {
|
||||
if node.Key == "" {
|
||||
return fmt.Errorf("node %d has empty key", i)
|
||||
|
|
@ -397,6 +480,15 @@ func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes []string) error {
|
|||
return fmt.Errorf("node %q: invalid type %q", node.Key, node.Type)
|
||||
}
|
||||
}
|
||||
if err := validateGraphApplyNodeFields(node, customStatuses); err != nil {
|
||||
return err
|
||||
}
|
||||
if node.ID != "" {
|
||||
if seenIDs[node.ID] {
|
||||
return fmt.Errorf("duplicate explicit id %q (node %q)", node.ID, node.Key)
|
||||
}
|
||||
seenIDs[node.ID] = true
|
||||
}
|
||||
// Validate MetadataRefs point to known keys.
|
||||
for metaKey, refKey := range node.MetadataRefs {
|
||||
if !seenKeys[refKey] {
|
||||
|
|
@ -463,6 +555,20 @@ func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes []string) error {
|
|||
return fmt.Errorf("edge %d: invalid dependency type %q", i, edge.Type)
|
||||
}
|
||||
}
|
||||
if edge.Gate != "" || edge.SpawnerKey != "" || edge.SpawnerID != "" {
|
||||
if graphApplyDependencyType(edge.Type) != types.DepWaitsFor {
|
||||
return fmt.Errorf("edge %d: gate/spawner fields require type %q", i, types.DepWaitsFor)
|
||||
}
|
||||
if edge.Gate != "" && edge.Gate != types.WaitsForAllChildren && edge.Gate != types.WaitsForAnyChildren {
|
||||
return fmt.Errorf("edge %d: invalid gate %q (valid: %s, %s)", i, edge.Gate, types.WaitsForAllChildren, types.WaitsForAnyChildren)
|
||||
}
|
||||
if edge.SpawnerKey != "" && edge.SpawnerID != "" {
|
||||
return fmt.Errorf("edge %d: cannot specify both spawner_key and spawner_id", i)
|
||||
}
|
||||
if edge.SpawnerKey != "" && !seenKeys[edge.SpawnerKey] {
|
||||
return fmt.Errorf("edge %d: spawner key %q not found in plan", i, edge.SpawnerKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := validateGraphApplyLocalCycles(plan, seenKeys); err != nil {
|
||||
|
|
@ -472,6 +578,35 @@ func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes []string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// validateGraphApplyNodeFields checks the single-node fields added for full
|
||||
// issue-model parity, mirroring the checks `bd create` applies to its flags.
|
||||
func validateGraphApplyNodeFields(node GraphApplyNode, customStatuses []string) error {
|
||||
if node.ID != "" {
|
||||
if _, err := validation.ValidateIDFormat(node.ID); err != nil {
|
||||
return fmt.Errorf("node %q: %w", node.Key, err)
|
||||
}
|
||||
}
|
||||
if node.Status != "" && !types.Status(node.Status).IsValidWithCustom(customStatuses) {
|
||||
return fmt.Errorf("node %q: invalid status %q (built-in: open, in_progress, blocked, deferred, closed, pinned, hooked; or configure custom statuses via 'bd config set status.custom')", node.Key, node.Status)
|
||||
}
|
||||
if node.EstimatedMinutes != nil && *node.EstimatedMinutes < 0 {
|
||||
return fmt.Errorf("node %q: estimated_minutes must be non-negative", node.Key)
|
||||
}
|
||||
if node.WispType != "" && !types.WispType(node.WispType).IsValid() {
|
||||
return fmt.Errorf("node %q: invalid wisp_type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", node.Key, node.WispType)
|
||||
}
|
||||
if node.MolType != "" && !types.MolType(node.MolType).IsValid() {
|
||||
return fmt.Errorf("node %q: invalid mol_type %q (must be swarm, patrol, or work)", node.Key, node.MolType)
|
||||
}
|
||||
if node.Ephemeral != nil && node.NoHistory != nil && *node.Ephemeral && *node.NoHistory {
|
||||
return fmt.Errorf("node %q: ephemeral and no_history are mutually exclusive", node.Key)
|
||||
}
|
||||
if (node.EventKind != "" || node.Actor != "" || node.Target != "" || node.Payload != "") && node.Type != string(types.TypeEvent) {
|
||||
return fmt.Errorf("node %q: event_kind, actor, target, and payload require type %q", node.Key, types.TypeEvent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateGraphApplyLocalCycles(plan *GraphApplyPlan, knownKeys map[string]bool) error {
|
||||
adj := make(map[string][]string)
|
||||
for _, node := range plan.Nodes {
|
||||
|
|
@ -521,12 +656,125 @@ func validateGraphApplyLocalCycles(plan *GraphApplyPlan, knownKeys map[string]bo
|
|||
return nil
|
||||
}
|
||||
|
||||
// graphApplyNodeIssue materializes a plan node into an issue via the same
|
||||
// createIssueParams path used by single-issue `bd create`, so every field the
|
||||
// CLI can set stays addressable from graph plans. Assignee handling is left
|
||||
// to the caller (embedded and proxied paths defer assignment differently).
|
||||
func graphApplyNodeIssue(node GraphApplyNode, opts GraphApplyOptions, createdBy, owner string) (*types.Issue, error) {
|
||||
issueType := types.IssueType(node.Type)
|
||||
if issueType == "" {
|
||||
issueType = types.TypeTask
|
||||
}
|
||||
|
||||
var metadataJSON json.RawMessage
|
||||
if len(node.Metadata) > 0 {
|
||||
raw, err := json.Marshal(node.Metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("node %q: marshaling metadata: %w", node.Key, err)
|
||||
}
|
||||
metadataJSON = raw
|
||||
}
|
||||
|
||||
priority := 2 // Default P2
|
||||
if node.Priority != nil {
|
||||
priority = *node.Priority
|
||||
}
|
||||
|
||||
ephemeral, noHistory, err := graphApplyNodeStorageClass(node, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if node.Owner != "" {
|
||||
owner = node.Owner
|
||||
}
|
||||
|
||||
issue := buildCreateIssue(createIssueParams{
|
||||
ID: node.ID,
|
||||
Title: node.Title,
|
||||
Description: node.Description,
|
||||
Design: node.Design,
|
||||
AcceptanceCriteria: node.AcceptanceCriteria,
|
||||
Notes: node.Notes,
|
||||
SpecID: node.SpecID,
|
||||
Priority: priority,
|
||||
IssueType: issueType.Normalize(),
|
||||
ExternalRef: node.ExternalRef,
|
||||
EstimatedMinutes: node.EstimatedMinutes,
|
||||
Ephemeral: ephemeral,
|
||||
NoHistory: noHistory,
|
||||
CreatedBy: createdBy,
|
||||
Owner: owner,
|
||||
Labels: node.Labels,
|
||||
MolType: types.MolType(node.MolType),
|
||||
WispType: types.WispType(node.WispType),
|
||||
EventKind: node.EventKind,
|
||||
Actor: node.Actor,
|
||||
Target: node.Target,
|
||||
Payload: node.Payload,
|
||||
DueAt: node.DueAt,
|
||||
DeferUntil: node.DeferUntil,
|
||||
Metadata: metadataJSON,
|
||||
})
|
||||
if node.Status != "" {
|
||||
issue.Status = types.Status(node.Status)
|
||||
}
|
||||
issue.Pinned = node.Pinned
|
||||
return issue, nil
|
||||
}
|
||||
|
||||
// graphApplyNodeStorageClass resolves a node's effective storage class from
|
||||
// its per-node overrides and the plan-wide CLI flags.
|
||||
func graphApplyNodeStorageClass(node GraphApplyNode, opts GraphApplyOptions) (ephemeral, noHistory bool, err error) {
|
||||
ephemeral = opts.Ephemeral
|
||||
if node.Ephemeral != nil {
|
||||
ephemeral = *node.Ephemeral
|
||||
}
|
||||
noHistory = opts.NoHistory
|
||||
if node.NoHistory != nil {
|
||||
noHistory = *node.NoHistory
|
||||
}
|
||||
if ephemeral && noHistory {
|
||||
return false, false, fmt.Errorf("node %q: ephemeral and no_history are mutually exclusive", node.Key)
|
||||
}
|
||||
return ephemeral, noHistory, nil
|
||||
}
|
||||
|
||||
// graphApplyEdgeDependency builds the dependency record for an edge, including
|
||||
// waits-for gate metadata (types.WaitsForMeta) and conversation thread IDs.
|
||||
// resolveKey maps a plan-local node key to its minted issue ID.
|
||||
func graphApplyEdgeDependency(edge GraphApplyEdge, fromID, toID string, depType types.DependencyType, resolveKey func(string) string) (*types.Dependency, error) {
|
||||
dep := &types.Dependency{
|
||||
IssueID: fromID,
|
||||
DependsOnID: toID,
|
||||
Type: depType,
|
||||
}
|
||||
if edge.Gate != "" || edge.SpawnerKey != "" || edge.SpawnerID != "" {
|
||||
gate := edge.Gate
|
||||
if gate == "" {
|
||||
gate = types.WaitsForAllChildren
|
||||
}
|
||||
spawnerID := edge.SpawnerID
|
||||
if edge.SpawnerKey != "" {
|
||||
spawnerID = resolveKey(edge.SpawnerKey)
|
||||
}
|
||||
metaBytes, err := json.Marshal(types.WaitsForMeta{Gate: gate, SpawnerID: spawnerID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edge %s->%s: serializing waits-for metadata: %w", fromID, toID, err)
|
||||
}
|
||||
dep.Metadata = string(metaBytes)
|
||||
}
|
||||
dep.ThreadID = edge.ThreadID
|
||||
return dep, nil
|
||||
}
|
||||
|
||||
func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphApplyOptions) (*GraphApplyResult, error) {
|
||||
if err := opts.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyToID := make(map[string]string, len(plan.Nodes))
|
||||
owner := getOwner()
|
||||
|
||||
commitMsg := plan.CommitMessage
|
||||
if commitMsg == "" {
|
||||
|
|
@ -538,44 +786,13 @@ func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphAppl
|
|||
pendingAssignees := make(map[int]string)
|
||||
|
||||
for i, node := range plan.Nodes {
|
||||
issueType := types.IssueType(node.Type)
|
||||
if issueType == "" {
|
||||
issueType = types.TypeTask
|
||||
}
|
||||
|
||||
var metadataJSON json.RawMessage
|
||||
if len(node.Metadata) > 0 {
|
||||
raw, err := json.Marshal(node.Metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("node %q: marshaling metadata: %w", node.Key, err)
|
||||
}
|
||||
metadataJSON = raw
|
||||
}
|
||||
|
||||
priority := 2 // Default P2
|
||||
if node.Priority != nil {
|
||||
priority = *node.Priority
|
||||
}
|
||||
|
||||
issue := &types.Issue{
|
||||
Title: node.Title,
|
||||
IssueType: issueType,
|
||||
Status: types.StatusOpen,
|
||||
Priority: priority,
|
||||
Labels: node.Labels,
|
||||
Metadata: metadataJSON,
|
||||
Ephemeral: opts.Ephemeral,
|
||||
NoHistory: opts.NoHistory,
|
||||
}
|
||||
if node.Description != "" {
|
||||
issue.Description = node.Description
|
||||
issue, err := graphApplyNodeIssue(node, opts, actor, owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if node.Estimate != nil {
|
||||
issue.EstimatedMinutes = node.Estimate
|
||||
}
|
||||
if node.ExternalRef != "" {
|
||||
issue.ExternalRef = &node.ExternalRef
|
||||
}
|
||||
if node.Assignee != "" {
|
||||
if node.AssignAfterCreate {
|
||||
pendingAssignees[i] = node.Assignee
|
||||
|
|
@ -600,14 +817,18 @@ func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphAppl
|
|||
if len(node.MetadataRefs) == 0 {
|
||||
continue
|
||||
}
|
||||
mergedMeta := make(map[string]string)
|
||||
mergedMeta := make(map[string]json.RawMessage)
|
||||
if issues[i].Metadata != nil {
|
||||
if err := json.Unmarshal(issues[i].Metadata, &mergedMeta); err != nil {
|
||||
return fmt.Errorf("node %q: re-parsing metadata: %w", node.Key, err)
|
||||
}
|
||||
}
|
||||
for metaKey, refKey := range node.MetadataRefs {
|
||||
mergedMeta[metaKey] = keyToID[refKey]
|
||||
idJSON, err := json.Marshal(keyToID[refKey])
|
||||
if err != nil {
|
||||
return fmt.Errorf("node %q: marshaling metadata ref %q: %w", node.Key, metaKey, err)
|
||||
}
|
||||
mergedMeta[metaKey] = idJSON
|
||||
}
|
||||
metaJSON, err := json.Marshal(mergedMeta)
|
||||
if err != nil {
|
||||
|
|
@ -685,10 +906,9 @@ func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphAppl
|
|||
if parentDepPairs[graphApplyDepPairKey(toID, fromID)] && graphApplyCycleRelevantDependencyType(depType) {
|
||||
return fmt.Errorf("edge %d %s->%s creates a blocking reverse of a parent-child relationship", i, fromID, toID)
|
||||
}
|
||||
dep := &types.Dependency{
|
||||
IssueID: fromID,
|
||||
DependsOnID: toID,
|
||||
Type: depType,
|
||||
dep, err := graphApplyEdgeDependency(edge, fromID, toID, depType, func(key string) string { return keyToID[key] })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{}); err != nil {
|
||||
return fmt.Errorf("adding edge %s->%s: %w", fromID, toID, err)
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ func TestExecuteGraphApplyRejectsMixedLocalExternalBlockingCycle(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Fatalf("validateGraphApplyPlan: %v", err)
|
||||
}
|
||||
_, err := executeGraphApply(ctx, plan, GraphApplyOptions{})
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func TestValidateGraphApplyPlanAcceptsCustomTypes(t *testing.T) {
|
||||
|
|
@ -17,7 +19,7 @@ func TestValidateGraphApplyPlanAcceptsCustomTypes(t *testing.T) {
|
|||
{Key: "spec", Title: "Step spec", Type: "spec"},
|
||||
},
|
||||
}
|
||||
if err := validateGraphApplyPlan(plan, []string{"spec"}); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, []string{"spec"}, nil); err != nil {
|
||||
t.Fatalf("expected custom type %q to validate, got %v", "spec", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -28,7 +30,7 @@ func TestValidateGraphApplyPlanRejectsTypeWhenCustomTypesAbsent(t *testing.T) {
|
|||
{Key: "spec", Title: "Step spec", Type: "spec"},
|
||||
},
|
||||
}
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected custom type to fail when nil customTypes")
|
||||
}
|
||||
|
|
@ -44,7 +46,7 @@ func TestValidateGraphApplyPlanRejectsInvalidTypes(t *testing.T) {
|
|||
{Key: "root", Title: "Root", Type: "definitely-not-a-type"},
|
||||
},
|
||||
}
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid type")
|
||||
}
|
||||
|
|
@ -61,7 +63,7 @@ func TestValidateGraphApplyPlanAcceptsBuiltInTypes(t *testing.T) {
|
|||
{Key: "n1", Title: "Node", Type: typ},
|
||||
},
|
||||
}
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Errorf("type %q rejected: %v", typ, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -73,7 +75,7 @@ func TestValidateGraphApplyPlanAcceptsEmptyType(t *testing.T) {
|
|||
{Key: "n1", Title: "Node", Type: ""},
|
||||
},
|
||||
}
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Fatalf("empty type rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -101,7 +103,7 @@ func TestValidateGraphApplyPlanAcceptsNewFields(t *testing.T) {
|
|||
},
|
||||
},
|
||||
}
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Fatalf("unexpected validation error: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -115,7 +117,7 @@ func TestValidateGraphApplyPlanRejectsNegativeEstimate(t *testing.T) {
|
|||
{Key: "n", Title: "Node", Estimate: &neg},
|
||||
},
|
||||
}
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative estimate")
|
||||
}
|
||||
|
|
@ -132,7 +134,7 @@ func TestValidateGraphApplyPlanRejectsEmptyDepTarget(t *testing.T) {
|
|||
{Key: "n", Title: "Node", Deps: []GraphApplyNodeDep{{Target: ""}}},
|
||||
},
|
||||
}
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty dep target")
|
||||
}
|
||||
|
|
@ -150,7 +152,7 @@ func TestValidateGraphApplyPlanParentAliasResolvesCorrectly(t *testing.T) {
|
|||
{Key: "child", Title: "Child", Parent: "root"},
|
||||
},
|
||||
}
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Fatalf("parent alias should resolve: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -163,7 +165,7 @@ func TestValidateGraphApplyPlanParentAliasRejectsUnknownKey(t *testing.T) {
|
|||
{Key: "child", Title: "Child", Parent: "nonexistent"},
|
||||
},
|
||||
}
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unknown parent key via alias")
|
||||
}
|
||||
|
|
@ -401,7 +403,7 @@ func TestValidateGraphApplyPlanRejectsLocalBlockingCycle(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected local graph cycle to be rejected")
|
||||
}
|
||||
|
|
@ -424,7 +426,7 @@ func TestValidateGraphApplyPlanReportsDeterministicCycleNode(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected local graph cycle to be rejected")
|
||||
}
|
||||
|
|
@ -445,7 +447,7 @@ func TestValidateGraphApplyPlanAllowsNonBlockingLocalCycle(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Fatalf("non-blocking cycle rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -461,7 +463,7 @@ func TestValidateGraphApplyPlanRejectsImplicitParentChildReverseBlockingCycle(t
|
|||
},
|
||||
}
|
||||
|
||||
err := validateGraphApplyPlan(plan, nil)
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected implicit parent-child plus reverse blocking edge to be rejected")
|
||||
}
|
||||
|
|
@ -482,7 +484,7 @@ func TestValidateGraphApplyPlanIgnoresIDOverridesForLocalCycleValidation(t *test
|
|||
},
|
||||
}
|
||||
|
||||
if err := validateGraphApplyPlan(plan, nil); err != nil {
|
||||
if err := validateGraphApplyPlan(plan, nil, nil); err != nil {
|
||||
t.Fatalf("ID override edge should not be treated as a local key cycle: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -658,3 +660,184 @@ func TestCreateIssuesFromGraph_DryRunDoesNotPersist(t *testing.T) {
|
|||
t.Errorf("parent_deps = %d, want 1", result.ParentDeps)
|
||||
}
|
||||
}
|
||||
|
||||
// singleNodePlanErr validates a one-node plan built by mutate and returns the
|
||||
// validation error (nil when the plan is accepted).
|
||||
func singleNodePlanErr(customStatuses []string, mutate func(*GraphApplyNode)) error {
|
||||
node := GraphApplyNode{Key: "a", Title: "A"}
|
||||
mutate(&node)
|
||||
plan := &GraphApplyPlan{Nodes: []GraphApplyNode{node}}
|
||||
return validateGraphApplyPlan(plan, nil, customStatuses)
|
||||
}
|
||||
|
||||
func TestValidateGraphApplyPlanNodeFieldRules(t *testing.T) {
|
||||
neg := -5
|
||||
on := true
|
||||
cases := []struct {
|
||||
name string
|
||||
customStatuses []string
|
||||
mutate func(*GraphApplyNode)
|
||||
wantErr string
|
||||
}{
|
||||
{name: "invalid status", mutate: func(n *GraphApplyNode) { n.Status = "bogus" }, wantErr: "invalid status"},
|
||||
{name: "builtin status accepted", mutate: func(n *GraphApplyNode) { n.Status = "in_progress" }},
|
||||
{name: "custom status accepted", customStatuses: []string{"triage"}, mutate: func(n *GraphApplyNode) { n.Status = "triage" }},
|
||||
{name: "custom status rejected without config", mutate: func(n *GraphApplyNode) { n.Status = "triage" }, wantErr: "invalid status"},
|
||||
{name: "negative estimate", mutate: func(n *GraphApplyNode) { n.EstimatedMinutes = &neg }, wantErr: "estimated_minutes"},
|
||||
{name: "invalid wisp_type", mutate: func(n *GraphApplyNode) { n.WispType = "bogus" }, wantErr: "invalid wisp_type"},
|
||||
{name: "valid wisp_type", mutate: func(n *GraphApplyNode) { n.WispType = "heartbeat" }},
|
||||
{name: "invalid mol_type", mutate: func(n *GraphApplyNode) { n.MolType = "bogus" }, wantErr: "invalid mol_type"},
|
||||
{name: "valid mol_type", mutate: func(n *GraphApplyNode) { n.MolType = "swarm" }},
|
||||
{name: "event fields require event type", mutate: func(n *GraphApplyNode) { n.EventKind = "agent.started" }, wantErr: "require type"},
|
||||
{name: "event fields on event node", mutate: func(n *GraphApplyNode) {
|
||||
n.Type = "event"
|
||||
n.EventKind = "agent.started"
|
||||
n.Actor = "x"
|
||||
n.Target = "y"
|
||||
n.Payload = "{}"
|
||||
}},
|
||||
{name: "node-level ephemeral+no_history conflict", mutate: func(n *GraphApplyNode) { n.Ephemeral = &on; n.NoHistory = &on }, wantErr: "mutually exclusive"},
|
||||
{name: "bad explicit id format", mutate: func(n *GraphApplyNode) { n.ID = "nohyphen" }, wantErr: "invalid ID format"},
|
||||
{name: "valid explicit id", mutate: func(n *GraphApplyNode) { n.ID = "bd-a1b2c3" }},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := singleNodePlanErr(tc.customStatuses, tc.mutate)
|
||||
if tc.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected plan to validate, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateGraphApplyPlanRejectsDuplicateExplicitIDs(t *testing.T) {
|
||||
plan := &GraphApplyPlan{
|
||||
Nodes: []GraphApplyNode{
|
||||
{Key: "a", Title: "A", ID: "bd-a1b2c3"},
|
||||
{Key: "b", Title: "B", ID: "bd-a1b2c3"},
|
||||
},
|
||||
}
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "duplicate explicit id") {
|
||||
t.Fatalf("expected duplicate explicit id error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateGraphApplyPlanEdgeGateRules(t *testing.T) {
|
||||
twoNodes := []GraphApplyNode{
|
||||
{Key: "gate", Title: "Gate"},
|
||||
{Key: "spawner", Title: "Spawner"},
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
edge GraphApplyEdge
|
||||
wantErr string
|
||||
}{
|
||||
{name: "gate requires waits-for", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "blocks", Gate: "all-children"}, wantErr: "require type"},
|
||||
{name: "gate defaults-to-blocks edge rejected", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Gate: "all-children"}, wantErr: "require type"},
|
||||
{name: "invalid gate value", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", Gate: "bogus"}, wantErr: "invalid gate"},
|
||||
{name: "spawner_key and spawner_id conflict", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", SpawnerKey: "spawner", SpawnerID: "bd-x"}, wantErr: "cannot specify both"},
|
||||
{name: "unknown spawner_key", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", SpawnerKey: "ghost"}, wantErr: "spawner key"},
|
||||
{name: "valid gated waits-for edge", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", Gate: "any-children", SpawnerKey: "spawner"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
plan := &GraphApplyPlan{Nodes: twoNodes, Edges: []GraphApplyEdge{tc.edge}}
|
||||
err := validateGraphApplyPlan(plan, nil, nil)
|
||||
if tc.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected plan to validate, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphApplyEdgeDependencyGateMetadata(t *testing.T) {
|
||||
resolve := func(key string) string {
|
||||
return map[string]string{"spawner": "bd-spawn1"}[key]
|
||||
}
|
||||
|
||||
t.Run("gate and spawner_key resolve into waits-for metadata", func(t *testing.T) {
|
||||
edge := GraphApplyEdge{Type: "waits-for", Gate: "any-children", SpawnerKey: "spawner"}
|
||||
dep, err := graphApplyEdgeDependency(edge, "bd-from", "bd-to", "waits-for", resolve)
|
||||
if err != nil {
|
||||
t.Fatalf("graphApplyEdgeDependency: %v", err)
|
||||
}
|
||||
var meta types.WaitsForMeta
|
||||
if err := json.Unmarshal([]byte(dep.Metadata), &meta); err != nil {
|
||||
t.Fatalf("metadata not valid WaitsForMeta JSON: %v", err)
|
||||
}
|
||||
if meta.Gate != types.WaitsForAnyChildren || meta.SpawnerID != "bd-spawn1" {
|
||||
t.Errorf("meta = %+v, want any-children gate with resolved spawner", meta)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("gate defaults to all-children when spawner is set", func(t *testing.T) {
|
||||
edge := GraphApplyEdge{Type: "waits-for", SpawnerID: "bd-ext1"}
|
||||
dep, err := graphApplyEdgeDependency(edge, "bd-from", "bd-to", "waits-for", resolve)
|
||||
if err != nil {
|
||||
t.Fatalf("graphApplyEdgeDependency: %v", err)
|
||||
}
|
||||
var meta types.WaitsForMeta
|
||||
if err := json.Unmarshal([]byte(dep.Metadata), &meta); err != nil {
|
||||
t.Fatalf("metadata not valid WaitsForMeta JSON: %v", err)
|
||||
}
|
||||
if meta.Gate != types.WaitsForAllChildren || meta.SpawnerID != "bd-ext1" {
|
||||
t.Errorf("meta = %+v, want all-children default with explicit spawner", meta)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("plain edge carries no metadata and passes thread_id", func(t *testing.T) {
|
||||
edge := GraphApplyEdge{Type: "replies-to", ThreadID: "thread-9"}
|
||||
dep, err := graphApplyEdgeDependency(edge, "bd-from", "bd-to", "replies-to", resolve)
|
||||
if err != nil {
|
||||
t.Fatalf("graphApplyEdgeDependency: %v", err)
|
||||
}
|
||||
if dep.Metadata != "" {
|
||||
t.Errorf("Metadata = %q, want empty for ungated edge", dep.Metadata)
|
||||
}
|
||||
if dep.ThreadID != "thread-9" {
|
||||
t.Errorf("ThreadID = %q, want thread-9", dep.ThreadID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestGraphApplyNodeCoversCreateIssueParams pins full issue-model parity
|
||||
// between single-issue `bd create` and graph plans: every createIssueParams
|
||||
// field must be addressable from a GraphApplyNode or listed here with a
|
||||
// reason. This keeps the schema gap from silently reopening as create grows.
|
||||
func TestGraphApplyNodeCoversCreateIssueParams(t *testing.T) {
|
||||
renamed := map[string]string{
|
||||
"IssueType": "Type",
|
||||
"InitialStatus": "Status",
|
||||
}
|
||||
excluded := map[string]string{
|
||||
"CreatedBy": "always the ambient actor identity; plans do not impersonate creators",
|
||||
}
|
||||
|
||||
nodeType := reflect.TypeOf(GraphApplyNode{})
|
||||
paramsType := reflect.TypeOf(createIssueParams{})
|
||||
for i := 0; i < paramsType.NumField(); i++ {
|
||||
name := paramsType.Field(i).Name
|
||||
if _, ok := excluded[name]; ok {
|
||||
continue
|
||||
}
|
||||
if alias, ok := renamed[name]; ok {
|
||||
name = alias
|
||||
}
|
||||
if _, ok := nodeType.FieldByName(name); !ok {
|
||||
t.Errorf("createIssueParams field %q is not addressable from graph plans; add it to GraphApplyNode (or the exclusion list with a reason)", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -519,6 +519,83 @@ bd create [title] [flags]
|
|||
--wisp-type string Wisp type for TTL-based compaction: heartbeat, ping, patrol, gc_report, recovery, error, escalation
|
||||
```
|
||||
|
||||
**Graph plan schema (`--graph`):**
|
||||
|
||||
`bd create --graph plan.json` creates a whole issue graph atomically from a
|
||||
JSON plan. Node field names follow the issue model's JSON tags (the same
|
||||
names `bd show --json` emits), so every native field except comments is
|
||||
addressable from a plan:
|
||||
|
||||
```json
|
||||
{
|
||||
"commit_message": "optional Dolt commit message",
|
||||
"nodes": [
|
||||
{
|
||||
"key": "api",
|
||||
"title": "Design the API",
|
||||
"type": "task",
|
||||
"description": "…", "design": "…", "acceptance_criteria": "…", "notes": "…",
|
||||
"status": "in_progress",
|
||||
"priority": 1,
|
||||
"assignee": "alice", "assign_after_create": false,
|
||||
"owner": "alice@example.com",
|
||||
"labels": ["backend"],
|
||||
"estimated_minutes": 45,
|
||||
"due_at": "2030-01-02T15:04:05Z",
|
||||
"defer_until": "2030-01-01T00:00:00Z",
|
||||
"spec_id": "bd-spec1", "external_ref": "gh-42",
|
||||
"metadata": {"any": "json", "count": 3},
|
||||
"metadata_refs": {"tracker": "impl"},
|
||||
"id": "bd-a1b2c3",
|
||||
"ephemeral": false, "no_history": false,
|
||||
"wisp_type": "heartbeat", "mol_type": "swarm",
|
||||
"pinned": false,
|
||||
"event_kind": "agent.started", "actor": "agent://a", "target": "bead://b", "payload": "{}"
|
||||
},
|
||||
{ "key": "impl", "title": "Implement it", "parent_key": "api" }
|
||||
],
|
||||
"edges": [
|
||||
{ "from_key": "impl", "to_key": "api", "type": "blocks" },
|
||||
{ "from_key": "api", "to_key": "impl", "type": "waits-for",
|
||||
"gate": "any-children", "spawner_key": "impl" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Node notes:
|
||||
|
||||
- `key` is a plan-local symbolic name; the result maps each key to the minted
|
||||
issue ID. `id` optionally pins an explicit issue ID instead (must match the
|
||||
database prefix, like `bd create --id`).
|
||||
- `parent_key` (a plan node key) or `parent_id` (an existing issue ID) adds a
|
||||
`parent-child` dependency on the created node.
|
||||
- `status` sets the initial status (default `open`, or `deferred` when
|
||||
`defer_until` is in the future). Nodes created `closed` get `closed_at`
|
||||
auto-filled. Timestamps are RFC3339; relative forms like `+6h` are not
|
||||
accepted in plans.
|
||||
- `ephemeral` / `no_history` override the plan-wide `--ephemeral` /
|
||||
`--no-history` flags per node (mutually exclusive per node; in
|
||||
proxied-server mode the effective storage class must be uniform across the
|
||||
plan).
|
||||
- `event_kind`, `actor`, `target`, and `payload` require `"type": "event"`.
|
||||
- `metadata` accepts arbitrary JSON values; `metadata_refs` values name other
|
||||
node keys and are replaced with their minted IDs after creation.
|
||||
- Unlike `bd create --parent`, graph children do not inherit parent labels
|
||||
and receive flat (non-hierarchical) IDs; plans are explicit artifacts.
|
||||
|
||||
Edge notes:
|
||||
|
||||
- `type` defaults to `blocks`. `parent_key`/`parent_id` on nodes already
|
||||
create `parent-child` edges; don't repeat them in `edges`.
|
||||
- `gate` (`all-children` | `any-children`) and `spawner_key`/`spawner_id`
|
||||
attach fanout-gate metadata to `waits-for` edges, mirroring
|
||||
`--waits-for`/`--waits-for-gate`. `spawner_key` references a plan node;
|
||||
`spawner_id` an existing issue.
|
||||
- `thread_id` threads conversation edges (e.g. `replies-to`).
|
||||
|
||||
Comments are the one model surface a plan cannot create; use `bd comments add`
|
||||
after creation.
|
||||
|
||||
### bd create-form
|
||||
|
||||
Create a new issue using an interactive terminal form.
|
||||
|
|
|
|||
|
|
@ -189,6 +189,13 @@ type GraphEdge struct {
|
|||
ToKey string
|
||||
ToID string
|
||||
Type types.DependencyType
|
||||
// Gate and spawner describe fanout-gate metadata for waits-for edges;
|
||||
// SpawnerKey references a plan-local node and is resolved after IDs mint.
|
||||
Gate string
|
||||
SpawnerKey string
|
||||
SpawnerID string
|
||||
// ThreadID threads conversation edges (replies-to).
|
||||
ThreadID string
|
||||
}
|
||||
|
||||
type GraphApplyResult struct {
|
||||
|
|
@ -800,7 +807,7 @@ func (u *issueUseCaseImpl) applyGraph(ctx context.Context, plan GraphPlan, actor
|
|||
if len(node.MetadataRefs) == 0 {
|
||||
continue
|
||||
}
|
||||
merged := make(map[string]string, len(node.MetadataRefs))
|
||||
merged := make(map[string]json.RawMessage, len(node.MetadataRefs))
|
||||
if len(node.Issue.Metadata) > 0 {
|
||||
if err := json.Unmarshal(node.Issue.Metadata, &merged); err != nil {
|
||||
return GraphApplyResult{}, fmt.Errorf("applyGraph: node %q: re-parsing metadata: %w", node.Key, err)
|
||||
|
|
@ -811,7 +818,11 @@ func (u *issueUseCaseImpl) applyGraph(ctx context.Context, plan GraphPlan, actor
|
|||
if !ok {
|
||||
return GraphApplyResult{}, fmt.Errorf("applyGraph: node %q: metadata_ref %q references unknown key %q", node.Key, metaKey, refKey)
|
||||
}
|
||||
merged[metaKey] = resolvedID
|
||||
idJSON, err := json.Marshal(resolvedID)
|
||||
if err != nil {
|
||||
return GraphApplyResult{}, fmt.Errorf("applyGraph: node %q: marshaling metadata ref %q: %w", node.Key, metaKey, err)
|
||||
}
|
||||
merged[metaKey] = idJSON
|
||||
}
|
||||
metaJSON, err := json.Marshal(merged)
|
||||
if err != nil {
|
||||
|
|
@ -925,6 +936,26 @@ func (u *issueUseCaseImpl) applyGraph(ctx context.Context, plan GraphPlan, actor
|
|||
IssueID: fromID,
|
||||
DependsOnID: toID,
|
||||
Type: depType,
|
||||
ThreadID: edge.ThreadID,
|
||||
}
|
||||
if edge.Gate != "" || edge.SpawnerKey != "" || edge.SpawnerID != "" {
|
||||
gate := edge.Gate
|
||||
if gate == "" {
|
||||
gate = types.WaitsForAllChildren
|
||||
}
|
||||
spawnerID := edge.SpawnerID
|
||||
if edge.SpawnerKey != "" {
|
||||
resolved, ok := keyToID[edge.SpawnerKey]
|
||||
if !ok {
|
||||
return GraphApplyResult{}, fmt.Errorf("applyGraph: edge %d references undefined spawner_key %q", i, edge.SpawnerKey)
|
||||
}
|
||||
spawnerID = resolved
|
||||
}
|
||||
metaBytes, err := json.Marshal(types.WaitsForMeta{Gate: gate, SpawnerID: spawnerID})
|
||||
if err != nil {
|
||||
return GraphApplyResult{}, fmt.Errorf("applyGraph: edge %d: serializing waits-for metadata: %w", i, err)
|
||||
}
|
||||
dep.Metadata = string(metaBytes)
|
||||
}
|
||||
if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{UseWispsTable: useWisp}); err != nil {
|
||||
return GraphApplyResult{}, fmt.Errorf("applyGraph: edge %d (%s -> %s): %w", i, fromID, toID, err)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue