add ai feature
This commit is contained in:
34
specs/008-ai-rename-command/checklists/requirements.md
Normal file
34
specs/008-ai-rename-command/checklists/requirements.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Specification Quality Checklist: AI-Assisted Rename Command
|
||||
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2025-11-05
|
||||
**Feature**: [Link to spec.md](/home/yanghao/projects/renamer/specs/008-ai-rename-command/spec.md)
|
||||
|
||||
## Content Quality
|
||||
|
||||
- [x] No implementation details (languages, frameworks, APIs)
|
||||
- [x] Focused on user value and business needs
|
||||
- [x] Written for non-technical stakeholders
|
||||
- [x] All mandatory sections completed
|
||||
|
||||
## Requirement Completeness
|
||||
|
||||
- [x] No [NEEDS CLARIFICATION] markers remain
|
||||
- [x] Requirements are testable and unambiguous
|
||||
- [x] Success criteria are measurable
|
||||
- [x] Success criteria are technology-agnostic (no implementation details)
|
||||
- [x] All acceptance scenarios are defined
|
||||
- [x] Edge cases are identified
|
||||
- [x] Scope is clearly bounded
|
||||
- [x] Dependencies and assumptions identified
|
||||
|
||||
## Feature Readiness
|
||||
|
||||
- [x] All functional requirements have clear acceptance criteria
|
||||
- [x] User scenarios cover primary flows
|
||||
- [x] Feature meets measurable outcomes defined in Success Criteria
|
||||
- [x] No implementation details leak into specification
|
||||
|
||||
## Notes
|
||||
|
||||
- All criteria satisfied.
|
||||
93
specs/008-ai-rename-command/contracts/rename-flow.yaml
Normal file
93
specs/008-ai-rename-command/contracts/rename-flow.yaml
Normal file
@@ -0,0 +1,93 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: Genkit renameFlow Contract
|
||||
version: 0.1.0
|
||||
description: >
|
||||
Contract for the `renameFlow` Genkit workflow that produces structured rename
|
||||
suggestions consumed by the `renamer ai` CLI command.
|
||||
servers:
|
||||
- url: genkit://renameFlow
|
||||
description: Logical identifier for local Genkit execution.
|
||||
paths:
|
||||
/renameFlow: # logical entry point (function invocation)
|
||||
post:
|
||||
summary: Generate rename suggestions for provided file names.
|
||||
description: Mirrors `genkit.Run(ctx, renameFlow, input)` in the CLI integration.
|
||||
operationId: runRenameFlow
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenameFlowInput'
|
||||
responses:
|
||||
'200':
|
||||
description: Successful rename suggestion payload.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenameFlowOutput'
|
||||
'400':
|
||||
description: Validation error (e.g., invalid filenames, mismatched counts).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
|
||||
components:
|
||||
schemas:
|
||||
RenameFlowInput:
|
||||
type: object
|
||||
required:
|
||||
- fileNames
|
||||
- userPrompt
|
||||
properties:
|
||||
fileNames:
|
||||
type: array
|
||||
description: Ordered list of basenames collected from CLI traversal.
|
||||
minItems: 1
|
||||
maxItems: 200
|
||||
items:
|
||||
type: string
|
||||
pattern: '^[^\\/:*?"<>|]+$'
|
||||
userPrompt:
|
||||
type: string
|
||||
description: Optional guidance supplied by the user.
|
||||
minLength: 0
|
||||
maxLength: 500
|
||||
RenameFlowOutput:
|
||||
type: object
|
||||
required:
|
||||
- suggestions
|
||||
properties:
|
||||
suggestions:
|
||||
type: array
|
||||
description: Suggested rename entries aligned with the input order.
|
||||
minItems: 1
|
||||
items:
|
||||
$ref: '#/components/schemas/RenameSuggestion'
|
||||
RenameSuggestion:
|
||||
type: object
|
||||
required:
|
||||
- original
|
||||
- suggested
|
||||
properties:
|
||||
original:
|
||||
type: string
|
||||
description: Original basename supplied in the request.
|
||||
pattern: '^[^\\/:*?"<>|]+$'
|
||||
suggested:
|
||||
type: string
|
||||
description: Proposed basename retaining original extension.
|
||||
pattern: '^[^\\/:*?"<>|]+$'
|
||||
ErrorResponse:
|
||||
type: object
|
||||
required:
|
||||
- error
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Human-readable reason for failure.
|
||||
remediation:
|
||||
type: string
|
||||
description: Suggested user action (e.g., adjust scope, reduce file count).
|
||||
62
specs/008-ai-rename-command/data-model.md
Normal file
62
specs/008-ai-rename-command/data-model.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# Data Model – Genkit renameFlow & AI CLI
|
||||
|
||||
## Entity: RenameFlowInput
|
||||
- **Fields**
|
||||
- `fileNames []string` — Ordered list of basenames collected from scope traversal.
|
||||
- `userPrompt string` — Optional user guidance merged into the prompt template.
|
||||
- **Validation Rules**
|
||||
- Require at least one filename; enforce maximum of 200 per invocation (soft limit before batching).
|
||||
- Reject names containing path separators; traversal supplies basenames only.
|
||||
- Trim whitespace from `userPrompt`; clamp length (e.g., 1–500 characters) to guard against prompt injection.
|
||||
- **Relationships**
|
||||
- Serialized to JSON and passed into `genkit.Generate()` as the model input payload.
|
||||
- Logged with invocation metadata to support replay/debugging.
|
||||
|
||||
## Entity: RenameFlowOutput
|
||||
- **Fields**
|
||||
- `suggestions []RenameSuggestion` — AI-produced rename pairs in same order as input list when possible.
|
||||
- **Validation Rules**
|
||||
- `len(suggestions)` MUST equal length of input `fileNames` before approval.
|
||||
- Each suggestion MUST pass filename safety checks (see `RenameSuggestion`).
|
||||
- JSON payload MUST parse cleanly with no additional top-level properties.
|
||||
- **Relationships**
|
||||
- Returned to the CLI bridge, transformed into preview rows and ledger entries.
|
||||
|
||||
## Entity: RenameSuggestion
|
||||
- **Fields**
|
||||
- `original string` — Original basename (must match an item from input list).
|
||||
- `suggested string` — Proposed basename with identical extension as `original`.
|
||||
- **Validation Rules**
|
||||
- Preserve extension suffix (text after last `.`); fail if changed or removed.
|
||||
- Disallow illegal filesystem characters: `/ \ : * ? " < > |` and control bytes.
|
||||
- Enforce case-insensitive uniqueness across all `suggested` values to avoid collisions.
|
||||
- Reject empty or whitespace-only suggestions; trim incidental spaces.
|
||||
- **Relationships**
|
||||
- Consumed by preview renderer to display mappings.
|
||||
- Persisted in ledger metadata alongside user prompt and model ID.
|
||||
|
||||
## Entity: AISuggestionBatch (Go side)
|
||||
- **Fields**
|
||||
- `Scope traversal.ScopeResult` — Snapshot of files selected for AI processing.
|
||||
- `Prompt string` — Rendered prompt sent to Genkit (stored for debugging).
|
||||
- `ModelID string` — Identifier for the AI model used during generation.
|
||||
- `Suggestions []RenameSuggestion` — Parsed results aligned with scope entries.
|
||||
- `Warnings []string` — Issues detected during validation (duplicates, unchanged names, limit truncation).
|
||||
- **Validation Rules**
|
||||
- Warnings that correspond to hard failures (duplicate targets, invalid characters) block apply until resolved.
|
||||
- Scope result order MUST align with suggestion order to keep preview deterministic.
|
||||
- **Relationships**
|
||||
- Passed into output renderer for table display.
|
||||
- Written to ledger with `history.RecordBatch` for undo.
|
||||
|
||||
## Entity: FlowInvocationLog
|
||||
- **Fields**
|
||||
- `InvocationID string` — UUID tying output to ledger entry.
|
||||
- `Timestamp time.Time` — Invocation time for audit trail.
|
||||
- `Duration time.Duration` — Round-trip latency for success criteria tracking.
|
||||
- `InputSize int` — Number of filenames processed (used for batching heuristics).
|
||||
- `Errors []string` — Captured model or validation errors.
|
||||
- **Validation Rules**
|
||||
- Duration recorded only on successful completions; errors populated otherwise.
|
||||
- **Relationships**
|
||||
- Optional: appended to debug logs or analytics for performance monitoring (non-ledger).
|
||||
90
specs/008-ai-rename-command/plan.md
Normal file
90
specs/008-ai-rename-command/plan.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Implementation Plan: AI-Assisted Rename Command
|
||||
|
||||
**Branch**: `008-ai-rename-command` | **Date**: 2025-11-05 | **Spec**: `specs/008-ai-rename-command/spec.md`
|
||||
**Input**: Feature specification from `/specs/008-ai-rename-command/spec.md`
|
||||
|
||||
**Note**: This plan grounds the `/speckit.plan` prompt “Genkit Flow 设计 (Genkit Flow Design)” by detailing how the CLI and Genkit workflow collaborate to deliver structured AI rename suggestions.
|
||||
|
||||
## Summary
|
||||
|
||||
Design and implement a `renameFlow` Genkit workflow that produces deterministic, JSON-formatted rename suggestions and wire it into a new `renamer ai` CLI path. The plan covers prompt templating, JSON validation, scope handling parity with existing commands, preview/confirmation UX, ledger integration, and fallback/error flows to keep AI-generated batches auditable and undoable.
|
||||
|
||||
## Technical Context
|
||||
|
||||
**Language/Version**: Go 1.24 (CLI + Genkit workflow)
|
||||
**Primary Dependencies**: `spf13/cobra`, `spf13/pflag`, internal traversal/history/output packages, `github.com/firebase/genkit/go`, OpenAI-compatible provider bridge
|
||||
**Storage**: Local filesystem plus append-only `.renamer` ledger
|
||||
**Testing**: `go test ./...` including flow unit tests for prompt/render/validation, contract + integration tests under `tests/`
|
||||
**Target Platform**: Cross-platform CLI executed from local shells; Genkit workflow runs in-process via Go bindings
|
||||
**Project Type**: Single Go CLI project with additional internal AI packages
|
||||
**Performance Goals**: Generate rename suggestions for ≤200 files within 30 seconds end-to-end (per SC-001)
|
||||
**Constraints**: Preview-first safety, undoable ledger entries, scope parity with existing commands, deterministic JSON responses, offline fallback excluded (network required)
|
||||
**Scale/Scope**: Handles hundreds of files per invocation, with potential thousands when batched; assumes human-in-the-loop confirmation
|
||||
|
||||
## Constitution Check
|
||||
|
||||
- Preview flow MUST show deterministic rename mappings and require explicit confirmation (Preview-First Safety). ✅ `renamer ai` reuses preview renderer to display AI suggestions, blocks apply until `--yes` or interactive confirmation, and supports `--dry-run`.
|
||||
- Undo strategy MUST describe how the `.renamer` ledger entry is written and reversed (Persistent Undo Ledger). ✅ Accepted batches append AI metadata (prompt, model, rationale) to ledger entries; undo replays via existing ledger service with no schema break.
|
||||
- Planned rename rules MUST document their inputs, validations, and composing order (Composable Rule Engine). ✅ `renameFlow` enforces rename suggestion structure (original, suggested), keeps extensions intact, and CLI validates conflicts before applying.
|
||||
- Scope handling MUST cover files vs directories (`-d`), recursion (`-r`), and extension filtering via `-e` without escaping the requested path (Scope-Aware Traversal). ✅ CLI gathers scope using shared traversal component, honoring existing flags before passing filenames to Genkit.
|
||||
- CLI UX plan MUST confirm Cobra usage, flag naming, help text, and automated tests for preview/undo flows (Ergonomic CLI Stewardship). ✅ New `ai` command extends Cobra root with existing persistent flags, adds prompt/model overrides, and includes contract + integration coverage for preview/apply/undo.
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/008-ai-rename-command/
|
||||
├── plan.md
|
||||
├── research.md
|
||||
├── data-model.md
|
||||
├── quickstart.md
|
||||
├── contracts/
|
||||
└── spec.md
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
|
||||
```text
|
||||
cmd/
|
||||
├── root.go
|
||||
├── ai.go # new Cobra command wiring + RunE
|
||||
├── list.go
|
||||
├── replace.go
|
||||
├── remove.go
|
||||
└── undo.go
|
||||
|
||||
internal/
|
||||
├── ai/
|
||||
│ ├── flow/
|
||||
│ │ ├── rename_flow.go # Genkit flow definition using Go SDK
|
||||
│ │ └── prompt.tmpl # prompt template with rules/formatting
|
||||
│ ├── client.go # wraps Genkit invocation + response handling
|
||||
│ ├── preview.go # maps RenameSuggestion -> preview rows
|
||||
│ ├── validation.go # conflict + filename safety checks
|
||||
│ └── session.go # manages user guidance refinements
|
||||
├── traversal/
|
||||
├── output/
|
||||
├── history/
|
||||
└── ...
|
||||
|
||||
tests/
|
||||
├── contract/
|
||||
│ └── ai_command_preview_test.go # ensures JSON contract adherence
|
||||
├── integration/
|
||||
│ └── ai_flow_apply_test.go # preview, confirm, undo happy path
|
||||
└── fixtures/
|
||||
└── ai/
|
||||
└── sample_photos/ # test assets for AI rename flows
|
||||
|
||||
scripts/
|
||||
└── smoke-test-ai.sh # optional future smoke harness (planned)
|
||||
```
|
||||
|
||||
**Structure Decision**: Implement the Genkit `renameFlow` directly within Go (`internal/ai/flow`) while reusing shared traversal/output pipelines through the new `ai` command. Tests mirror existing command coverage with contract and integration suites.
|
||||
|
||||
## Complexity Tracking
|
||||
|
||||
| Violation | Why Needed | Simpler Alternative Rejected Because |
|
||||
|-----------|------------|--------------------------------------|
|
||||
| _None_ | — | — |
|
||||
29
specs/008-ai-rename-command/quickstart.md
Normal file
29
specs/008-ai-rename-command/quickstart.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Quickstart – AI Rename Command
|
||||
|
||||
1. **Preview AI suggestions before applying.**
|
||||
```bash
|
||||
renamer ai --path ./photos --prompt "Hawaii vacation album"
|
||||
```
|
||||
- Traverses `./photos` (non-recursive by default) and sends the collected basenames to `renameFlow`.
|
||||
- Displays a preview table with original → suggested names and any validation warnings.
|
||||
|
||||
2. **Adjust scope or guidance and regenerate.**
|
||||
```bash
|
||||
renamer ai --path ./photos --recursive --hidden \
|
||||
--prompt "Group by location, keep capture order"
|
||||
```
|
||||
- `--recursive` includes nested folders; `--hidden` opts in hidden files.
|
||||
- Re-running the command with updated guidance regenerates suggestions without modifying files.
|
||||
|
||||
3. **Apply suggestions non-interactively when satisfied.**
|
||||
```bash
|
||||
renamer ai --path ./photos --prompt "Hawaii vacation" --yes
|
||||
```
|
||||
- `--yes` skips the interactive confirmation while still logging the preview.
|
||||
- Use `--dry-run` to inspect output programmatically without touching the filesystem.
|
||||
|
||||
4. **Undo the most recent AI batch if needed.**
|
||||
```bash
|
||||
renamer undo
|
||||
```
|
||||
- Restores original filenames using the ledger entry created by the AI command.
|
||||
21
specs/008-ai-rename-command/research.md
Normal file
21
specs/008-ai-rename-command/research.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Phase 0 Research – Genkit renameFlow
|
||||
|
||||
## Decision: Enforce JSON-Only Responses via Prompt + Guardrails
|
||||
- **Rationale**: The CLI must parse deterministic structures. Embedding an explicit JSON schema example, restating illegal character rules, and wrapping the Genkit call with `OutputJSON()` (or equivalent) reduces hallucinated prose and aligns with ledger needs.
|
||||
- **Alternatives considered**: Post-processing free-form text was rejected because it increases parsing failures and weakens auditability. Relaxing constraints to “JSON preferred” was rejected to avoid brittle regex extraction.
|
||||
|
||||
## Decision: Keep Prompt Template as External File with Go Template Variables
|
||||
- **Rationale**: Storing the prompt under `internal/ai/flow/prompt.tmpl` keeps localization and iteration separate from code. Using Go-style templating enables the flow to substitute the file list and user prompt consistently while making it easier to unit test rendered prompts.
|
||||
- **Alternatives considered**: Hardcoding prompt strings inside the Go flow was rejected due to limited reuse and poor readability; using Markdown-based prompts was rejected because the model might echo formatting in its response.
|
||||
|
||||
## Decision: Invoke Genkit Flow In-Process via Go SDK
|
||||
- **Rationale**: The spec emphasizes local filesystem workflows without network services. Using the Genkit Go SDK keeps execution in-process, avoids packaging a separate runtime, and fits CLI invocation patterns.
|
||||
- **Alternatives considered**: Hosting a long-lived HTTP service was rejected because it complicates installation and violates the local-only assumption. Spawning an external Node process was rejected due to additional toolchain requirements.
|
||||
|
||||
## Decision: Validate Suggestions Against Existing Filename Rules Before Apply
|
||||
- **Rationale**: Even with JSON enforcement, the model could suggest duplicates, rename directories, or remove extensions. Reusing internal validation logic ensures suggestions honor filesystem invariants and matches ledger expectations before touching disk.
|
||||
- **Alternatives considered**: Trusting AI output without local validation was rejected due to risk of destructive renames. Silently auto-correcting invalid names was rejected because it obscures AI behavior from users.
|
||||
|
||||
## Decision: Align Testing with Contract + Golden Prompt Fixtures
|
||||
- **Rationale**: Contract tests with fixed model responses (via canned JSON) allow deterministic verification, while golden prompt fixtures ensure template rendering matches expectations. This combo offers coverage without depending on live AI calls in CI.
|
||||
- **Alternatives considered**: Live integration tests hitting the model were rejected due to cost, flakiness, and determinism concerns. Pure unit tests without prompt verification were rejected because prompt regressions directly impact model quality.
|
||||
102
specs/008-ai-rename-command/spec.md
Normal file
102
specs/008-ai-rename-command/spec.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# Feature Specification: AI-Assisted Rename Command
|
||||
|
||||
**Feature Branch**: `008-ai-rename-command`
|
||||
**Created**: 2025-11-05
|
||||
**Status**: Draft
|
||||
**Input**: User description: "添加 ai 子命令,使用go genkit 调用ai能力对文件列表进行重命名。"
|
||||
|
||||
## Clarifications
|
||||
|
||||
### Session 2025-11-05
|
||||
|
||||
- Q: How should the CLI handle filename privacy when calling the AI service? → A: Send raw filenames without masking.
|
||||
- Q: How should the AI provider credential be supplied to the CLI? → A: Read from an environment variable (e.g., `RENAMER_AI_KEY`).
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### User Story 1 - Request AI rename plan (Priority: P1)
|
||||
|
||||
As a command-line user, I can request AI-generated rename suggestions for a set of files so that I get a consistent naming plan without defining rules manually.
|
||||
|
||||
**Why this priority**: This delivers the core value of leveraging AI to save time on naming decisions for large batches.
|
||||
|
||||
**Independent Test**: Execute the AI rename command against a sample directory and verify a preview of suggested names is produced without altering files.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a directory with mixed file names and optional user instructions, **When** the user runs the AI rename command, **Then** the tool returns a preview mapping each original name to a suggested name.
|
||||
2. **Given** a scope that includes hidden files when the user enables the corresponding flag, **When** the AI rename command runs, **Then** the preview reflects only the files allowed by the selected scope options.
|
||||
|
||||
---
|
||||
|
||||
### User Story 2 - Refine and confirm suggestions (Priority: P2)
|
||||
|
||||
As a command-line user, I can review, adjust, or regenerate AI suggestions before applying them so that I have control over the final names.
|
||||
|
||||
**Why this priority**: Users need confidence and agency to ensure AI suggestions match their intent, reducing the risk of undesired renames.
|
||||
|
||||
**Independent Test**: Run the AI rename command, adjust the instruction text, regenerate suggestions, and confirm the tool updates the preview without applying changes until approval.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** an initial AI preview, **When** the user supplies new guidance or rejects the batch, **Then** the tool allows a regeneration or cancellation without renaming any files.
|
||||
2. **Given** highlighted conflicts or invalid suggestions in the preview, **When** the user attempts to accept the batch, **Then** the tool blocks execution and instructs the user to resolve the issues.
|
||||
|
||||
---
|
||||
|
||||
### User Story 3 - Apply and audit AI renames (Priority: P3)
|
||||
|
||||
As a command-line user, I can apply approved AI rename suggestions and rely on the existing history and undo mechanisms so that AI-driven batches are traceable and reversible.
|
||||
|
||||
**Why this priority**: Preserving auditability and undo aligns AI-driven actions with existing safety guarantees.
|
||||
|
||||
**Independent Test**: Accept an AI rename batch, verify files are renamed, the ledger records the operation, and the undo command restores originals.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** an approved AI rename preview, **When** the user confirms execution, **Then** the files are renamed and the batch details are recorded in the ledger with AI-specific metadata.
|
||||
2. **Given** an executed AI rename batch, **When** the user runs the undo command, **Then** all affected files return to their original names and the ledger reflects the reversal.
|
||||
|
||||
---
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- AI service fails, times out, or returns an empty response; the command must preserve current filenames and surface actionable error guidance.
|
||||
- The AI proposes duplicate, conflicting, or filesystem-invalid names; the preview must flag each item and prevent application until resolved.
|
||||
- The selected scope includes more files than the AI request limit; the command must communicate limits and guide the user to narrow the scope or batch the request.
|
||||
- The ledger already contains pending batches for the same files; the tool must clarify how the new AI batch interacts with existing history before proceeding.
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001**: The CLI must gather the current file scope using existing flags and present the selected files and optional instructions to the AI suggestion service.
|
||||
- **FR-002**: The system must generate a human-readable preview that pairs each original filename with the AI-proposed name and indicates the rationale or confidence when available.
|
||||
- **FR-003**: The CLI must block application when the preview contains conflicts, invalid names, or missing suggestions and must explain the required corrective actions.
|
||||
- **FR-004**: Users must be able to modify guidance and request a new set of AI suggestions without leaving the command until they accept or exit.
|
||||
- **FR-005**: When users approve a preview, the tool must execute the rename batch, record it in the ledger with the user guidance and AI attribution, and support undo via the existing command.
|
||||
- **FR-006**: The command must support dry-run mode that exercises the AI interaction and preview without writing to disk, clearly labeling the output as non-destructive.
|
||||
- **FR-007**: The system must handle AI service errors gracefully by retaining current filenames, logging diagnostic information, and providing retry instructions.
|
||||
|
||||
### Key Entities
|
||||
|
||||
- **AISuggestionBatch**: Captures the scope summary, user guidance, timestamp, AI provider metadata, and the list of rename suggestions evaluated during a session.
|
||||
- **RenameSuggestion**: Represents a single proposed change with original name, suggested name, validation status, and optional rationale.
|
||||
- **UserGuidance**: Stores free-form instructions supplied by the user, including any follow-up refinements applied within the session.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- AI rename suggestions are generated within existing rate limits; large directories may require the user to split the work manually.
|
||||
- Users running the AI command have network access and credentials required to reach the AI service.
|
||||
- Existing ledger and undo mechanisms remain unchanged and can store additional metadata without format migrations.
|
||||
- AI requests transmit the original filenames without masking; users must avoid including sensitive names when invoking the command.
|
||||
- The CLI reads AI provider credentials from environment variables (default `RENAMER_AI_KEY`); no interactive credential prompts are provided.
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001**: 95% of AI rename previews for up to 200 files complete in under 30 seconds from command invocation.
|
||||
- **SC-002**: 90% of accepted AI rename batches complete without conflicts or manual post-fix adjustments reported by users.
|
||||
- **SC-003**: 100% of AI-driven rename batches remain fully undoable via the existing undo command.
|
||||
- **SC-004**: In post-launch surveys, at least 80% of participating users report that AI suggestions improved their rename workflow efficiency.
|
||||
119
specs/008-ai-rename-command/tasks.md
Normal file
119
specs/008-ai-rename-command/tasks.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# Tasks: AI-Assisted Rename Command
|
||||
|
||||
**Input**: Design documents from `/specs/008-ai-rename-command/`
|
||||
**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/
|
||||
|
||||
## Format: `[ID] [P?] [Story] Description`
|
||||
|
||||
- **[P]**: Can run in parallel (different files, no dependencies)
|
||||
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
|
||||
- Include exact file paths in descriptions
|
||||
|
||||
## Phase 1: Setup (Shared Infrastructure)
|
||||
|
||||
**Purpose**: Add Go-based Genkit dependency and scaffold AI flow package.
|
||||
|
||||
- [x] T001 Ensure Genkit Go module dependency (`github.com/firebase/genkit/go`) is present in `go.mod` / `go.sum`
|
||||
- [x] T002 Create AI flow package directories in `internal/ai/flow/`
|
||||
- [x] T003 [P] Add Go test harness scaffold for AI flow in `internal/ai/flow/flow_test.go`
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Foundational (Blocking Prerequisites)
|
||||
|
||||
**Purpose**: Provide shared assets and configuration required by all user stories.
|
||||
|
||||
- [x] T004 Author AI rename prompt template with JSON instructions in `internal/ai/flow/prompt.tmpl`
|
||||
- [x] T005 Implement reusable JSON parsing helpers for Genkit responses in `internal/ai/flow/json.go`
|
||||
- [x] T006 Implement AI credential loader reading `RENAMER_AI_KEY` in `internal/ai/config.go`
|
||||
- [x] T007 Register the `ai` Cobra command scaffold in `cmd/root.go`
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: User Story 1 - Request AI rename plan (Priority: P1) 🎯 MVP
|
||||
|
||||
**Goal**: Allow users to preview AI-generated rename suggestions for a scoped set of files.
|
||||
|
||||
**Independent Test**: Run `renamer ai --path <dir> --dry-run` and verify the preview table lists original → suggested names without renaming files.
|
||||
|
||||
### Tests for User Story 1
|
||||
|
||||
- [x] T008 [P] [US1] Add prompt rendering unit test covering file list formatting in `internal/ai/flow/prompt_test.go`
|
||||
- [x] T009 [P] [US1] Create CLI preview contract test enforcing JSON schema in `tests/contract/ai_command_preview_test.go`
|
||||
|
||||
### Implementation for User Story 1
|
||||
|
||||
- [x] T010 [US1] Implement `renameFlow` Genkit workflow with JSON-only response in `internal/ai/flow/rename_flow.go`
|
||||
- [x] T011 [P] [US1] Build Genkit client wrapper and response parser in `internal/ai/client.go`
|
||||
- [x] T012 [P] [US1] Implement suggestion validation rules (extensions, duplicates, illegal chars) in `internal/ai/validation.go`
|
||||
- [x] T013 [US1] Map AI suggestions to preview rows with rationale fields in `internal/ai/preview.go`
|
||||
- [x] T014 [US1] Wire `renamer ai` command to gather scope, invoke AI flow, and render preview in `cmd/ai.go`
|
||||
- [x] T015 [US1] Document preview usage and flags for `renamer ai` in `docs/cli-flags.md`
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: User Story 2 - Refine and confirm suggestions (Priority: P2)
|
||||
|
||||
**Goal**: Let users iterate on AI guidance, regenerate suggestions, and resolve conflicts before applying changes.
|
||||
|
||||
**Independent Test**: Run `renamer ai` twice with updated prompts, confirm regenerated preview replaces the previous batch, and verify conflicting targets block approval with actionable warnings.
|
||||
|
||||
### Tests for User Story 2
|
||||
|
||||
- [x] T016 [P] [US2] Add integration test for preview regeneration and cancel flow in `tests/integration/ai_preview_regen_test.go`
|
||||
|
||||
### Implementation for User Story 2
|
||||
|
||||
- [x] T017 [US2] Extend interactive loop in `cmd/ai.go` to support prompt refinement and regeneration commands
|
||||
- [x] T018 [P] [US2] Enhance conflict and warning annotations for regenerated suggestions in `internal/ai/validation.go`
|
||||
- [x] T019 [US2] Persist per-session prompt history and guidance notes in `internal/ai/session.go`
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: User Story 3 - Apply and audit AI renames (Priority: P3)
|
||||
|
||||
**Goal**: Execute approved AI rename batches, record them in the ledger, and ensure undo restores originals.
|
||||
|
||||
**Independent Test**: Accept an AI preview with `--yes`, verify files are renamed, ledger entry captures AI metadata, and `renamer undo` restores originals.
|
||||
|
||||
### Tests for User Story 3
|
||||
|
||||
- [X] T020 [P] [US3] Add integration test covering apply + undo lifecycle in `tests/integration/ai_flow_apply_test.go`
|
||||
- [X] T021 [P] [US3] Add ledger contract test verifying AI metadata persistence in `tests/contract/ai_ledger_entry_test.go`
|
||||
|
||||
### Implementation for User Story 3
|
||||
|
||||
- [X] T022 [US3] Implement confirm/apply execution path with `--yes` handling in `cmd/ai.go`
|
||||
- [X] T023 [P] [US3] Append AI batch metadata to ledger entries in `internal/history/ai_entry.go`
|
||||
- [X] T024 [US3] Ensure undo replay reads AI ledger metadata in `internal/history/undo.go`
|
||||
- [X] T025 [US3] Display progress and per-file outcomes during apply in `internal/output/progress.go`
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Polish & Cross-Cutting
|
||||
|
||||
**Purpose**: Final quality improvements, docs, and operational readiness.
|
||||
|
||||
- [ ] T026 Add smoke test script invoking `renamer ai` preview/apply flows in `scripts/smoke-test-ai.sh`
|
||||
- [X] T027 Update top-level documentation with AI command overview and credential requirements in `README.md`
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Complete Phases 1 → 2 before starting user stories.
|
||||
- User Story order: US1 → US2 → US3 (each builds on prior capabilities).
|
||||
- Polish tasks run after all user stories are feature-complete.
|
||||
|
||||
## Parallel Execution Opportunities
|
||||
|
||||
- US1: T011 and T012 can run in parallel after T010 completes.
|
||||
- US2: T018 can run in parallel with T017 once session loop scaffolding exists.
|
||||
- US3: T023 and T025 can proceed concurrently after T022 defines apply workflow.
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
1. Deliver User Story 1 as the MVP (preview-only experience).
|
||||
2. Iterate on refinement workflow (User Story 2) to reduce risk of bad suggestions before apply.
|
||||
3. Add apply + ledger integration (User Story 3) to complete end-to-end flow.
|
||||
4. Finish with polish tasks to solidify operational readiness.
|
||||
Reference in New Issue
Block a user