# yaml-language-server: $schema=./node_modules/cli-contracts/schemas/cli-contract.schema.json
cli_contracts: 0.1.0

info:
  title: litedbmodel-gen CLI
  version: 0.2.0
  description: >-
    embedoc-based model code generator for litedbmodel.
    Parses SQL DDL (PostgreSQL / MySQL / SQLite) and generates
    TypeScript column definitions that stay in sync with your schema.
  license:
    name: MIT
  contact:
    name: foo-ogawa
    url: https://github.com/foo-ogawa/litedbmodel.ts

artifact_slots:
  sql-schemas:
    direction: read
    description: SQL DDL files for schema parsing
  embedoc-config:
    direction: readwrite
    description: embedoc.config.yaml configuration (read and updated during init)
  generated-models:
    direction: write
    description: Generated TypeScript model definitions

command_sets:
  litedbmodel-gen:
    summary: embedoc-based model code generator for litedbmodel.
    executable: litedbmodel-gen

    global_options:
      - name: version
        aliases: [V]
        description: Print version and exit.
        schema:
          type: boolean

      - name: help
        aliases: [h]
        description: Show help and exit.
        schema:
          type: boolean

    commands:
      # ── init ────────────────────────────────────────────
      init:
        summary: Set up litedbmodel-gen in an embedoc project.
        description: >-
          Registers the sql_schema datasource, litedbmodel_columns renderer,
          and model.hbs template into an existing embedoc project.
          Copies the starter Handlebars template, updates
          .embedoc/renderers/index.ts and .embedoc/datasources/index.ts,
          and adds a schema datasource entry to embedoc.config.yaml.
        usage:
          - litedbmodel-gen init
          - litedbmodel-gen init path/to/embedoc.config.yaml

        arguments:
          - name: config
            index: 0
            required: false
            description: >-
              Path to embedoc.config.yaml.
              Defaults to embedoc.config.yaml in the current directory.
            schema:
              type: string
              default: embedoc.config.yaml
            file:
              mode: read
              exists: true
              media_type: application/yaml
              encoding: utf-8

        exits:
          '0':
            description: >-
              litedbmodel-gen set up successfully.
              Template copied, renderers/datasources registered,
              and embedoc config updated.
            stdout:
              format: text
            files:
              - path: .embedoc/templates/model.hbs
                required: false
                media_type: text/x-handlebars-template
                encoding: utf-8
                description: Starter Handlebars template for model files (skipped if already exists).

          '1':
            description: >-
              Setup failed due to an unexpected file operation error.
            stderr:
              format: text

          '3':
            description: >-
              Input validation failed. The specified embedoc.config.yaml
              path was not found. Run "npx embedoc init" first.
            stderr:
              format: json

        x-agent:
          riskLevel: low
          requiresConfirmation: false
          idempotent: true
          sideEffects:
            - file_write
          recommendedBeforeUse:
            - Run "npx embedoc init" first to create embedoc.config.yaml.

      # ── audit ────────────────────────────────────────────
      audit:
        summary: Audit litedbmodel usage code for common anti-patterns.
        description: >-
          Scans TypeScript source files that import or use litedbmodel models,
          detecting anti-patterns such as loop-insert (use createMany),
          delete-then-reinsert (use upsert), N+1 queries, missing idempotency
          guards, missing UNIQUE constraints for onConflict, over-broad deletes,
          and missing forUpdate in concurrent-write paths.
          Returns structured findings with severity ratings and remediation
          guidance referencing the correct litedbmodel API.
        usage:
          - litedbmodel-gen audit
          - litedbmodel-gen audit src/
          - litedbmodel-gen audit src/services/user-service.ts --fail-on warning --report-format text

        arguments:
          - name: target
            index: 0
            required: false
            description: >-
              File or directory path to audit.
              Defaults to the current working directory.
            schema:
              type: string
              default: "."

        options:
          - name: adapter
            description: LLM adapter to use for the audit.
            schema:
              type: string
              enum: [mock, claude, openai, gemini]
              default: mock

          - name: model
            description: Model name override for the selected adapter.
            schema:
              type: string

          - name: show-prompt
            description: Output the constructed prompt without calling the LLM API.
            schema:
              type: boolean
              default: false

          - name: fail-on
            description: >-
              Minimum finding severity that causes exit code 10.
              Findings below this threshold are still reported.
            schema:
              type: string
              enum: [warning, error, critical]
              default: error

          - name: output
            aliases: [o]
            description: Write the report to a file instead of stdout.
            schema:
              type: string
            file:
              mode: write

          - name: report-format
            description: Output format for the audit report.
            schema:
              type: string
              enum: [json, text, yaml]
              default: json

          - name: log-file
            aliases: [l]
            description: File path to write structured progress logs.
            schema:
              type: string
            file:
              mode: write

        x-agent:
          riskLevel: low
          requiresConfirmation: false
          idempotent: true
          dsl_task: audit-litedbmodel-usage
          sideEffects: [network]
          sideEffectNote: >-
            Makes network calls to the configured LLM provider when adapter is
            not "mock". Writes to the filesystem only when --output is specified.
          safeDryRunOption: show-prompt
          expectedDurationMs: 120000
          retryableExitCodes: [1, 12]

        exits:
          '0':
            description: >-
              Audit completed. No findings at or above the --fail-on threshold.
            stdout:
              format: json
              schema:
                $ref: '#/components/schemas/AgentAuditResult'
          '1':
            description: General error (unexpected exception or I/O failure).
            stderr:
              format: text
          '3':
            description: >-
              Input validation failed (target path not found, no TypeScript
              files found at path).
            stderr:
              format: json
          '10':
            description: >-
              Blocking findings detected at or above the --fail-on threshold.
            stdout:
              format: json
              schema:
                $ref: '#/components/schemas/AgentAuditResult'
          '11':
            description: agent-contracts-runtime package is not installed.
            stderr:
              format: json
          '12':
            description: >-
              Adapter initialization failed (missing API key or invalid
              configuration).
            stderr:
              format: json

      # ── implement ─────────────────────────────────────────
      implement:
        summary: Implement a feature using litedbmodel best practices.
        description: >-
          Reads the project's model definitions, then implements the described
          feature directly in the target source file(s), applying litedbmodel
          best-practice patterns: createMany for batch inserts, upsert with
          onConflict/onConflictUpdate for idempotent writes, forUpdate for
          concurrent-safe reads, and DBModel.transaction for multi-step
          operations. Avoids all eight common litedbmodel anti-patterns.
          Requires an agentic adapter (claude) that can read and
          write project files.
        usage:
          - >-
            litedbmodel-gen implement
            "Add syncNutrientSummary in src/services/meal.service.ts"
            --target src/services/meal.service.ts
            --models "src/models/**/*.ts"
            --adapter claude
          - >-
            litedbmodel-gen implement
            "Add bulk upsert for order items"
            --target src/services/order.service.ts
            --adapter claude

        arguments:
          - name: description
            index: 0
            required: true
            description: >-
              Natural-language description of the feature to implement.
              Should specify the function name, target file, and business logic.
            schema:
              type: string

        options:
          - name: target
            aliases: [t]
            description: >-
              Target source file(s) to create or edit. The agent reads these
              files to understand existing code and writes the implementation
              to them.
            schema:
              type: string

          - name: models
            description: >-
              Glob pattern for model definition files. The agent reads these
              to understand available models, columns, and relations.
            schema:
              type: string
              default: "models/**/*.ts"

          - name: adapter
            description: LLM adapter to use for code generation.
            schema:
              type: string
              enum: [mock, claude, openai, gemini]
              default: mock

          - name: model
            description: Model name override for the selected adapter.
            schema:
              type: string

          - name: show-prompt
            description: Output the constructed prompt without calling the LLM API.
            schema:
              type: boolean
              default: false

          - name: fail-on
            description: >-
              Minimum finding severity that causes exit code 10.
              Design concerns (info/warning) are still reported at exit 0.
            schema:
              type: string
              enum: [warning, error, critical]
              default: error

          - name: output
            aliases: [o]
            description: Write the report to a file instead of stdout.
            schema:
              type: string
            file:
              mode: write

          - name: report-format
            description: Output format for the implementation report.
            schema:
              type: string
              enum: [json, text, yaml]
              default: json

          - name: log-file
            aliases: [l]
            description: File path to write structured progress logs.
            schema:
              type: string
            file:
              mode: write

        x-agent:
          riskLevel: high
          requiresConfirmation: true
          idempotent: false
          dsl_task: implement-litedbmodel-feature
          sideEffects: [network, filesystem_write]
          sideEffectNote: >-
            The agent reads project files and writes implementation code
            directly to the target source file(s). Uses an agentic adapter
            (claude) with file read/write tools.
          safeDryRunOption: show-prompt
          expectedDurationMs: 120000
          retryableExitCodes: [1, 12]

        exits:
          '0':
            description: >-
              Implementation written to target files successfully with no
              design concerns at or above the --fail-on threshold.
            stdout:
              format: json
              schema:
                $ref: '#/components/schemas/LitedbmodelImplementResult'
          '1':
            description: General error (unexpected exception or I/O failure).
            stderr:
              format: text
          '3':
            description: >-
              Input validation failed (missing description or unreadable
              model files).
            stderr:
              format: json
          '10':
            description: >-
              Implementation written but design concerns at or above the
              --fail-on threshold were detected.
            stdout:
              format: json
              schema:
                $ref: '#/components/schemas/LitedbmodelImplementResult'
          '11':
            description: agent-contracts-runtime package is not installed.
            stderr:
              format: json
          '12':
            description: >-
              Adapter initialization failed (missing API key or invalid
              configuration).
            stderr:
              format: json

      # ── insights ──────────────────────────────────────
      insights:
        summary: Export SQL schema → model file edges as ExternalInsight JSON.
        description: >-
          Reads embedoc.config.yaml datasources and maps each SQL DDL table
          to its generated model file for agent-contracts-analyzer integration.
        usage:
          - litedbmodel-gen insights --format json
          - litedbmodel-gen insights --format json --project-root .
          - litedbmodel-gen insights --format json --config embedoc.config.yaml

        options:
          - name: format
            aliases: [f]
            description: "Output format (json only)."
            value_name: format
            schema:
              type: string
              default: json
              enum: [json]

          - name: project-root
            description: Project root directory containing embedoc.config.yaml.
            value_name: path
            schema:
              type: string
              default: .

          - name: config
            aliases: [c]
            description: Path to embedoc.config.yaml.
            value_name: path
            schema:
              type: string
            file:
              mode: read
              exists: true
              media_type: application/yaml
              encoding: utf-8

        exits:
          '0':
            description: ExternalInsight JSON emitted to stdout.
            stdout:
              format: json

          '1':
            description: Export failed (config not found, unreadable SQL, or internal error).
            stderr:
              format: text

        x-agent:
          riskLevel: low
          requiresConfirmation: false
          idempotent: true
          sideEffects: []

      # ── agents ──────────────────────────────────────────
      agents:
        summary: Output the full resolved agent DSL as structured data.
        description: >-
          Outputs the complete resolved agent-contracts DSL (agents, tasks,
          workflows, handoff_types) embedded in this CLI binary.
          Useful for debugging, external tooling integration, and DSL
          inspection.
        options:
          - name: format
            aliases: [F]
            description: Output format.
            schema:
              type: string
              enum: [yaml, json]
              default: yaml

        exits:
          '0':
            description: DSL output successfully.
            stdout:
              format: text
          '1':
            description: Failed to load embedded DSL.
            stderr:
              format: text

        x-agent:
          riskLevel: low
          requiresConfirmation: false
          idempotent: true
          sideEffects: []

components:
  schemas:
    AgentEvidence:
      type: object
      required: [type, content]
      properties:
        type:
          type: string
          description: Evidence category (e.g. code_snippet, log_line, metric).
        content:
          type: string
          description: The evidence body.
        source:
          type: string
          description: File path, URL, or identifier of the evidence source.

    AgentFinding:
      type: object
      required: [severity, category, message]
      properties:
        id:
          type: string
          description: Optional stable identifier for the finding.
        severity:
          type: string
          enum: [info, warning, error, critical]
        category:
          type: string
          description: Domain-specific vocabulary label (e.g. LOOP_CREATE, N_PLUS_ONE).
        target:
          type: string
          description: Symbol, class, or function where the finding applies.
        location:
          type: string
          description: File path and optional line reference.
        message:
          type: string
          description: Human-readable description of the finding.
        recommendation:
          type: string
          description: Actionable fix referencing the correct litedbmodel API.
        confidence:
          type: number
          minimum: 0
          maximum: 1
          description: Model confidence in the finding (0–1).
        evidence:
          type: array
          items:
            $ref: '#/components/schemas/AgentEvidence'
        details:
          type: object
          description: Arbitrary additional structured detail.

    AgentRecommendedAction:
      type: object
      required: [kind, title]
      properties:
        kind:
          type: string
          enum: [run_command, edit_file, review, confirm, block, ignore]
        title:
          type: string
          description: Short imperative label for the action.
        command:
          type: string
          description: Shell command to run (for kind=run_command).
        target:
          type: string
          description: File or symbol to edit/review.
        rationale:
          type: string
          description: Why this action is recommended.

    AgentAuditResult:
      type: object
      required: [summary, riskLevel, findings]
      properties:
        summary:
          type: string
          description: One-paragraph summary of the audit result.
        riskLevel:
          type: string
          enum: [low, medium, high, critical]
          description: Overall risk level reflecting the highest-severity finding.
        findings:
          type: array
          items:
            $ref: '#/components/schemas/AgentFinding'
        recommendedActions:
          type: array
          items:
            $ref: '#/components/schemas/AgentRecommendedAction'
        metadata:
          type: object
          properties:
            tool:
              type: string
            command:
              type: string
            version:
              type: string
            generatedAt:
              type: string
            adapter:
              type: string
            model:
              type: string

    FileChange:
      type: object
      required: [path, action]
      properties:
        path:
          type: string
          description: Relative file path that was created or modified.
        action:
          type: string
          enum: [created, updated]
          description: Whether the file was newly created or updated.
        rationale:
          type: string
          description: Why this file was changed.

    LitedbmodelImplementResult:
      allOf:
        - $ref: '#/components/schemas/AgentAuditResult'
        - type: object
          required: [changedFiles]
          properties:
            changedFiles:
              type: array
              description: Files that the agent created or modified.
              items:
                $ref: '#/components/schemas/FileChange'
            dependencies:
              type: array
              description: npm packages required but not yet in the project.
              items:
                type: string
            notes:
              type: string
              description: Additional integration instructions.
