caelum0x 49b183818c Unify gitgram + aitimemachine into the monorepo (de-submodule) and merge vendored engines
Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as
opaque submodule gitlinks on GitHub) into fully-tracked first-party content.

AITM now merges its 7 vendored repos as first-party engines:
- memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts
- git: vendored C git (bundled binary) + gitnexus (in-process code intelligence)
- agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess)

Includes the full session's product build: Gitgram web/mobile/backend features,
AITM website/CLI/MCP, the unified memory layer, engine build tooling
(scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md),
and extensive test suites.

Build artifacts, node_modules, external/, and gemini-cli are gitignored.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 14:14:09 +03:00

279 lines
9.3 KiB
Go

package issueops
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// IsAllowedUpdateField checks if a field name is valid for issue updates.
func IsAllowedUpdateField(key string) bool {
allowed := map[string]bool{
"status": true, "priority": true, "title": true, "assignee": true,
"description": true, "design": true, "acceptance_criteria": true, "notes": true,
"issue_type": true, "estimated_minutes": true, "external_ref": true, "spec_id": true,
"started_at": true,
"closed_at": true, "close_reason": true, "closed_by_session": true,
"source_repo": true,
"sender": true, "wisp": true, "wisp_type": true, "no_history": true, "pinned": true,
"mol_type": true,
"event_category": true, "event_actor": true, "event_target": true, "event_payload": true,
"due_at": true, "defer_until": true, "await_id": true, "waiters": true,
"metadata": true,
}
return allowed[key]
}
// ManageClosedAt auto-sets closed_at when closing or clears it when reopening.
func ManageClosedAt(oldIssue *types.Issue, updates map[string]interface{}, setClauses []string, args []interface{}) ([]string, []interface{}) {
statusVal, hasStatus := updates["status"]
_, hasExplicitClosedAt := updates["closed_at"]
if hasExplicitClosedAt || !hasStatus {
return setClauses, args
}
var newStatus string
switch v := statusVal.(type) {
case string:
newStatus = v
case types.Status:
newStatus = string(v)
default:
return setClauses, args
}
if newStatus == string(types.StatusClosed) {
now := time.Now().UTC()
setClauses = append(setClauses, "closed_at = ?")
args = append(args, now)
} else if oldIssue.Status == types.StatusClosed {
setClauses = append(setClauses, "closed_at = ?", "close_reason = ?")
args = append(args, nil, "")
}
return setClauses, args
}
// ManageStartedAt auto-sets started_at when transitioning to in_progress.
// If the issue already has a started_at, it is preserved (not overwritten).
func ManageStartedAt(oldIssue *types.Issue, updates map[string]interface{}, setClauses []string, args []interface{}) ([]string, []interface{}) {
statusVal, hasStatus := updates["status"]
_, hasExplicitStartedAt := updates["started_at"]
if hasExplicitStartedAt || !hasStatus {
return setClauses, args
}
var newStatus string
switch v := statusVal.(type) {
case string:
newStatus = v
case types.Status:
newStatus = string(v)
default:
return setClauses, args
}
if newStatus == string(types.StatusInProgress) && oldIssue.StartedAt == nil {
now := time.Now().UTC()
setClauses = append(setClauses, "started_at = ?")
args = append(args, now)
}
return setClauses, args
}
// DetermineEventType returns the appropriate event type for an update.
func DetermineEventType(oldIssue *types.Issue, updates map[string]interface{}) types.EventType {
statusVal, hasStatus := updates["status"]
if !hasStatus {
return types.EventUpdated
}
var newStatus string
switch v := statusVal.(type) {
case string:
newStatus = v
case types.Status:
newStatus = string(v)
default:
return types.EventUpdated
}
if newStatus == string(types.StatusClosed) {
return types.EventClosed
}
if oldIssue.Status == types.StatusClosed {
return types.EventReopened
}
return types.EventStatusChanged
}
// UpdateResult holds the result of an UpdateIssueInTx call.
type UpdateResult struct {
OldIssue *types.Issue
IsWisp bool
}
// UpdateIssueInTx performs the full update SQL logic within a transaction.
// It routes to the correct table (issues/wisps) automatically.
// The caller is responsible for Dolt versioning (DOLT_ADD/COMMIT) if needed.
//
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
func UpdateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) {
return updateIssueInTx(ctx, tx, id, updates, actor, true)
}
// UpdateIssueWithoutEventInTx applies normal update semantics without recording
// an intermediate event. Demotion uses this to preserve the historical event
// stream: create/update history is copied, then a single demotion event is added.
func UpdateIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) {
return updateIssueInTx(ctx, tx, id, updates, actor, false)
}
func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string, recordEvent bool) (*UpdateResult, error) {
// Route to correct table.
isWisp := IsActiveWispInTx(ctx, tx, id)
issueTable, _, eventTable, _ := WispTableRouting(isWisp)
// Read old issue inside the transaction for consistency.
oldIssue, err := GetIssueInTx(ctx, tx, id)
if err != nil {
return nil, fmt.Errorf("failed to get issue for update: %w", err)
}
// Validate issue_type against built-in + custom types (GH#3030).
// This mirrors the create path (PrepareIssueForInsert → ValidateWithCustom)
// and reads custom types from the same transaction, so it works reliably
// even in subprocess contexts where the CLI-level store may be unavailable.
if rawType, ok := updates["issue_type"]; ok {
if issueType, ok := rawType.(string); ok {
customTypes, err := ResolveCustomTypesInTx(ctx, tx)
if err != nil {
return nil, fmt.Errorf("failed to get custom types for validation: %w", err)
}
if !types.IssueType(issueType).IsValidWithCustom(customTypes) {
return nil, fmt.Errorf("invalid issue type: %s", issueType)
}
}
}
// Build SET clauses.
setClauses := []string{"updated_at = ?"}
args := []interface{}{time.Now().UTC()}
for key, value := range updates {
if !IsAllowedUpdateField(key) {
return nil, fmt.Errorf("invalid field for update: %s", key)
}
columnName := key
if key == "wisp" {
columnName = "ephemeral"
}
setClauses = append(setClauses, fmt.Sprintf("`%s` = ?", columnName))
// Handle JSON serialization for array fields stored as TEXT.
if key == "waiters" {
waitersJSON, _ := json.Marshal(value)
args = append(args, string(waitersJSON))
} else if key == "metadata" {
metadataStr, err := storage.NormalizeMetadataValue(value)
if err != nil {
return nil, fmt.Errorf("invalid metadata: %w", err)
}
args = append(args, metadataStr)
} else {
args = append(args, value)
}
}
// Auto-clear pinned column when status transitions away from "pinned".
if rawStatus, ok := updates["status"]; ok {
var statusStr string
switch v := rawStatus.(type) {
case string:
statusStr = v
case types.Status:
statusStr = string(v)
}
if oldIssue.Pinned && statusStr != string(types.StatusPinned) {
if _, alreadySet := updates["pinned"]; !alreadySet {
setClauses = append(setClauses, "`pinned` = ?")
args = append(args, false)
}
}
}
// Auto-manage closed_at (set on close, clear on reopen).
setClauses, args = ManageClosedAt(oldIssue, updates, setClauses, args)
// Auto-manage started_at (set on transition to in_progress). (GH#2796)
setClauses, args = ManageStartedAt(oldIssue, updates, setClauses, args)
args = append(args, id)
//nolint:gosec // G201: issueTable comes from WispTableRouting (hardcoded constants)
query := fmt.Sprintf("UPDATE %s SET %s WHERE id = ?", issueTable, strings.Join(setClauses, ", "))
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return nil, fmt.Errorf("failed to update issue: %w", err)
}
if recordEvent {
oldData, _ := json.Marshal(oldIssue)
newData, _ := json.Marshal(updates)
eventType := DetermineEventType(oldIssue, updates)
if err := RecordFullEventInTable(ctx, tx, eventTable, id, eventType, actor, string(oldData), string(newData)); err != nil {
return nil, fmt.Errorf("failed to record event: %w", err)
}
}
if rawStatus, hasStatus := updates["status"]; hasStatus {
var newStatus string
switch v := rawStatus.(type) {
case string:
newStatus = v
case types.Status:
newStatus = string(v)
}
oldActive := oldIssue.Status != types.StatusClosed && oldIssue.Status != types.StatusPinned
newActive := newStatus != string(types.StatusClosed) && newStatus != string(types.StatusPinned)
if oldActive != newActive {
var affectedIssues, affectedWisps []string
var aerr error
if isWisp {
affectedIssues, affectedWisps, aerr = AffectedByStatusChangeForWispInTx(ctx, tx, id)
} else {
affectedIssues, affectedWisps, aerr = AffectedByStatusChangeInTx(ctx, tx, id)
}
if aerr != nil {
return nil, fmt.Errorf("affected by status change for %s: %w", id, aerr)
}
if err := RecomputeIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil {
return nil, fmt.Errorf("recompute is_blocked after status change for %s: %w", id, err)
}
}
}
return &UpdateResult{OldIssue: oldIssue, IsWisp: isWisp}, nil
}
// RecordFullEventInTable records an event with both old and new values.
//
//nolint:gosec // G201: table is from WispTableRouting ("events" or "wisp_events")
func RecordFullEventInTable(ctx context.Context, tx DBTX, table, issueID string, eventType types.EventType, actor, oldValue, newValue string) error {
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (id, issue_id, event_type, actor, old_value, new_value)
VALUES (?, ?, ?, ?, ?, ?)
`, table), NewEventID(), issueID, eventType, actor, oldValue, newValue)
if err != nil {
return fmt.Errorf("record event in %s: %w", table, err)
}
return nil
}