From c7e8c6db3a616120e3d270fe493b3e3f8342e23d Mon Sep 17 00:00:00 2001 From: anandh8x Date: Mon, 8 Jun 2026 18:06:10 +0530 Subject: [PATCH] Add spec mode foundation --- internal/agent/loop.go | 47 +++++++- internal/agent/loop_test.go | 114 ++++++++++++++++++ internal/agent/system_prompt.go | 5 +- internal/agent/types.go | 15 ++- internal/cli/sessions.go | 53 ++++++++ internal/cli/sessions_test.go | 45 +++++++ internal/sessions/store.go | 154 +++++++++++++++++++++++- internal/sessions/store_test.go | 55 +++++++++ internal/specialist/manifest.go | 1 + internal/specmode/exit_tool.go | 108 +++++++++++++++++ internal/specmode/prompt.go | 32 +++++ internal/specmode/registry.go | 14 +++ internal/specmode/slug.go | 33 +++++ internal/specmode/spec.go | 89 ++++++++++++++ internal/specmode/specmode_test.go | 96 +++++++++++++++ internal/tools/ask_user_test.go | 15 ++- internal/tools/registry.go | 5 +- internal/tools/registry_test.go | 4 +- internal/zerocommands/contracts.go | 18 +++ internal/zerocommands/contracts_test.go | 29 +++++ 20 files changed, 916 insertions(+), 16 deletions(-) create mode 100644 internal/specmode/exit_tool.go create mode 100644 internal/specmode/prompt.go create mode 100644 internal/specmode/registry.go create mode 100644 internal/specmode/slug.go create mode 100644 internal/specmode/spec.go create mode 100644 internal/specmode/specmode_test.go diff --git a/internal/agent/loop.go b/internal/agent/loop.go index 0d1b18de4..01e9757f0 100644 --- a/internal/agent/loop.go +++ b/internal/agent/loop.go @@ -15,6 +15,11 @@ import ( const maxTurnsAnswer = "Agent reached maximum number of turns without a final answer." +const ( + toolResultMetaControl = "control" + toolResultControlSpecReview = "spec_review_required" +) + // abortedToolResultNotice is the placeholder tool result recorded for a tool // call that was advertised by the assistant turn but never executed because the // repeated-failure guard halted the run first. It keeps every tool_use paired @@ -214,6 +219,13 @@ func Run(ctx context.Context, prompt string, provider Provider, options Options) result.Messages = copyMessages(messages) return result, abortErr } + if stopReason := stopReasonFromToolResult(toolResult); stopReason != "" { + messages = appendAbortedToolResults(messages, collected.ToolCalls[index+1:]) + result.FinalAnswer = toolResult.Output + result.StopReason = stopReason + result.Messages = copyMessages(messages) + return result, nil + } // Repeated-failure guard: if a tool keeps failing the same way, hint // once (with its schema) then halt — so no model loops on a bad call. @@ -312,6 +324,16 @@ func executeToolCall(ctx context.Context, registry *tools.Registry, call ToolCal DenialReason: DenialFiltered, }, nil } + tool, toolFound := registry.Get(call.Name) + if permissionMode == PermissionModeSpecDraft && toolFound && !ToolAdvertised(tool, permissionMode) { + return ToolResult{ + ToolCallID: call.ID, + Name: call.Name, + Status: tools.StatusError, + Output: `Error: Tool "` + call.Name + `" is not available in spec-draft mode.`, + DenialReason: DenialFiltered, + }, nil + } // ask_user is intercepted in the loop (like permissions) so the question can // be routed to an interactive front-end instead of blocking inside the tool. @@ -320,7 +342,6 @@ func executeToolCall(ctx context.Context, registry *tools.Registry, call ToolCal return executeAskUser(ctx, registry, call, args, permissionMode, options) } - tool, toolFound := registry.Get(call.Name) permissionGranted := permissionMode == PermissionModeUnsafe if toolFound && tool.Safety().Permission == tools.PermissionAllow { permissionGranted = true @@ -886,12 +907,36 @@ func ToolAdvertised(tool tools.Tool, permissionMode PermissionMode) bool { if tool.Safety().Permission == tools.PermissionDeny { return false } + if permissionMode == PermissionModeSpecDraft { + return toolAdvertisedInSpecDraft(tool) + } if permissionMode == PermissionModeAuto { return tool.Safety().Permission == tools.PermissionAllow || tool.Safety().AdvertiseInAuto } return true } +func toolAdvertisedInSpecDraft(tool tools.Tool) bool { + switch tool.Name() { + case "ask_user", "ExitSpecMode": + return true + case "update_plan": + return false + } + safety := tool.Safety() + return safety.SideEffect == tools.SideEffectRead && safety.Permission == tools.PermissionAllow +} + +func stopReasonFromToolResult(result ToolResult) StopReason { + if result.Meta == nil { + return "" + } + if result.Meta[toolResultMetaControl] == toolResultControlSpecReview { + return StopReasonSpecReviewRequired + } + return "" +} + // appendAbortedToolResults adds a placeholder tool-result message for each of // the given (unexecuted) tool calls, so every advertised tool_use keeps a // matching tool_result when the loop halts a turn before all calls have run. diff --git a/internal/agent/loop_test.go b/internal/agent/loop_test.go index 77d19a9ff..e0e47479e 100644 --- a/internal/agent/loop_test.go +++ b/internal/agent/loop_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/Gitlawb/zero/internal/sandbox" + "github.com/Gitlawb/zero/internal/specmode" "github.com/Gitlawb/zero/internal/tools" "github.com/Gitlawb/zero/internal/zeroruntime" ) @@ -856,6 +857,119 @@ func TestBuildSystemPromptInjectsWorkspaceContext(t *testing.T) { } } +func TestBuildSystemPromptAllowsSpecModeOverride(t *testing.T) { + prompt := buildSystemPrompt(Options{SystemPrompt: specmode.DraftSystemPrompt}) + if !strings.HasPrefix(prompt, "Spec mode is active.") { + t.Fatalf("expected spec prompt override, got %q", prompt) + } + if !strings.Contains(prompt, "Confirmation Modes") { + t.Fatalf("expected confirmation policy to remain appended") + } +} + +func TestSpecDraftAdvertisesOnlySafeDraftTools(t *testing.T) { + root := t.TempDir() + registry := tools.NewRegistry() + for _, tool := range tools.CoreTools(root) { + registry.Register(tool) + } + specmode.RegisterDraftTools(registry, root, nil) + provider := &mockProvider{ + turns: [][]zeroruntime.StreamEvent{{ + {Type: zeroruntime.StreamEventText, Content: "done"}, + {Type: zeroruntime.StreamEventDone}, + }}, + } + + _, err := Run(context.Background(), "draft", provider, Options{ + Registry: registry, + PermissionMode: PermissionModeSpecDraft, + }) + if err != nil { + t.Fatal(err) + } + names := map[string]bool{} + for _, definition := range provider.requests[0].Tools { + names[definition.Name] = true + } + for _, want := range []string{"read_file", "list_directory", "glob", "grep", "skill", "ask_user", specmode.ExitToolName} { + if !names[want] { + t.Fatalf("spec draft tools missing %q from %#v", want, names) + } + } + for _, denied := range []string{"write_file", "edit_file", "apply_patch", "bash", "update_plan", "web_fetch"} { + if names[denied] { + t.Fatalf("spec draft advertised denied tool %q in %#v", denied, names) + } + } +} + +func TestSpecDraftDeniesHiddenToolCalls(t *testing.T) { + root := t.TempDir() + registry := tools.NewRegistry() + registry.Register(tools.NewWriteFileTool(root)) + provider := providerCallingWriteFileThenAnswer("done") + + result, err := Run(context.Background(), "draft", provider, Options{ + Registry: registry, + PermissionMode: PermissionModeSpecDraft, + MaxTurns: 2, + }) + + if err != nil { + t.Fatal(err) + } + if result.FinalAnswer != "done" { + t.Fatalf("expected final answer after denial, got %q", result.FinalAnswer) + } + var denied string + for _, message := range result.Messages { + if message.Role == zeroruntime.MessageRoleTool { + denied = message.Content + break + } + } + if !strings.Contains(denied, "not available in spec-draft mode") { + t.Fatalf("expected spec-draft denial, got %q", denied) + } + if _, err := os.Stat(filepath.Join(root, "notes.txt")); !os.IsNotExist(err) { + t.Fatalf("write_file should not have written notes.txt, stat err=%v", err) + } +} + +func TestRunStopsWhenExitSpecModeReturnsReviewControl(t *testing.T) { + root := t.TempDir() + registry := tools.NewRegistry() + specmode.RegisterDraftTools(registry, root, nil) + provider := &mockProvider{ + turns: [][]zeroruntime.StreamEvent{{ + {Type: zeroruntime.StreamEventToolCallStart, ToolCallID: "exit-1", ToolName: specmode.ExitToolName}, + {Type: zeroruntime.StreamEventToolCallDelta, ToolCallID: "exit-1", ArgumentsFragment: `{"title":"Spec Mode","plan":"# Goal\n\nAdd spec mode."}`}, + {Type: zeroruntime.StreamEventToolCallEnd, ToolCallID: "exit-1"}, + {Type: zeroruntime.StreamEventDone}, + }}, + } + + result, err := Run(context.Background(), "draft", provider, Options{ + Registry: registry, + PermissionMode: PermissionModeSpecDraft, + MaxTurns: 3, + }) + + if err != nil { + t.Fatal(err) + } + if result.StopReason != StopReasonSpecReviewRequired { + t.Fatalf("StopReason = %q, want %q", result.StopReason, StopReasonSpecReviewRequired) + } + if len(provider.requests) != 1 { + t.Fatalf("expected run to stop after ExitSpecMode, got %d requests", len(provider.requests)) + } + if !strings.Contains(result.FinalAnswer, ".zero/specs/") { + t.Fatalf("final answer should mention saved spec, got %q", result.FinalAnswer) + } +} + func assertMessage(t *testing.T, message zeroruntime.Message, role zeroruntime.MessageRole, contentContains string) { t.Helper() diff --git a/internal/agent/system_prompt.go b/internal/agent/system_prompt.go index 331cb8c23..5b8b8a966 100644 --- a/internal/agent/system_prompt.go +++ b/internal/agent/system_prompt.go @@ -39,7 +39,10 @@ const maxProjectContextBytes = 8 << 10 // 8 KiB // guidelines), and the safety confirmation policy. It is built once per run so // every turn shares one (cacheable) system turn. func buildSystemPrompt(options Options) string { - core := strings.TrimSpace(coreSystemPrompt) + core := strings.TrimSpace(options.SystemPrompt) + if core == "" { + core = strings.TrimSpace(coreSystemPrompt) + } if core == "" { core = fallbackSystemPrompt } diff --git a/internal/agent/types.go b/internal/agent/types.go index 3f33ed65d..082262f18 100644 --- a/internal/agent/types.go +++ b/internal/agent/types.go @@ -18,9 +18,16 @@ type PermissionAction string type PermissionDecisionAction string const ( - PermissionModeAuto PermissionMode = "auto" - PermissionModeAsk PermissionMode = "ask" - PermissionModeUnsafe PermissionMode = "unsafe" + PermissionModeAuto PermissionMode = "auto" + PermissionModeAsk PermissionMode = "ask" + PermissionModeUnsafe PermissionMode = "unsafe" + PermissionModeSpecDraft PermissionMode = "spec-draft" +) + +type StopReason string + +const ( + StopReasonSpecReviewRequired StopReason = "spec_review_required" ) const ( @@ -129,6 +136,7 @@ type Options struct { Model string ReasoningEffort string Cwd string + SystemPrompt string // ContextWindow is the model's maximum input token budget. When > 0 the agent // loop compacts long conversations once the estimated size crosses a fraction // of this window. 0 DISABLES compaction entirely (every existing caller/test @@ -160,4 +168,5 @@ type Result struct { FinalAnswer string Turns int Messages []Message + StopReason StopReason } diff --git a/internal/cli/sessions.go b/internal/cli/sessions.go index 42bf009f2..10cd5fbe8 100644 --- a/internal/cli/sessions.go +++ b/internal/cli/sessions.go @@ -12,6 +12,7 @@ import ( type sessionCommandOptions struct { json bool + kind sessions.SessionKind sequence int eventID string excludeTarget bool @@ -90,8 +91,26 @@ func parseSessionsArgs(args []string) (string, []string, sessionCommandOptions, options.json = true case "--exclude-target": options.excludeTarget = true + case "--kind": + value, next, err := nextFlagValue(args, index, arg) + if err != nil { + return command, remaining, options, false, err + } + kind, err := parseSessionKindFlag(value) + if err != nil { + return command, remaining, options, false, err + } + options.kind = kind + index = next default: switch { + case strings.HasPrefix(arg, "--kind="): + kind, err := parseSessionKindFlag(strings.TrimPrefix(arg, "--kind=")) + if err != nil { + return command, remaining, options, false, err + } + options.kind = kind + continue case arg == "--sequence": value, next, err := nextFlagValue(args, index, arg) if err != nil { @@ -194,6 +213,16 @@ func parseNonEmptySessionsFlag(flag string, value string) (string, error) { return trimmed, nil } +func parseSessionKindFlag(value string) (sessions.SessionKind, error) { + kind := sessions.SessionKind(strings.ToLower(strings.TrimSpace(value))) + switch kind { + case sessions.SessionKindFork, sessions.SessionKindChild, sessions.SessionKindSpecDraft, sessions.SessionKindSpecImpl: + return kind, nil + default: + return "", execUsageError{fmt.Sprintf("invalid --kind %q. Expected fork, child, spec-draft, or spec-impl.", value)} + } +} + func isSessionsCommand(command string) bool { switch command { case "list", "children", "lineage", "tree", "rewind-plan", "rewind", "compact-plan": @@ -204,6 +233,9 @@ func isSessionsCommand(command string) bool { } func validateSessionCommandFlags(command string, options sessionCommandOptions) error { + if options.kind != "" && command != "list" { + return execUsageError{"--kind is only valid for sessions list"} + } hasRewindFlag := options.sequence > 0 || strings.TrimSpace(options.eventID) != "" || options.excludeTarget if hasRewindFlag && command != "rewind-plan" && command != "rewind" { return execUsageError{"--sequence, --event, and --exclude-target are only valid for sessions rewind-plan and rewind"} @@ -220,6 +252,7 @@ func runSessionsList(store *sessions.Store, options sessionCommandOptions, stdou if err != nil { return writeAppError(stderr, err.Error(), exitCrash) } + items = filterSessionsByKind(items, options.kind) if options.json { if err := writePrettyJSON(stdout, redaction.RedactValue(zerocommands.SessionSnapshots(items), redaction.Options{})); err != nil { return exitCrash @@ -232,6 +265,19 @@ func runSessionsList(store *sessions.Store, options sessionCommandOptions, stdou return exitSuccess } +func filterSessionsByKind(items []sessions.Metadata, kind sessions.SessionKind) []sessions.Metadata { + if kind == "" { + return items + } + filtered := make([]sessions.Metadata, 0, len(items)) + for _, item := range items { + if item.SessionKind == kind { + filtered = append(filtered, item) + } + } + return filtered +} + func runSessionsChildren(store *sessions.Store, sessionID string, options sessionCommandOptions, stdout io.Writer, stderr io.Writer) int { items, err := store.ListChildren(sessionID) if err != nil { @@ -446,6 +492,12 @@ func formatSessionSnapshotLine(session zerocommands.SessionSnapshot) string { if session.TaskID != "" { details = append(details, "task="+redact(session.TaskID)) } + if session.SpecStatus != "" { + details = append(details, "spec="+redact(session.SpecStatus)) + } + if session.SpecID != "" { + details = append(details, "spec_id="+redact(session.SpecID)) + } if session.Tag != "" { details = append(details, "tag="+redact(session.Tag)) } @@ -483,6 +535,7 @@ Commands: Flags: --json Print JSON output + --kind Filter list by fork, child, spec-draft, or spec-impl --sequence Rewind target sequence (rewind-plan, rewind) --event Rewind target event id (rewind-plan, rewind) --exclude-target Drop the target event (rewind-plan, rewind) diff --git a/internal/cli/sessions_test.go b/internal/cli/sessions_test.go index 04aa1e478..2fc766913 100644 --- a/internal/cli/sessions_test.go +++ b/internal/cli/sessions_test.go @@ -216,6 +216,51 @@ func TestRunSessionsValidatesArgs(t *testing.T) { } } +func TestRunSessionsListFiltersByKind(t *testing.T) { + store := sessions.NewStore(sessions.StoreOptions{RootDir: t.TempDir(), Now: sequenceClockCLI([]time.Time{ + time.Date(2026, 6, 8, 12, 0, 0, 0, time.UTC), + time.Date(2026, 6, 8, 12, 0, 1, 0, time.UTC), + })}) + if _, err := store.Create(sessions.CreateInput{SessionID: "regular", Title: "Regular"}); err != nil { + t.Fatal(err) + } + if _, err := store.Create(sessions.CreateInput{ + SessionID: "draft", + SessionKind: sessions.SessionKindSpecDraft, + Title: "Spec draft", + SpecID: "2026-06-08-spec-draft", + SpecStatus: sessions.SpecStatusDraft, + }); err != nil { + t.Fatal(err) + } + + var stdout bytes.Buffer + var stderr bytes.Buffer + exitCode := runWithDeps([]string{"sessions", "list", "--kind", "spec-draft"}, &stdout, &stderr, appDeps{ + newSessionStore: func() *sessions.Store { + return store + }, + }) + if exitCode != exitSuccess { + t.Fatalf("sessions list --kind exit = %d, stderr = %q", exitCode, stderr.String()) + } + output := stdout.String() + if !strings.Contains(output, "draft") || strings.Contains(output, "regular") || !strings.Contains(output, "spec=draft") { + t.Fatalf("filtered sessions output = %q", output) + } + + stdout.Reset() + stderr.Reset() + exitCode = runWithDeps([]string{"sessions", "tree", "draft", "--kind", "spec-draft"}, &stdout, &stderr, appDeps{ + newSessionStore: func() *sessions.Store { + return store + }, + }) + if exitCode != exitUsage || !strings.Contains(stderr.String(), "--kind is only valid for sessions list") { + t.Fatalf("expected --kind validation error, exit=%d stderr=%q", exitCode, stderr.String()) + } +} + func sequenceClockCLI(values []time.Time) func() time.Time { index := 0 return func() time.Time { diff --git a/internal/sessions/store.go b/internal/sessions/store.go index 81bffb216..a438892ab 100644 --- a/internal/sessions/store.go +++ b/internal/sessions/store.go @@ -39,13 +39,26 @@ const ( EventSessionChild EventType = "session_child" EventSpecialistStart EventType = "specialist_start" EventSpecialistStop EventType = "specialist_stop" + EventSpecDraft EventType = "spec_draft" + EventSpecApproved EventType = "spec_approved" + EventSpecRejected EventType = "spec_rejected" ) type SessionKind string const ( - SessionKindFork SessionKind = "fork" - SessionKindChild SessionKind = "child" + SessionKindFork SessionKind = "fork" + SessionKindChild SessionKind = "child" + SessionKindSpecDraft SessionKind = "spec-draft" + SessionKindSpecImpl SessionKind = "spec-impl" +) + +type SpecStatus string + +const ( + SpecStatusDraft SpecStatus = "draft" + SpecStatusApproved SpecStatus = "approved" + SpecStatusRejected SpecStatus = "rejected" ) type Metadata struct { @@ -65,6 +78,15 @@ type Metadata struct { ForkedFromSequence int `json:"forkedFromSequence,omitempty"` SpawnedFromEventID string `json:"spawnedFromEventId,omitempty"` SpawnedFromSequence int `json:"spawnedFromSequence,omitempty"` + SpecID string `json:"specId,omitempty"` + SpecFilePath string `json:"specFilePath,omitempty"` + SpecStatus SpecStatus `json:"specStatus,omitempty"` + SpecDraftModelID string `json:"specDraftModelId,omitempty"` + SpecDraftReasoning string `json:"specDraftReasoning,omitempty"` + SpecUserComment string `json:"specUserComment,omitempty"` + SpecRejectReason string `json:"specRejectReason,omitempty"` + SpecSourceSessionID string `json:"specSourceSessionId,omitempty"` + SpecImplSessionID string `json:"specImplSessionId,omitempty"` CreatedAt string `json:"createdAt"` UpdatedAt string `json:"updatedAt"` EventCount int `json:"eventCount"` @@ -88,6 +110,15 @@ type CreateInput struct { ForkedFromSequence int SpawnedFromEventID string SpawnedFromSequence int + SpecID string + SpecFilePath string + SpecStatus SpecStatus + SpecDraftModelID string + SpecDraftReasoning string + SpecUserComment string + SpecRejectReason string + SpecSourceSessionID string + SpecImplSessionID string } type ForkInput struct { @@ -121,6 +152,18 @@ type AppendEventInput struct { Payload any } +type RecordSpecInput struct { + SpecID string + SpecFilePath string + SpecStatus SpecStatus + SpecDraftModelID string + SpecDraftReasoning string + SpecUserComment string + SpecRejectReason string + SpecSourceSessionID string + SpecImplSessionID string +} + type Event struct { ID string `json:"id"` SessionID string `json:"sessionId"` @@ -216,6 +259,15 @@ func (store *Store) Create(input CreateInput) (Metadata, error) { ForkedFromSequence: input.ForkedFromSequence, SpawnedFromEventID: strings.TrimSpace(input.SpawnedFromEventID), SpawnedFromSequence: input.SpawnedFromSequence, + SpecID: strings.TrimSpace(input.SpecID), + SpecFilePath: strings.TrimSpace(input.SpecFilePath), + SpecStatus: normalizeSpecStatus(input.SpecStatus), + SpecDraftModelID: strings.TrimSpace(input.SpecDraftModelID), + SpecDraftReasoning: strings.TrimSpace(input.SpecDraftReasoning), + SpecUserComment: strings.TrimSpace(input.SpecUserComment), + SpecRejectReason: strings.TrimSpace(input.SpecRejectReason), + SpecSourceSessionID: strings.TrimSpace(input.SpecSourceSessionID), + SpecImplSessionID: strings.TrimSpace(input.SpecImplSessionID), CreatedAt: timestamp, UpdatedAt: timestamp, EventCount: 0, @@ -363,6 +415,52 @@ func (store *Store) Fork(parentSessionID string, input ForkInput) (Metadata, err return loaded, nil } +func (store *Store) RecordSpec(sessionID string, input RecordSpecInput) (Metadata, Event, error) { + if !ValidSessionID(sessionID) { + return Metadata{}, Event{}, fmt.Errorf("invalid zero session id %q", sessionID) + } + status := normalizeSpecStatus(input.SpecStatus) + if status == "" { + return Metadata{}, Event{}, fmt.Errorf("zero spec status is required") + } + unlock, err := store.lockSession(sessionID) + if err != nil { + return Metadata{}, Event{}, err + } + defer unlock() + + session, err := store.readMetadata(sessionID) + if err != nil { + return Metadata{}, Event{}, err + } + applySpecRecord(&session, input, status) + if err := store.writeMetadata(session); err != nil { + return Metadata{}, Event{}, err + } + event, err := store.appendEventLocked(sessionID, AppendEventInput{ + Type: specEventType(status), + Payload: map[string]any{ + "specId": session.SpecID, + "specFilePath": session.SpecFilePath, + "specStatus": session.SpecStatus, + "specDraftModelId": session.SpecDraftModelID, + "specDraftReasoning": session.SpecDraftReasoning, + "specUserComment": session.SpecUserComment, + "specRejectReason": session.SpecRejectReason, + "specSourceSessionId": session.SpecSourceSessionID, + "specImplSessionId": session.SpecImplSessionID, + }, + }) + if err != nil { + return Metadata{}, Event{}, err + } + loaded, err := store.readMetadata(sessionID) + if err != nil { + return Metadata{}, Event{}, err + } + return loaded, event, nil +} + func (store *Store) AppendEvent(sessionID string, input AppendEventInput) (Event, error) { if !ValidSessionID(sessionID) { return Event{}, fmt.Errorf("invalid zero session id %q", sessionID) @@ -577,3 +675,55 @@ func firstNonEmpty(values ...string) string { } return "" } + +func normalizeSpecStatus(status SpecStatus) SpecStatus { + switch SpecStatus(strings.ToLower(strings.TrimSpace(string(status)))) { + case SpecStatusDraft: + return SpecStatusDraft + case SpecStatusApproved: + return SpecStatusApproved + case SpecStatusRejected: + return SpecStatusRejected + default: + return "" + } +} + +func specEventType(status SpecStatus) EventType { + switch normalizeSpecStatus(status) { + case SpecStatusApproved: + return EventSpecApproved + case SpecStatusRejected: + return EventSpecRejected + default: + return EventSpecDraft + } +} + +func applySpecRecord(session *Metadata, input RecordSpecInput, status SpecStatus) { + if specID := strings.TrimSpace(input.SpecID); specID != "" { + session.SpecID = specID + } + if path := strings.TrimSpace(input.SpecFilePath); path != "" { + session.SpecFilePath = path + } + session.SpecStatus = status + if modelID := strings.TrimSpace(input.SpecDraftModelID); modelID != "" { + session.SpecDraftModelID = modelID + } + if reasoning := strings.TrimSpace(input.SpecDraftReasoning); reasoning != "" { + session.SpecDraftReasoning = reasoning + } + if comment := strings.TrimSpace(input.SpecUserComment); comment != "" { + session.SpecUserComment = comment + } + if reason := strings.TrimSpace(input.SpecRejectReason); reason != "" { + session.SpecRejectReason = reason + } + if sourceID := strings.TrimSpace(input.SpecSourceSessionID); sourceID != "" { + session.SpecSourceSessionID = sourceID + } + if implID := strings.TrimSpace(input.SpecImplSessionID); implID != "" { + session.SpecImplSessionID = implID + } +} diff --git a/internal/sessions/store_test.go b/internal/sessions/store_test.go index 5f5a7af0d..bb014b951 100644 --- a/internal/sessions/store_test.go +++ b/internal/sessions/store_test.go @@ -445,6 +445,61 @@ func TestPrepareExecWhitespaceResumeDoesNotFallbackToLatest(t *testing.T) { } } +func TestRecordSpecUpdatesMetadataAndAppendsEvents(t *testing.T) { + store := NewStore(StoreOptions{RootDir: t.TempDir(), Now: sequenceClock([]time.Time{ + time.Date(2026, 6, 8, 10, 0, 0, 0, time.UTC), + time.Date(2026, 6, 8, 10, 0, 1, 0, time.UTC), + time.Date(2026, 6, 8, 10, 0, 2, 0, time.UTC), + })}) + session, err := store.Create(CreateInput{ + SessionID: "draft", + SessionKind: SessionKindSpecDraft, + SpecDraftModelID: "gpt-5", + SpecDraftReasoning: "high", + }) + if err != nil { + t.Fatalf("Create returned error: %v", err) + } + + updated, event, err := store.RecordSpec(session.SessionID, RecordSpecInput{ + SpecID: "2026-06-08-spec-mode", + SpecFilePath: "/repo/.zero/specs/2026-06-08-spec-mode.md", + SpecStatus: SpecStatusDraft, + }) + + if err != nil { + t.Fatalf("RecordSpec returned error: %v", err) + } + if updated.SpecID != "2026-06-08-spec-mode" || updated.SpecStatus != SpecStatusDraft || updated.LastEventType != EventSpecDraft { + t.Fatalf("updated metadata = %#v", updated) + } + if event.Type != EventSpecDraft { + t.Fatalf("event type = %s, want %s", event.Type, EventSpecDraft) + } + + approved, event, err := store.RecordSpec(session.SessionID, RecordSpecInput{ + SpecStatus: SpecStatusApproved, + SpecUserComment: "ship it", + SpecImplSessionID: "impl", + }) + if err != nil { + t.Fatalf("RecordSpec approve returned error: %v", err) + } + if approved.SpecID != "2026-06-08-spec-mode" || approved.SpecStatus != SpecStatusApproved || approved.SpecUserComment != "ship it" || approved.SpecImplSessionID != "impl" { + t.Fatalf("approved metadata = %#v", approved) + } + if event.Type != EventSpecApproved { + t.Fatalf("event type = %s, want %s", event.Type, EventSpecApproved) + } + events, err := store.ReadEvents(session.SessionID) + if err != nil { + t.Fatal(err) + } + if len(events) != 2 { + t.Fatalf("expected two spec events, got %#v", events) + } +} + func fixedClock(value string) func() time.Time { parsed, err := time.Parse(time.RFC3339, value) if err != nil { diff --git a/internal/specialist/manifest.go b/internal/specialist/manifest.go index e9a3860bd..310e6252a 100644 --- a/internal/specialist/manifest.go +++ b/internal/specialist/manifest.go @@ -104,6 +104,7 @@ var knownToolNames = map[string]bool{ "glob": true, "grep": true, "skill": true, + "ask_user": true, "write_file": true, "edit_file": true, "apply_patch": true, diff --git a/internal/specmode/exit_tool.go b/internal/specmode/exit_tool.go new file mode 100644 index 000000000..1430370d1 --- /dev/null +++ b/internal/specmode/exit_tool.go @@ -0,0 +1,108 @@ +package specmode + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Gitlawb/zero/internal/tools" +) + +const ( + ExitToolName = "ExitSpecMode" + ControlSpecReviewRequired = "spec_review_required" +) + +type ExitTool struct { + workspaceRoot string + now func() time.Time +} + +func NewExitTool(workspaceRoot string, now func() time.Time) ExitTool { + return ExitTool{workspaceRoot: workspaceRoot, now: now} +} + +func (tool ExitTool) Name() string { + return ExitToolName +} + +func (tool ExitTool) Description() string { + return "Save the completed spec-mode markdown plan and stop for user review before implementation." +} + +func (tool ExitTool) Parameters() tools.Schema { + return tools.Schema{ + Type: "object", + Properties: map[string]tools.PropertySchema{ + "title": { + Type: "string", + Description: "Short 3-6 word title for the spec.", + }, + "plan": { + Type: "string", + Description: "Complete markdown implementation spec.", + }, + }, + Required: []string{"title", "plan"}, + AdditionalProperties: false, + } +} + +func (tool ExitTool) Safety() tools.Safety { + return tools.Safety{ + SideEffect: tools.SideEffectWrite, + Permission: tools.PermissionAllow, + Reason: "Writes a spec markdown file under the workspace .zero/specs directory and stops for review.", + } +} + +func (tool ExitTool) Run(_ context.Context, args map[string]any) tools.Result { + title, err := requiredString(args, "title") + if err != nil { + return tools.Result{Status: tools.StatusError, Output: "Error: Invalid arguments for ExitSpecMode: " + err.Error()} + } + plan, err := requiredString(args, "plan") + if err != nil { + return tools.Result{Status: tools.StatusError, Output: "Error: Invalid arguments for ExitSpecMode: " + err.Error()} + } + saved, err := SaveDraft(SaveOptions{ + WorkspaceRoot: tool.workspaceRoot, + Title: title, + Plan: plan, + Now: tool.now, + }) + if err != nil { + return tools.Result{Status: tools.StatusError, Output: "Error: Failed to save spec: " + err.Error()} + } + output := fmt.Sprintf("Spec saved for review: %s", saved.RelativePath) + return tools.Result{ + Status: tools.StatusOK, + Output: output, + Meta: map[string]string{ + "control": ControlSpecReviewRequired, + "specId": saved.ID, + "specTitle": saved.Title, + "specFilePath": saved.Path, + "relativePath": saved.RelativePath, + }, + ChangedFiles: []string{saved.RelativePath}, + Display: tools.Display{Summary: output, Kind: "file"}, + } +} + +func requiredString(args map[string]any, key string) (string, error) { + value, ok := args[key] + if !ok || value == nil { + return "", fmt.Errorf("%s is required", key) + } + text, ok := value.(string) + if !ok { + return "", fmt.Errorf("%s must be a string", key) + } + text = strings.TrimSpace(text) + if text == "" { + return "", fmt.Errorf("%s must be a non-empty string", key) + } + return text, nil +} diff --git a/internal/specmode/prompt.go b/internal/specmode/prompt.go new file mode 100644 index 000000000..1caeba2bc --- /dev/null +++ b/internal/specmode/prompt.go @@ -0,0 +1,32 @@ +package specmode + +const DraftSystemPrompt = `Spec mode is active. + +You are drafting an implementation spec, not changing files. + +Use read-only tools to inspect the workspace. You may use ask_user only when a +decision is genuinely blocking and cannot be resolved from the workspace or a +reasonable safe assumption. + +Do not write files, edit files, apply patches, run shell commands, spawn +specialists, or implement the requested change during spec mode. + +When you have enough context, call ExitSpecMode with: +- title: a short 3-6 word title +- plan: a complete markdown implementation spec + +The plan must choose one concrete approach. Do not leave unresolved choices such +as "Option A" and "Option B". If something remains uncertain, make the safest +reasonable assumption and state it clearly. If you cannot produce a concrete plan +after inspection and ask_user, call ExitSpecMode only with the best safe +assumption clearly stated. + +The spec must include: +- Goal +- Relevant files/components +- Proposed implementation steps +- Tests and verification +- Risks and edge cases +- Out of scope + +After calling ExitSpecMode, stop.` diff --git a/internal/specmode/registry.go b/internal/specmode/registry.go new file mode 100644 index 000000000..09000e789 --- /dev/null +++ b/internal/specmode/registry.go @@ -0,0 +1,14 @@ +package specmode + +import ( + "time" + + "github.com/Gitlawb/zero/internal/tools" +) + +func RegisterDraftTools(registry *tools.Registry, workspaceRoot string, now func() time.Time) { + if registry == nil { + return + } + registry.Register(NewExitTool(workspaceRoot, now)) +} diff --git a/internal/specmode/slug.go b/internal/specmode/slug.go new file mode 100644 index 000000000..1130b5c7b --- /dev/null +++ b/internal/specmode/slug.go @@ -0,0 +1,33 @@ +package specmode + +import ( + "strings" +) + +const maxSlugLength = 60 + +func slugify(value string) string { + value = strings.ToLower(strings.TrimSpace(value)) + var builder strings.Builder + lastDash := false + for _, char := range value { + switch { + case char >= 'a' && char <= 'z', char >= '0' && char <= '9': + builder.WriteRune(char) + lastDash = false + default: + if builder.Len() > 0 && !lastDash { + builder.WriteByte('-') + lastDash = true + } + } + if builder.Len() >= maxSlugLength { + break + } + } + slug := strings.Trim(builder.String(), "-") + if slug == "" { + return "spec" + } + return slug +} diff --git a/internal/specmode/spec.go b/internal/specmode/spec.go new file mode 100644 index 000000000..d6ecb337f --- /dev/null +++ b/internal/specmode/spec.go @@ -0,0 +1,89 @@ +package specmode + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +const ( + SpecDirName = ".zero/specs" +) + +type SaveOptions struct { + WorkspaceRoot string + Title string + Plan string + Now func() time.Time +} + +type SavedSpec struct { + ID string + Title string + Path string + RelativePath string +} + +func SaveDraft(options SaveOptions) (SavedSpec, error) { + root := strings.TrimSpace(options.WorkspaceRoot) + if root == "" { + return SavedSpec{}, fmt.Errorf("workspace root is required") + } + absoluteRoot, err := filepath.Abs(root) + if err != nil { + return SavedSpec{}, fmt.Errorf("resolve workspace root: %w", err) + } + title := strings.TrimSpace(options.Title) + if title == "" { + return SavedSpec{}, fmt.Errorf("title is required") + } + plan := strings.TrimSpace(options.Plan) + if plan == "" { + return SavedSpec{}, fmt.Errorf("plan is required") + } + now := options.Now + if now == nil { + now = time.Now + } + + date := now().UTC().Format("2006-01-02") + slug := slugify(title) + specDir := filepath.Join(absoluteRoot, filepath.FromSlash(SpecDirName)) + if err := os.MkdirAll(specDir, 0o755); err != nil { + return SavedSpec{}, fmt.Errorf("create spec directory: %w", err) + } + + for suffix := 0; suffix < 1000; suffix++ { + id := date + "-" + slug + if suffix > 0 { + id = fmt.Sprintf("%s-%s-%d", date, slug, suffix+1) + } + relativePath := filepath.ToSlash(filepath.Join(SpecDirName, id+".md")) + path := filepath.Join(absoluteRoot, filepath.FromSlash(relativePath)) + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + if os.IsExist(err) { + continue + } + return SavedSpec{}, fmt.Errorf("create spec file: %w", err) + } + if _, err := file.WriteString(plan + "\n"); err != nil { + _ = file.Close() + _ = os.Remove(path) + return SavedSpec{}, fmt.Errorf("write spec file: %w", err) + } + if err := file.Close(); err != nil { + _ = os.Remove(path) + return SavedSpec{}, fmt.Errorf("close spec file: %w", err) + } + return SavedSpec{ + ID: id, + Title: title, + Path: path, + RelativePath: relativePath, + }, nil + } + return SavedSpec{}, fmt.Errorf("create spec file: too many name collisions for %q", title) +} diff --git a/internal/specmode/specmode_test.go b/internal/specmode/specmode_test.go new file mode 100644 index 000000000..1758f0fb1 --- /dev/null +++ b/internal/specmode/specmode_test.go @@ -0,0 +1,96 @@ +package specmode + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Gitlawb/zero/internal/tools" +) + +func TestSaveDraftWritesPlainMarkdownWithCollisionSuffix(t *testing.T) { + root := t.TempDir() + now := fixedSpecTime("2026-06-08T10:00:00Z") + + first, err := SaveDraft(SaveOptions{ + WorkspaceRoot: root, + Title: "OAuth Redirect", + Plan: "# Goal\n\nImplement redirect handling.", + Now: now, + }) + if err != nil { + t.Fatalf("SaveDraft first returned error: %v", err) + } + second, err := SaveDraft(SaveOptions{ + WorkspaceRoot: root, + Title: "OAuth Redirect", + Plan: "# Goal\n\nImplement redirect handling again.", + Now: now, + }) + if err != nil { + t.Fatalf("SaveDraft second returned error: %v", err) + } + + if first.ID != "2026-06-08-oauth-redirect" || second.ID != "2026-06-08-oauth-redirect-2" { + t.Fatalf("unexpected ids: first=%q second=%q", first.ID, second.ID) + } + if first.RelativePath != ".zero/specs/2026-06-08-oauth-redirect.md" { + t.Fatalf("relative path = %q", first.RelativePath) + } + content, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(first.RelativePath))) + if err != nil { + t.Fatalf("read saved spec: %v", err) + } + if got := string(content); got != "# Goal\n\nImplement redirect handling.\n" { + t.Fatalf("saved content = %q", got) + } +} + +func TestExitToolSavesSpecAndReturnsReviewControl(t *testing.T) { + root := t.TempDir() + tool := NewExitTool(root, fixedSpecTime("2026-06-08T11:00:00Z")) + + result := tool.Run(context.Background(), map[string]any{ + "title": "Spec Mode", + "plan": "# Goal\n\nAdd spec mode.", + }) + + if result.Status != tools.StatusOK { + t.Fatalf("ExitSpecMode status = %s output=%s", result.Status, result.Output) + } + if result.Meta["control"] != ControlSpecReviewRequired { + t.Fatalf("control meta = %#v", result.Meta) + } + if result.Meta["specId"] != "2026-06-08-spec-mode" { + t.Fatalf("specId meta = %#v", result.Meta) + } + if len(result.ChangedFiles) != 1 || result.ChangedFiles[0] != ".zero/specs/2026-06-08-spec-mode.md" { + t.Fatalf("changed files = %#v", result.ChangedFiles) + } + if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(result.ChangedFiles[0]))); err != nil { + t.Fatalf("expected spec file to exist: %v", err) + } + if !strings.Contains(result.Output, result.ChangedFiles[0]) { + t.Fatalf("output should mention relative path, got %q", result.Output) + } +} + +func TestExitToolRejectsInvalidArgs(t *testing.T) { + result := NewExitTool(t.TempDir(), nil).Run(context.Background(), map[string]any{ + "title": "Missing plan", + }) + if result.Status != tools.StatusError || !strings.Contains(result.Output, "plan is required") { + t.Fatalf("unexpected invalid arg result: %#v", result) + } +} + +func fixedSpecTime(value string) func() time.Time { + parsed, err := time.Parse(time.RFC3339, value) + if err != nil { + panic(err) + } + return func() time.Time { return parsed } +} diff --git a/internal/tools/ask_user_test.go b/internal/tools/ask_user_test.go index f4110a349..b5d70e586 100644 --- a/internal/tools/ask_user_test.go +++ b/internal/tools/ask_user_test.go @@ -88,9 +88,18 @@ func TestAskUserToolRunRejectsMissingQuestions(t *testing.T) { } } -// NOTE: ask_user is intentionally NOT in CoreReadOnlyTools yet — it needs the -// agent loop's interactive intercept (OnAskUser) to function. The agent module -// registers it in core and wires the intercept together, with its own test. +func TestCoreReadOnlyToolsIncludeAskUser(t *testing.T) { + found := false + for _, tool := range CoreReadOnlyTools(t.TempDir()) { + if tool.Name() == "ask_user" { + found = true + break + } + } + if !found { + t.Fatal("expected ask_user in core read-only tools") + } +} func TestParseAskUserQuestionsLenientOptions(t *testing.T) { // minimax-style: options as array of objects with a label field. diff --git a/internal/tools/registry.go b/internal/tools/registry.go index 582f17b24..d856faf91 100644 --- a/internal/tools/registry.go +++ b/internal/tools/registry.go @@ -174,10 +174,7 @@ func CoreReadOnlyTools(workspaceRoot string) []Tool { // skill reads reusable instruction files from the skills dir (it resolves // skills.DefaultDir itself); read-only, so it is safe in the core/MCP set. NewSkillTool(""), - // NOTE: ask_user (NewAskUserTool) is intentionally NOT registered in core - // yet. It needs the agent loop's interactive intercept (OnAskUser); without - // it the tool only returns the non-interactive fallback. The agent module - // registers it in core when that intercept path lands. + NewAskUserTool(), } } diff --git a/internal/tools/registry_test.go b/internal/tools/registry_test.go index cee42ece8..418d7796c 100644 --- a/internal/tools/registry_test.go +++ b/internal/tools/registry_test.go @@ -12,8 +12,8 @@ import ( func TestCoreReadOnlyToolsExposeSafeMetadata(t *testing.T) { toolset := CoreReadOnlyTools(t.TempDir()) - if len(toolset) != 5 { - t.Fatalf("expected 5 core read-only tools, got %d", len(toolset)) + if len(toolset) != 6 { + t.Fatalf("expected 6 core read-only tools, got %d", len(toolset)) } for _, tool := range toolset { diff --git a/internal/zerocommands/contracts.go b/internal/zerocommands/contracts.go index 8b75c15fc..26b5f3464 100644 --- a/internal/zerocommands/contracts.go +++ b/internal/zerocommands/contracts.go @@ -105,6 +105,15 @@ type SessionSnapshot struct { ForkedFromSequence int `json:"forkedFromSequence,omitempty"` SpawnedFromEventID string `json:"spawnedFromEventId,omitempty"` SpawnedFromSequence int `json:"spawnedFromSequence,omitempty"` + SpecID string `json:"specId,omitempty"` + SpecFilePath string `json:"specFilePath,omitempty"` + SpecStatus string `json:"specStatus,omitempty"` + SpecDraftModelID string `json:"specDraftModelId,omitempty"` + SpecDraftReasoning string `json:"specDraftReasoning,omitempty"` + SpecUserComment string `json:"specUserComment,omitempty"` + SpecRejectReason string `json:"specRejectReason,omitempty"` + SpecSourceSessionID string `json:"specSourceSessionId,omitempty"` + SpecImplSessionID string `json:"specImplSessionId,omitempty"` CreatedAt string `json:"createdAt,omitempty"` UpdatedAt string `json:"updatedAt,omitempty"` EventCount int `json:"eventCount"` @@ -294,6 +303,15 @@ func SessionSnapshotFromMetadata(item sessions.Metadata) SessionSnapshot { ForkedFromSequence: item.ForkedFromSequence, SpawnedFromEventID: item.SpawnedFromEventID, SpawnedFromSequence: item.SpawnedFromSequence, + SpecID: item.SpecID, + SpecFilePath: item.SpecFilePath, + SpecStatus: string(item.SpecStatus), + SpecDraftModelID: item.SpecDraftModelID, + SpecDraftReasoning: item.SpecDraftReasoning, + SpecUserComment: item.SpecUserComment, + SpecRejectReason: item.SpecRejectReason, + SpecSourceSessionID: item.SpecSourceSessionID, + SpecImplSessionID: item.SpecImplSessionID, CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, EventCount: item.EventCount, diff --git a/internal/zerocommands/contracts_test.go b/internal/zerocommands/contracts_test.go index 5aefac060..6506f741e 100644 --- a/internal/zerocommands/contracts_test.go +++ b/internal/zerocommands/contracts_test.go @@ -266,6 +266,35 @@ func TestSessionSnapshotsPreserveLineageFields(t *testing.T) { } } +func TestSessionSnapshotsExposeSpecFields(t *testing.T) { + snapshot := SessionSnapshotFromMetadata(sessions.Metadata{ + SessionID: "draft", + SessionKind: sessions.SessionKindSpecDraft, + SpecID: "2026-06-08-spec-mode", + SpecFilePath: "/repo/.zero/specs/2026-06-08-spec-mode.md", + SpecStatus: sessions.SpecStatusDraft, + SpecDraftModelID: "gpt-5", + SpecDraftReasoning: "high", + SpecUserComment: "looks good", + SpecRejectReason: "too broad", + SpecSourceSessionID: "source", + SpecImplSessionID: "impl", + }) + + if snapshot.Kind != string(sessions.SessionKindSpecDraft) || + snapshot.SpecID != "2026-06-08-spec-mode" || + snapshot.SpecFilePath == "" || + snapshot.SpecStatus != string(sessions.SpecStatusDraft) || + snapshot.SpecDraftModelID != "gpt-5" || + snapshot.SpecDraftReasoning != "high" || + snapshot.SpecUserComment != "looks good" || + snapshot.SpecRejectReason != "too broad" || + snapshot.SpecSourceSessionID != "source" || + snapshot.SpecImplSessionID != "impl" { + t.Fatalf("spec fields missing from snapshot: %#v", snapshot) + } +} + func findCatalogSnapshot(t *testing.T, snapshots []ProviderCatalogSnapshot, id string) ProviderCatalogSnapshot { t.Helper()