Library Stable Maven Central

Embedding Cognotik

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.

Key Capabilities

Everything you need to integrate AI agents into your software lifecycle.

Headless Execution

Run agents without a UI using serverless = true. Perfect for background jobs, scripts, and server-side processing.

CI/CD Integration

Embed agents in GitHub Actions or Jenkins to perform code reviews, auto-fixes, or documentation generation on every push.

Gradle Plugin

Wrap agent tasks in custom Gradle tasks to automate boilerplate generation as part of your build process.

UnifiedHarness API

A simple entry point to configure models, inject API keys, and execute plans or individual tasks programmatically.

Cognitive Modes

Choose from Waterfall, Adaptive, Conversational, and more — each optimized for different problem types.

Budget & Safety

Set spending limits, iteration caps, and temperature controls. Full auditability with usage logs and result artifacts.

Developer Guide

From installation to production deployment — everything in one place.

1. Add the Dependency

Add the core library to your build.gradle.kts:

Kotlin DSL
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:

Kotlin
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.

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.

Kotlin
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

  • workspace — The directory the agent reads/writes. Pass File(".") for CI/CD, or null for a temp directory.
  • autoFix — Set to true for unattended execution. If false, the agent may pause waiting for human confirmation.
  • cognitiveSettings — The planning strategy:
    • Waterfall — Plans everything first, then executes sequentially. Best for predictable tasks.
    • AdaptivePlanning — Think → Act → Reflect loops. Best for research or debugging.
    • Conversational — One task at a time with history. Best for interactive use.

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.

Kotlin
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
    )
}

Every task requires two configuration objects: TaskTypeConfig (static tool settings) and TaskExecutionConfig (runtime job inputs). Here are the most commonly embedded tasks:

File

FileModificationTask

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
)
File

FileAppendTask

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")
)
Analysis

ReadDocumentsTask

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"
)
Analysis

FileSearchTask

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
)
Execution

RunToolTask

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

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

SubPlanTask

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.

A. Custom Gradle Task

Wrap the harness in a Gradle task to add AI capabilities directly to your build pipeline.

Kotlin
// 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()
    }
}

Then register it in your build.gradle.kts:

Kotlin DSL
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:

YAML
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:

Kotlin
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

Tips for reliable headless execution in production environments.

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.

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.