Documentation
¶
Index ¶
Constants ¶
const ( // DirArchive is the subdirectory for archived tasks within .context/. DirArchive = "archive" // DirClaude is the Claude Code configuration directory in the project root. DirClaude = ".claude" // DirClaudeHooks is the hooks subdirectory within .claude/. DirClaudeHooks = ".claude/hooks" // DirContext is the default context directory name. DirContext = ".context" // DirSessions is the subdirectory for session snapshots within .context/. DirSessions = "sessions" )
Directory path constants used throughout the application.
const ( // EntryTask represents a task entry in TASKS.md. EntryTask = "task" // EntryDecision represents an architectural decision in DECISIONS.md. EntryDecision = "decision" // EntryLearning represents a lesson learned in LEARNINGS.md. EntryLearning = "learning" // EntryConvention represents a code pattern in CONVENTIONS.md. EntryConvention = "convention" // EntryComplete represents a task completion action (marks the task as done). EntryComplete = "complete" // EntryUnknown is returned when user input doesn't match any known type. EntryUnknown = "unknown" )
Entry type constants for context updates.
These are the canonical internal representations used in switch statements for routing add/update commands to the appropriate handler.
const ( // FieldContext is the background/situation field for decisions and learnings. FieldContext = "context" // FieldRationale is the reasoning field for decisions (why this choice). FieldRationale = "rationale" // FieldConsequence is the outcomes field for decisions (what changes). FieldConsequence = "consequences" // FieldApplication is the usage field for learnings (how to apply going forward). FieldApplication = "application" // FieldLesson is the insight field for learnings (the key takeaway). FieldLesson = "lesson" )
Field name constants for structured entry attributes.
These are used in validation error messages and as attribute names in context-update XML tags for decisions and learnings.
const ( // EnvCtxDir is the environment variable for overriding the context directory. EnvCtxDir = "CTX_DIR" // EnvCtxTokenBudget is the environment variable for overriding the token budget. EnvCtxTokenBudget = "CTX_TOKEN_BUDGET" )
Environment configuration.
const ( // ClaudeBlockText is a text content block. ClaudeBlockText = "text" // ClaudeBlockThinking is an extended thinking content block. ClaudeBlockThinking = "thinking" // ClaudeBlockToolUse is a tool invocation block. ClaudeBlockToolUse = "tool_use" // ClaudeBlockToolResult is a tool execution result block. ClaudeBlockToolResult = "tool_result" )
Claude API content block types.
const ( // RoleUser is a user message. RoleUser = "user" // RoleAssistant is an assistant message. RoleAssistant = "assistant" )
Claude API message roles.
const ( // FileAutoSave is the hook script for auto-saving sessions. FileAutoSave = "auto-save-session.sh" // FileBlockNonPathScript is the hook script that blocks non-PATH ctx // invocations. FileBlockNonPathScript = "block-non-path-ctx.sh" // FilePromptCoach is the hook script for prompt quality feedback. FilePromptCoach = "prompt-coach.sh" // FileClaudeMd is the Claude Code configuration file in the project root. FileClaudeMd = "CLAUDE.md" // FileSettings is the Claude Code local settings file. FileSettings = ".claude/settings.local.json" )
Claude Code integration file names.
const ( // FileConstitution contains inviolable rules for agents. FileConstitution = "CONSTITUTION.md" // FileTask contains current work items and their status. FileTask = "TASKS.md" // FileConvention contains code patterns and standards. FileConvention = "CONVENTIONS.md" // FileArchitecture contains system structure documentation. FileArchitecture = "ARCHITECTURE.md" // FileDecision contains architectural decisions with rationale. FileDecision = "DECISIONS.md" // FileLearning contains gotchas, tips, and lessons learned. FileLearning = "LEARNINGS.md" // FileGlossary contains domain terms and definitions. FileGlossary = "GLOSSARY.md" // FileDrift contains staleness indicators and drift detection results. FileDrift = "DRIFT.md" // FileAgentPlaybook contains the meta-instructions for using the // context system. FileAgentPlaybook = "AGENT_PLAYBOOK.md" // FileDependency contains project dependency documentation. FileDependency = "DEPENDENCIES.md" )
Context file name constants for .context/ directory.
const ( // HeadingLearningStart is the Markdown heading for entries in LEARNINGS.md HeadingLearningStart = "## [" // HeadingLearnings is the Markdown heading for LEARNINGs.md HeadingLearnings = "# Learnings" // ColumnLearning is the singular column header for learning index tables. ColumnLearning = "Learning" )
Learnings
const ( // HeadingDecisions is the Markdown heading for DECISIONS.md HeadingDecisions = "# Decisions" // ColumnDecision is the singular column header for decision index tables. ColumnDecision = "Decision" )
Decisions
const ( // CommentOpen is the HTML comment opening tag. CommentOpen = "<!--" // CommentClose is the HTML comment closing tag. CommentClose = "-->" )
HTML comment markers for parsing and generation.
const ( // CtxMarkerStart marks the beginning of an embedded context block. CtxMarkerStart = "<!-- ctx:context -->" // CtxMarkerEnd marks the end of an embedded context block. CtxMarkerEnd = "<!-- ctx:end -->" )
Context block markers for embedding context in files.
const ( // IndexStart marks the beginning of an auto-generated index. IndexStart = "<!-- INDEX:START -->" // IndexEnd marks the end of an auto-generated index. IndexEnd = "<!-- INDEX:END -->" )
Index markers for auto-generated table of contents sections.
const ( // PrefixTaskUndone is the prefix for an unchecked task item. PrefixTaskUndone = "- [ ]" // PrefixTaskDone is the prefix for a checked (completed) task item. PrefixTaskDone = "- [x]" )
Task checkbox prefixes for Markdown task lists.
const ( // NewlineCRLF is the Windows new line. // // We check NewlineCRLF first, then NewlineLF to handle both formats. NewlineCRLF = "\r\n" // NewlineLF is Unix new line. NewlineLF = "\n" // Separator is a Markdown horizontal rule used between sections. Separator = "---" // Ellipsis is a Markdown ellipsis. Ellipsis = "..." // HeadingLevelOneStart is the Markdown heading for the first section. HeadingLevelOneStart = "# " // HeadingLevelTwoStart is the Markdown heading for subsequent sections. HeadingLevelTwoStart = "## " )
const (
// FileContextRC is the optional runtime configuration file.
FileContextRC = ".contextrc"
)
Runtime configuration constants.
const (
// MarkTaskComplete is the unchecked task marker.
MarkTaskComplete = "x"
)
const MaxDecisionsToSummarize = 3
MaxDecisionsToSummarize is the number of recent decisions to include in summaries.
const MaxLearningsToSummarize = 5
MaxLearningsToSummarize is the number of recent learnings to include in summaries.
const MaxPreviewLen = 60
MaxPreviewLen is the maximum length for preview lines before truncation.
const (
// ParserPeekLines is the number of lines to scan when detecting file format.
ParserPeekLines = 50
)
Parser configuration.
const WatchAutoSaveInterval = 5
WatchAutoSaveInterval is the number of updates between auto-saves in watch mode.
Variables ¶
var DefaultClaudePermissions = []string{
"Bash(ctx status:*)",
"Bash(ctx agent:*)",
"Bash(ctx add:*)",
"Bash(ctx session:*)",
"Bash(ctx tasks:*)",
"Bash(ctx loop:*)",
}
DefaultClaudePermissions lists the default permissions for ctx commands.
These permissions allow Claude Code to run ctx CLI commands without prompting for approval. All ctx subcommands are pre-approved.
var EntryPlural = map[string]string{ EntryTask: "tasks", EntryDecision: "decisions", EntryLearning: "learnings", EntryConvention: "conventions", }
EntryPlural maps entry type constants to their plural forms.
Used for user-facing messages (e.g., "no decisions found").
var FileReadOrder = []string{ FileConstitution, FileTask, FileConvention, FileArchitecture, FileDecision, FileLearning, FileGlossary, FileDrift, FileAgentPlaybook, }
FileReadOrder defines the priority order for reading context files.
The order follows a logical progression for AI agents:
CONSTITUTION — Inviolable rules. Must be loaded first so the agent knows what it cannot do before attempting anything.
TASKS — Current work items. What the agent should focus on.
CONVENTIONS — How to write code. Patterns and standards to follow.
ARCHITECTURE — System structure. Understanding of components and boundaries before making changes.
DECISIONS — Historical context. Why things are the way they are, to avoid re-debating settled decisions.
LEARNINGS — Gotchas and tips. Lessons from past work that inform current implementation.
GLOSSARY — Reference material. Domain terms and abbreviations for lookup as needed.
DRIFT — Staleness indicators. Lower priority since it's primarily for maintenance workflows.
AGENT_PLAYBOOK — Meta instructions. How to use this context system. Loaded last because it's about the system itself, not the work. The agent should understand the content before the operating manual.
var FileType = map[string]string{ EntryDecision: FileDecision, EntryTask: FileTask, EntryLearning: FileLearning, EntryConvention: FileConvention, }
FileType maps short names to actual file names.
var Packages = map[string]string{
"package.json": "Node.js dependencies",
"go.mod": "Go module dependencies",
"Cargo.toml": "Rust dependencies",
"requirements.txt": "Python dependencies",
"Gemfile": "Ruby dependencies",
}
Packages maps dependency manifest files to their descriptions.
Used by sync to detect projects and suggest dependency documentation.
var Patterns = []Pattern{
{".eslintrc*", "linting conventions"},
{".prettierrc*", "formatting conventions"},
{"tsconfig.json", "TypeScript configuration"},
{".editorconfig", "editor configuration"},
{"Makefile", "build commands"},
{"Dockerfile", "containerization"},
}
Patterns lists config files that should be documented in CONVENTIONS.md.
Used by sync to suggest documenting project configuration.
var RegExBulletItem = regexp.MustCompile(`(?m)^-\s*(.+)$`)
RegExBulletItem matches any Markdown bullet item (not just tasks).
Groups:
- 1: item content
var RegExContextUpdate = regexp.MustCompile(`<context-update(\s+[^>]+)>([^<]+)</context-update>`)
RegExContextUpdate matches context-update XML tags.
Groups:
- 1: opening tag attributes (e.g., ` type="task" context="..."`)
- 2: content between tags
var RegExDecision = regexp.MustCompile(`(?m)^## \[\d{4}-\d{2}-\d{2}-\d{6}].*$`)
RegExDecision matches decision entry headers in multiline content. Use for finding decision positions without capturing groups.
var RegExDecisionPatterns = []*regexp.Regexp{ regexp.MustCompile(`(?i)decided to\s+(.{20,100})`), regexp.MustCompile(`(?i)decision:\s*(.{20,100})`), regexp.MustCompile(`(?i)we('ll| will) use\s+(.{10,80})`), regexp.MustCompile(`(?i)going with\s+(.{10,80})`), regexp.MustCompile(`(?i)chose\s+(.{10,80})\s+(over|instead)`), }
RegExDecisionPatterns detects decision-like phrases in text.
var RegExEntryHeader = regexp.MustCompile(
`## \[(\d{4}-\d{2}-\d{2})-(\d{6})] (.+)`,
)
RegExEntryHeader matches entry headers like "## [2026-01-28-051426] Title here".
Groups:
- 1: date (YYYY-MM-DD)
- 2: time (HHMMSS)
- 3: title
var RegExEntryHeading = regexp.MustCompile(`(?m)^## \[`)
RegExEntryHeading matches any entry heading (## [timestamp]). Use for counting entries without capturing groups.
var RegExGlossary = regexp.MustCompile(`(?m)(?:^|\n)\s*(?:-\s*)?\*\*[^*]+\*\*`)
RegExGlossary matches glossary definition entries (lines with **term**).
var RegExLearning = regexp.MustCompile(`(?m)^- \*\*\[\d{4}-\d{2}-\d{2}]\*\*.*$`)
RegExLearning matches learning entry headers in multiline content. Use for finding learning positions without capturing groups.
var RegExLearningPatterns = []*regexp.Regexp{ regexp.MustCompile(`(?i)learned that\s+(.{20,100})`), regexp.MustCompile(`(?i)gotcha:\s*(.{20,100})`), regexp.MustCompile(`(?i)lesson:\s*(.{20,100})`), regexp.MustCompile(`(?i)TIL:?\s*(.{20,100})`), regexp.MustCompile(`(?i)turns out\s+(.{20,100})`), regexp.MustCompile(`(?i)important to (note|remember):\s*(.{20,100})`), }
RegExLearningPatterns detects learning-like phrases in text.
var RegExLineNumber = regexp.MustCompile(`(?m)^\s*\d+→`)
RegExLineNumber matches Claude Code's line number prefixes like " 1→".
var RegExNonFileNameChar = regexp.MustCompile(`[^a-zA-Z0-9-]+`)
RegExNonFileNameChar matches characters not allowed in file names.
var RegExPath = regexp.MustCompile("`([^`]+\\.[a-zA-Z]{1,5})`")
RegExPath matches file paths in Markdown backticks.
Groups:
- 1: file path
var RegExPhase = regexp.MustCompile(`^#{1,6}\s+Phase`)
RegExPhase matches phase headers at any heading level (e.g., "## Phase 1", "### Phase").
var RegExTask = regexp.MustCompile(regExTaskPattern)
RegExTask matches a task item on a single line.
Use with MatchString or FindStringSubmatch on individual lines. For multiline content, use RegExTaskMultiline.
var RegExTaskDoneTimestamp = regexp.MustCompile(`#done:(\d{4}-\d{2}-\d{2}-\d{6})`)
RegExTaskDoneTimestamp extracts the #done: timestamp from a task line.
Groups:
- 1: timestamp (YYYY-MM-DD-HHMMSS)
var RegExTaskMultiline = regexp.MustCompile(`(?m)` + regExTaskPattern)
RegExTaskMultiline matches task items across multiple lines.
Use with FindAllStringSubmatch on multiline content.
var RequiredFiles = []string{ FileConstitution, FileTask, FileDecision, }
RequiredFiles lists the essential context files that must be present.
These are the files created with `ctx init --minimal` and checked by drift detection for missing files.
Functions ¶
func RegExFromAttrName ¶ added in v0.2.0
RegExFromAttrName creates a regex to extract an XML attribute value by name.
Parameters:
- name: The attribute name to match
Returns:
- *regexp.Regexp: Pattern matching name="value" with value in group 1
func UserInputToEntry ¶ added in v0.2.0
UserInputToEntry normalizes user input to a canonical entry type.
Accepts both singular and plural forms (e.g., "task" or "tasks") and returns the canonical singular form. Matching is case-insensitive. Unknown inputs return EntryUnknown.
Parameters:
- s: User-provided entry type string
Returns:
- string: Canonical entry type constant (EntryTask, EntryDecision, etc.)