|
| 1 | +# Cheat Sheets |
| 2 | + |
| 3 | +Quick mental models for key lifecycles and flows in ctx. |
| 4 | + |
| 5 | +## CLI Command Dispatch |
| 6 | + |
| 7 | +Steps: |
| 8 | +1. `cmd/ctx/main.go` calls `bootstrap.RootCmd()` |
| 9 | +2. RootCmd creates Cobra root with global flags |
| 10 | +3. `Initialize()` registers 34 commands in 8 groups |
| 11 | +4. PersistentPreRunE fires: boundary check, init check |
| 12 | +5. Cobra routes to matched command's Run() handler |
| 13 | +6. Handler calls core/ logic, domain packages |
| 14 | +7. Output via write/* package, errors via err/* package |
| 15 | + |
| 16 | +Key invariants: |
| 17 | +- PersistentPreRunE runs for ALL subcommands |
| 18 | +- AnnotationSkipInit bypasses init check (doctor, guide, setup) |
| 19 | +- All flag descriptions from YAML (enforced by audit) |
| 20 | + |
| 21 | +Common failure modes: |
| 22 | +- Missing .context/ without SkipInit -> error before Run() |
| 23 | +- Flag name collision with global flag -> silent shadowing |
| 24 | + |
| 25 | +``` |
| 26 | + main.go --> RootCmd() --> PersistentPreRunE --> Run() |
| 27 | + | | | |
| 28 | + Initialize() boundary + core/ logic |
| 29 | + 34 commands init guards --> write/* |
| 30 | +``` |
| 31 | + |
| 32 | +--- |
| 33 | + |
| 34 | +## Context Loading (ctx agent) |
| 35 | + |
| 36 | +Steps: |
| 37 | +1. Agent calls `ctx agent --budget N` |
| 38 | +2. rc.TokenBudget() resolves budget (flag > env > .ctxrc > 8000) |
| 39 | +3. context/load.Do() reads all .md files from .context/ |
| 40 | +4. Files sorted by config.FileReadOrder priority |
| 41 | +5. Each file's tokens estimated (4 chars/token) |
| 42 | +6. Files added in priority order until budget exhausted |
| 43 | +7. Overflow files listed as "Also Noted" summaries |
| 44 | +8. Markdown packet returned to stdout |
| 45 | + |
| 46 | +Key invariants: |
| 47 | +- CONSTITUTION always loaded first |
| 48 | +- Symlinks rejected (M-2 defense) |
| 49 | +- Budget is conservative overestimate (never under-counts) |
| 50 | + |
| 51 | +Common failure modes: |
| 52 | +- Very large TASKS.md consumes most of budget -> low-priority |
| 53 | + files (GLOSSARY, PLAYBOOK) never seen by agent |
| 54 | +- Empty file detection via EffectivelyEmpty() -> skipped with note |
| 55 | + |
| 56 | +``` |
| 57 | + Agent --> rc.TokenBudget() --> load.Do() |
| 58 | + | | |
| 59 | + resolve priority read + estimate tokens |
| 60 | + | | |
| 61 | + sort by order fit to budget |
| 62 | + | | |
| 63 | + format packet "Also Noted" overflow |
| 64 | +``` |
| 65 | + |
| 66 | +--- |
| 67 | + |
| 68 | +## MCP Request Lifecycle |
| 69 | + |
| 70 | +Steps: |
| 71 | +1. Client sends JSON-RPC line to stdin |
| 72 | +2. Server.Serve() reads line from scanner |
| 73 | +3. parse.Request() unmarshals JSON |
| 74 | +4. dispatch.Do() routes by method name |
| 75 | +5. Handler executes domain logic |
| 76 | +6. session.CheckGovernance() appends warnings |
| 77 | +7. out.*Response() wraps result |
| 78 | +8. io.Writer.WriteJSON() writes to stdout |
| 79 | + |
| 80 | +Key invariants: |
| 81 | +- Main loop is single-threaded (sequential processing) |
| 82 | +- Governance is advisory only (never blocks) |
| 83 | +- Notifications (no ID) produce no response |
| 84 | +- Poller runs independently on 5s interval |
| 85 | + |
| 86 | +Common failure modes: |
| 87 | +- Slow handler blocks all subsequent requests |
| 88 | +- Parse error -> error response, loop continues |
| 89 | +- Scanner overflow -> truncated JSON -> parse error |
| 90 | + |
| 91 | +``` |
| 92 | + Client Server Handler |
| 93 | + |--JSON-RPC line------>| | |
| 94 | + | |--parse() | |
| 95 | + | |--dispatch()------>| |
| 96 | + | | |--domain logic |
| 97 | + | | |--governance check |
| 98 | + | |<--result----------| |
| 99 | + |<--JSON-RPC response--| | |
| 100 | +``` |
| 101 | + |
| 102 | +--- |
| 103 | + |
| 104 | +## Journal Import Pipeline |
| 105 | + |
| 106 | +Steps: |
| 107 | +1. User runs `ctx journal source --all` |
| 108 | +2. parser.FindSessionsForCWD() scans ~/.claude/projects/ |
| 109 | +3. Auto-detects format (JSONL, Copilot, Copilot CLI, Markdown) |
| 110 | +4. Matches sessions by git remote URL and CWD |
| 111 | +5. Loads journal state from .state.json |
| 112 | +6. Plans each session: new, regen, skip, or locked |
| 113 | +7. Formats matched sessions as Markdown |
| 114 | +8. Writes to .context/journal/ |
| 115 | +9. Marks imported in state, saves state |
| 116 | + |
| 117 | +Key invariants: |
| 118 | +- Locked entries never regenerated |
| 119 | +- State tracks 5 stages: exported -> enriched -> normalized |
| 120 | + -> fences_verified -> locked |
| 121 | +- Atomic state writes (temp + rename) |
| 122 | + |
| 123 | +Common failure modes: |
| 124 | +- Changed JSONL format -> silent parse failures, empty sessions |
| 125 | +- Same project in multiple paths -> duplicate imports |
| 126 | +- 1MB buffer limit -> truncated large tool results |
| 127 | + |
| 128 | +``` |
| 129 | + [Scan] --> [Detect Format] --> [Match CWD] |
| 130 | + | | | |
| 131 | + 4 parsers auto-detect git remote |
| 132 | + | | | |
| 133 | + [Plan] ----> [Format MD] ----> [Write] |
| 134 | + | | |
| 135 | + state check mark imported |
| 136 | +``` |
| 137 | + |
| 138 | +--- |
| 139 | + |
| 140 | +## Hook Lifecycle (UserPromptSubmit) |
| 141 | + |
| 142 | +Steps: |
| 143 | +1. Claude Code fires UserPromptSubmit hook |
| 144 | +2. hooks.json routes to `ctx system check-*` commands |
| 145 | +3. system/input.go reads hook JSON from stdin (2s timeout) |
| 146 | +4. Each check runs independently, writes result to stdout |
| 147 | +5. Checks: context-size, ceremonies, persistence, journal, |
| 148 | + reminders, version, resources, knowledge, map-staleness, |
| 149 | + memory-drift, freshness, heartbeat |
| 150 | +6. Advisory output returned to Claude Code |
| 151 | +7. All hooks exit 0 (never block initialization) |
| 152 | + |
| 153 | +Key invariants: |
| 154 | +- 2-second stdin read timeout (prevents hanging) |
| 155 | +- Daily throttle via marker file date comparison |
| 156 | +- Adaptive prompt counter: silent 1-15, periodic 16+ |
| 157 | +- All hooks exit 0 (never block) |
| 158 | + |
| 159 | +Common failure modes: |
| 160 | +- Missing stdin JSON -> timeout, graceful empty response |
| 161 | +- Throttle marker file corruption -> check runs every prompt |
| 162 | + |
| 163 | +``` |
| 164 | + Claude Code hooks.json ctx system check-* |
| 165 | + |--hook fire------->| | |
| 166 | + | |--route--------->| |
| 167 | + | | (12 checks) |--read stdin (2s) |
| 168 | + | | |--check logic |
| 169 | + | | |--throttle gate |
| 170 | + |<--advisory--------|<--result (0)----| |
| 171 | +``` |
| 172 | + |
| 173 | +--- |
| 174 | + |
| 175 | +## Entry Write Flow |
| 176 | + |
| 177 | +Steps: |
| 178 | +1. Caller provides EntryParams (type, content, opts) |
| 179 | +2. entry.Validate() checks required fields per type |
| 180 | + - Decision: context, rationale, consequence |
| 181 | + - Learning: context, lesson, application |
| 182 | + - Task/Convention: content only |
| 183 | +3. entry.Write() reads existing file |
| 184 | +4. Formats entry per type template (from tpl/) |
| 185 | +5. Inserts at correct position (tasks: before first unchecked) |
| 186 | +6. Writes file back via io.SafeWriteFile() |
| 187 | +7. Updates index for decisions/learnings (not tasks/conventions) |
| 188 | + |
| 189 | +Key invariants: |
| 190 | +- Entry headers are timestamped: `## [YYYY-MM-DD-HHMMSS] Title` |
| 191 | +- Index updated between INDEX:START/END markers |
| 192 | +- Three callers: CLI add, MCP handler, watch command |
| 193 | + |
| 194 | +Common failure modes: |
| 195 | +- Concurrent writes -> last writer wins (no locking) |
| 196 | +- Index update fails after write -> stale index |
| 197 | +- Missing required field -> validation error before write |
| 198 | + |
| 199 | +``` |
| 200 | + Caller --> Validate() --> Write() |
| 201 | + | | |
| 202 | + check fields read-modify-write |
| 203 | + | | |
| 204 | + type-specific format + insert |
| 205 | + | | |
| 206 | + error early update index |
| 207 | +``` |
| 208 | + |
| 209 | +--- |
| 210 | + |
| 211 | +## Execution Flow Index (enriched 2026-04-03 via GitNexus) |
| 212 | + |
| 213 | +_Auto-detected from the call graph. Complements the manually |
| 214 | +written cheat sheets above._ |
| 215 | + |
| 216 | +Top cross-community flows (spanning multiple domains): |
| 217 | + |
| 218 | +| Flow | Steps | Entry Point | Key Symbols | |
| 219 | +|------|-------|-------------|-------------| |
| 220 | +| Deploy -> ContextDir | 10 | initialize | DeployTemplates, Do, ContextDir | |
| 221 | +| Deploy -> Symlinks | 10 | initialize | DeployTemplates, Do, Symlinks | |
| 222 | +| Write -> Init | 10 | MCP server | Serve, Init, SafeWriteFile | |
| 223 | +| Write -> Server | 10 | MCP server | Serve, New, Do | |
| 224 | +| Write -> TokenBudget | 10 | MCP server | Serve, TokenBudget, Do | |
| 225 | +| Run -> Init | 10 | CLI commands | Run, Do, Init | |
| 226 | +| Sync -> ContextDir | 10 | sync cmd | Run, Do, ContextDir | |
| 227 | +| Run -> Text | 9 | CLI commands | Run, Do, desc.Text | |
| 228 | +| Run -> URI | 9 | CLI commands | Run, catalog, URI | |
| 229 | +| Run -> NotFoundError | 8 | CLI commands | Run, Do, NotFound | |
| 230 | + |
| 231 | +### Multi-Flow Hotspots |
| 232 | + |
| 233 | +Symbols participating in 3+ flows (high-impact modification points): |
| 234 | + |
| 235 | +| Symbol | Flows | Location | |
| 236 | +|--------|-------|----------| |
| 237 | +| desc.Text | 53 | internal/assets/read/desc/desc.go:75 | |
| 238 | +| load.Do | 100+ | internal/context/load/loader.go:34 | |
| 239 | +| SafeWriteFile | 69 callers | internal/io/security.go | |
| 240 | +| rc.ContextDir | 20+ | internal/rc/rc.go | |
| 241 | +| validate.Symlinks | 10+ | internal/validate/path.go | |
| 242 | +| err/context.NotFound | 30+ | internal/err/context/context.go | |
| 243 | +| rc.RC | 15+ | internal/rc/rc.go | |
0 commit comments