> For the complete documentation index, see [llms.txt](https://docs.gitloom.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gitloom.cloud/documentation/go.md).

# Go

```bash
go get github.com/GitLoomHQ/gitloom-go/gitloom   # current: v0.6.0
```

A **drop-in replacement for** [**karma**](https://github.com/MelloB1989/karma)**'s completion calls** — same method signatures; a `ChatId` makes the conversation manage itself.

## Drop-in

```go
client := gitloom.New("") // reads GITLOOM_API_KEY

kai := gitloom.WrapKarma(
    ai.NewKarmaAI(ai.GPT4o, ai.OpenAI),   // the karma you already use
    client,
    gitloom.ConversationOptions{Model: "gpt-4o", Namespace: userID},
)

// karma's own signature — switch the receiver, change nothing else.
resp, _ := kai.ChatCompletion(models.AIChatHistory{
    ChatId:   "chat-42", // ← the only change
    Messages: []models.AIMessage{{Role: models.User, Message: "What camera do I own?"}},
})
```

Pass **only the new messages — never append anything**. Behind the call: the stored conversation supplies the earlier turns, memory is retrieved and injected as background, both turns are stored with karma's real token count, compaction runs on cadence or window pressure, and every compaction feeds the summarized turns to memory ingestion. No `ChatId` passes straight through. `ChatCompletionStream` works identically — chunks stream through your callback, the exchange is stored at the end.

Compaction is your choice: `Summarize: gitloom.KarmaSummarizer(kai)` runs locally on your model; `SummarizeServer: true` hands it to GitLoom's model.

## Added features, on the same wrapper

```go
conv, _ := kai.Conversation(ctx, "chat-42")   // the SAME managed conversation

conv.Rewind(ctx, 6)
conv.Edit(ctx, 4, models.AIMessage{Role: models.User, Message: "ask differently"})
conv.EditInPlace(ctx, 4, "[redacted]")
conv.SetTitle(ctx, "Camera shopping")
conv.Branches(ctx)
```

A rewind or edit here is what the next `ChatCompletion` continues from. Data-URL images and files in `AIMessage` are uploaded transparently and stored by reference.

## Recall, filtered and answered

`kai.Memory()` — or the bare `*gitloom.Client` — reaches the memory directly.

```go
mem := kai.Memory()

// Ranked memories, no model call. Milliseconds.
res, _ := mem.Recall(ctx, "what camera do I own", &gitloom.RecallOptions{
    Tiers:    []string{"facts"},        // facts, incidents, rules, skills
    Paths:    []string{"facts/gear"},   // any directories
    Tags:     []string{"camera"},
    Since:    time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
    MinScore: 0.3,
    Limit:    8,
})
for _, m := range res.Memories {
    fmt.Printf("%.2f %s %v\n%s\n", m.Score, m.Path, m.Matched, m.Content)
}

// One text answer from a fast model over that retrieval …
ans, _ := mem.Answer(ctx, "what camera do I own", nil)
// … or let a stronger model search the memory itself with tools.
agentic, _ := mem.Answer(ctx, "which of my trips had the longest flight",
    &gitloom.RecallOptions{Mode: gitloom.ModeAgentic})
fmt.Println(agentic.Answer, agentic.Trace)
```

Each entry is **one whole memory**, not a scattering of its sections — `Content` is the full body and `Sections` names the headings that matched. `Score` is a calibrated relevance in `[0, 1]`, comparable across queries, so `MinScore` means the same thing whatever was asked. `Matched` says which arms produced it; matched only by `graph` is context that rode in beside a real match, and `Via` names what pulled it in. Set `Detail: "full"` for revision history, the last diff, relation snippets and cues.

Filters apply **inside every retrieval arm** server-side, so confining a query to a directory is a real boundary rather than a cut made after the fact.

`Answer` is metered as a chat, not a read, and returns `gitloom.ErrNoAnswer` rather than an empty string when the model finds nothing to say.

## Tags and when it happened

```go
// Every memory drawn from this conversation carries the tags, and is dated to
// when it happened rather than when it was sent.
turns := []gitloom.Turn{{Role: "user", Content: "We just checked in near Gion."}}
err := mem.Remember(ctx, turns, &gitloom.RememberOptions{
    Tags:       []string{"trip", "japan"},
    OccurredAt: gitloom.Date("2026-05-14T19:30"), // read in Timezone
    Timezone:   "Asia/Kolkata",
})
```

`OccurredAt` takes `gitloom.At(t)` for an instant, sent as epoch seconds; `gitloom.Unix(sec)`; `gitloom.Day(2026, time.May, 14)` for a calendar day with no time of day; or `gitloom.Date(s)` for text the server reads: a date, RFC 3339 with an offset, or a datetime without one, read in `Timezone`. The `Date` fields it replaces still work and are deprecated.

Tags are trimmed and lowercased, and hold letters, digits, spaces and `- _ . : / # @`, up to 32 tags of 64 characters. One that breaks the rules refuses the write with an `*APIError` whose `Code` is `invalid_tag` and whose message names it.

Recall reports them back:

```go
res, _ := mem.Recall(ctx, "where did I stay in Kyoto", nil)
for _, m := range res.Memories {
    when := m.OccurredAt.Format(time.RFC3339)
    if m.OccurredPrecision == "day" {
        when = m.OccurredAt.Format(time.DateOnly) // only the date is known
    }
    fmt.Println(m.Path, m.UserTags, when, m.OccurredSource)
}
```

`UserTags` holds yours alone, lowercased and sorted rather than in the order you sent them; `Tags` lists those first, then the ones GitLoom inferred, also sorted. `CreatedAt`, `UpdatedAt`, `OccurredAt` and `ExpiresAt` are `time.Time` in UTC, zero when absent. `OccurredSource` says how the time is known: `user` (you said), `extracted` (the memory names the day), `said` (when its conversation happened) or `written`. The `Created` and `Updated` strings are deprecated.

## Listing without a question

```go
// Every memory tagged "lease" whose subject happened since March, newest first.
leases, _ := mem.Recall(ctx, "", &gitloom.RecallOptions{
    Tags:      []string{"lease"},
    TimeField: gitloom.TimeOccurred,
    Since:     time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC),
})
```

Leave the query empty and give at least one filter (`Tags`, `TagsAll`, `Since`, `Until`, `Tiers` or `Paths`) to list every memory the filters match, newest first, each scoring 1. The mode must be raw and `Rank` unset. With neither a query nor a filter, `Recall` returns `gitloom.ErrNoQuery` without calling the API. `TimeField` picks the time `Since` and `Until` bound, and orders the listing: `TimeOccurred` (when the memory's subject happened), `TimeCreated`, or `TimeUpdated` (the default).

## Direct memory

`Remember` has a model decide what a conversation holds. These are the other half, for when you already know what a memory says and where it belongs, such as in a migration or an agent filing its own conclusion:

```go
err := mem.Write(ctx, []gitloom.NewMemory{{
    Path:       "facts/people/maya.md",
    Content:    "Maya rides a bicycle to work and prefers morning meetings.",
    Tags:       []string{"people", "colleague"},
    OccurredAt: gitloom.Day(2026, time.July, 19), // what it is about, not now
    Cues:       []string{"how does Maya commute"},
    Related:    []string{"manager: facts/people/sam.md"},
}}, nil)

// Seconds later, once the write has landed:
m, _ := mem.Get(ctx, "facts/people/maya.md", nil) // a file, or file.md#section
tree, _ := mem.Tree(ctx, &gitloom.TreeOptions{Path: "facts", Depth: 3})
topics, _ := mem.Topics(ctx, &gitloom.TopicsOptions{Like: "databas"})
graph, _ := mem.Graph(ctx, nil)
err = mem.Forget(ctx, []string{"facts/people/maya.md"}, nil)
```

`Tree` is the table of contents a navigator descends instead of guessing at search terms. `Topics` is what you call before filing under a new topic, so `facts/databases` is not invented beside an existing `facts/database`. `Write` and `Forget` are asynchronous like `Remember`, and `Forget` leaves earlier revisions in git history. Send writes in batches: one call is one commit round and one push.

## Vocabulary and skills

```go
// Teach abbreviations and domain terms. A recall for "k8s" then also finds
// memories written "kubernetes", and the definition comes back as Defined.
mem.LearnTerms(ctx, []gitloom.Term{{
    Term:       "kubernetes",
    Aliases:    []string{"k8s", "kube"},
    Definition: "Container orchestration.",
}}, "")
mem.LookupTerm(ctx, "k8s", "")                                  // → Term, true, nil
mem.Vocabulary(ctx, &gitloom.VocabOptions{Like: "kube"})
mem.ForgetTerms(ctx, []string{"kubernetes"}, "")

// Store how things are done; find the skill that fits a task.
mem.StoreSkills(ctx, []gitloom.Skill{{
    Name:        "Deploy to production",
    Topic:       "ops",
    Description: "Ship a release.",
    Content:     "## Steps\n1. Tag the release.\n2. `make deploy ENV=prod`",
    Triggers:    []string{"how do I ship a release", "deploy to prod"},
}}, "")
skills, _ := mem.FindSkills(ctx, "release the new build", nil)
```

Skills are memories under the `skills/` tier, so a recall with `Tiers: []string{"skills"}` reaches them too.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.gitloom.cloud/documentation/go.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
