Embedding Cognotik — Headless AI Agents for Automated Coding

Hero

Badges: Library · Stable · Maven Central

Headline: Embedding Cognotik

Subtext:

Use com.cognotik:webapp as an embedded engine. Run headless AI agents for complex coding tasks, refactoring, documentation generation, and automated workflows — no UI required.

CTAs: Quick Start · Source Code · Planning Docs

Key Capabilities

Installation

1. Add the Dependency

repositories {
    mavenCentral()
}

dependencies {
    // Core library — contains the Harness and Planning engines
    implementation("com.cognotik:webapp:2.0.39")

    // Logging (recommended)
    implementation("org.slf4j:slf4j-simple:2.0.9")
}

2. Initialize the Harness

The UnifiedHarness is your entry point. Initialize it with serverless = true for headless environments:

import com.simiacryptus.cognotik.util.UnifiedHarness
import com.simiacryptus.cognotik.chat.model.OpenAIModels

val harness = UnifiedHarness(
    serverless = true,       // No browser, no UI
    openBrowser = false,

    // Model selection
    smartModel = OpenAIModels.GPT4o,
    fastModel  = OpenAIModels.GPT35Turbo,

    // API key injection
    modelInstanceFn = { apiChatModel ->
        val apiKey = System.getenv("OPENAI_API_KEY")
            ?: throw RuntimeException("Missing OPENAI_API_KEY")
        apiChatModel.model.instance(key = apiKey)
    }
)

// Initialize platform services
harness.start()

Note: When modelInstanceFn is provided, the harness bypasses local .config files entirely. All API keys must be injected programmatically — ideal for CI/CD secrets.

Usage Scenarios

Scenario A: Full Agent Planning

Give the AI a high-level goal and let it figure out the steps, break them down, and execute them autonomously. Think of it as "The Manager" — you describe the outcome, it handles the process.

import com.simiacryptus.cognotik.plan.cognitive.CognitiveModeConfig
import com.simiacryptus.cognotik.plan.cognitive.CognitiveModeType
import java.io.File

fun runAgenticRefactor(projectDir: File, instruction: String) {
    // 1. Choose a cognitive strategy
    val strategy = CognitiveModeConfig(
        type = CognitiveModeType.Waterfall,
        name = "RefactorAgent"
    )

    // 2. Execute the plan
    harness.runPlan(
        prompt            = instruction,
        cognitiveSettings = strategy,
        workspace         = projectDir,
        timeoutMinutes    = 60,
        autoFix           = true  // No human prompts — fully autonomous
    )

    println("Done. Check results.md in the workspace.")
}

// Example
runAgenticRefactor(
    File("./my-project"),
    "Convert all public fields in User.kt to private with getters/setters."
)

Configuration Options:

Scenario B: Single Task Execution

Use a specific Cognotik tool as a function call within your own code — skip the high-level planning entirely. Think of it as "The Tool" — you specify exactly what to do.

import com.simiacryptus.cognotik.plan.tools.TaskType
import com.simiacryptus.cognotik.plan.tools.file.FileModificationTask.*

fun generateReadme(projectDir: File) {
    // 1. Static config (the "tool" settings)
    val typeConfig = FileModificationTaskTypeConfig(
        name = "ReadmeGenerator"
    )

    // 2. Runtime input (the "job" settings)
    val executionConfig = FileModificationTaskExecutionConfigData(
        files          = listOf("README.md"),
        modifications  = "Read src/main and generate a comprehensive README.",
        extractContent = true,
        task_description = "Generate Documentation"
    )

    // 3. Execute
    harness.runTask(
        taskType        = TaskType.FileModificationTask,
        typeConfig      = typeConfig,
        executionConfig = executionConfig,
        workspace       = projectDir,
        autoFix         = true
    )
}

Task Reference

Every task requires two configuration objects: TaskTypeConfig (static tool settings) and TaskExecutionConfig (runtime job inputs). Common embedded tasks:

FileModificationTask (File)

Refactoring, bug fixing, or feature implementation. Creates or modifies source files with AI assistance.

FileModificationTaskExecutionConfigData(
    files          = listOf("src/Main.kt"),
    related_files  = listOf("src/Utils.kt"),
    modifications  = "Refactor the main loop.",
    extractContent = true
)

FileAppendTask (File)

Optimized for adding content to the end of a file without modifying existing content.

FileAppendTaskExecutionConfigData(
    file           = "CHANGELOG.md",
    append_content = "## [1.0.1] - Fixed login bug",
    related_files  = listOf("src/auth/Login.kt")
)

ReadDocumentsTask (Analysis)

Pure analysis — reads files and answers questions without modifying the filesystem.

ReadDocumentsTaskExecutionConfigData(
    input_files      = listOf("src/**/*.java"),
    inquiry_questions = listOf(
        "How is authentication handled?"
    ),
    inquiry_goal = "Generate security docs"
)

FileSearchTask (Analysis)

Grep-like searches (literal or regex) with line numbers and surrounding context.

FileSearchTaskExecutionConfigData(
    search_pattern = "TODO|FIXME",
    is_regex       = true,
    input_files    = listOf("**/*.kt"),
    context_lines  = 2
)

RunToolTask (Execution)

Execute external CLI tools. Run tests, linters, formatters, or any command-line program.

RunToolTaskExecutionConfigData(
    tool       = "python",
    args       = listOf("scripts/verify.py", "--verbose"),
    workingDir = "."
)

SubPlanTask (Planning)

Spawn a nested agent with its own cognitive mode to solve a complex sub-goal.

SubPlanTaskExecutionConfigData(
    planning_goal = "Research JSON library options " +
                    "and implement a wrapper.",
    context = listOf("Must be Java 11 compatible")
)

For the full list of 60+ available tasks — including reasoning, writing, image generation, and game design — see the Task Planning documentation.

Integration

A. Custom Gradle Task

// buildSrc/src/main/kotlin/AiRefactorTask.kt
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Input
import com.simiacryptus.cognotik.util.UnifiedHarness
import com.simiacryptus.cognotik.plan.cognitive.*

abstract class AiRefactorTask : DefaultTask() {
    @get:Input
    abstract var instruction: String

    @TaskAction
    fun run() {
        val harness = UnifiedHarness(serverless = true)
        harness.start()

        harness.runPlan(
            prompt = instruction,
            cognitiveSettings = CognitiveModeConfig(
                type = CognitiveModeType.Waterfall
            ),
            workspace = project.projectDir
        )

        harness.stop()
    }
}

Register it in build.gradle.kts:

tasks.register<AiRefactorTask>("aiRefactor") {
    instruction = "Add KDoc comments to all public functions in src/main."
}

// Run with: ./gradlew aiRefactor

B. GitHub Actions Workflow

Build a CLI application (Fat JAR), then use it in a GitHub Actions workflow for automated code review and fixes:

name: AI Code Reviewer
on: [workflow_dispatch]

jobs:
  ai-fix:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'

      - name: Run Cognotik Agent
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          java -jar cognotik-cli.jar \
            --instruction "Review src/main for potential NPEs and fix them." \
            --workspace . \
            --mode waterfall

      - name: Archive Results
        uses: actions/upload-artifact@v4
        with:
          name: ai-results
          path: |
            results.md
            usage.json

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v5
        with:
          title: "🤖 AI Automated Fixes"
          body: "Auto-generated by Cognotik agent. See results.md for details."

C. Advanced Configuration

Fine-tune budget, safety limits, and model selection with the configuration lambda:

harness.runPlan(
    prompt = "Analyze and optimize database queries in src/dao/",
    cognitiveSettings = CognitiveModeConfig(
        type = CognitiveModeType.AdaptivePlanning
    ),
    config = { session, workspace ->
        OrchestrationConfig(
            sessionId  = session.sessionId,
            workingDir = workspace.absolutePath,

            // Model selection
            smartModel = OpenAIModels.GPT4o.asApiChatModel(),
            fastModel  = OpenAIModels.GPT35Turbo.asApiChatModel(),

            // Safety limits
            budget              = 2.00,   // Max $2.00 USD
            maxIterations       = 15,     // Max planning loops
            maxTasksPerIteration = 3,

            // Behavior
            autoFix     = true,
            temperature = 0.1   // Low temp for deterministic code
        )
    }
)

Best Practices

  1. Environment Variables — Ensure API keys are available where the JAR runs. The harness does not load from local .config files when a custom modelInstanceFn is used.
  2. Context Window — For large codebases, select a model with a large context window like gpt-4-turbo or claude-3-opus.
  3. Logging — Cognotik uses SLF4J. Add slf4j-simple to see the agent's reasoning process in your console output.
  4. Synchronous Execution — In serverless mode, the harness blocks the calling thread until completion — usually desired for CI/CD.
  5. Artifacts — The agent writes results.md and usage.json in the workspace. Archive these in your CI pipeline for audit trails.
  6. Budget Limits — Always set a budget in production to prevent runaway API costs. Start with $1–2 and adjust based on task complexity.

CTA

Ready to Embed AI in Your Pipeline?

Start with the Quick Start guide above, or explore the full task catalog to find the right tools for your workflow.

Actions: Get the Source · Full Documentation · Try the Desktop App