cotext 0.1.3

Structured project context for humans and coding agents, with a CLI and ratatui TUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

use crate::storage::Project;

const START_MARKER: &str = "<!-- COTEXT:START -->";
const END_MARKER: &str = "<!-- COTEXT:END -->";

#[derive(Clone, Debug, Default)]
pub struct InstallReport {
    pub changed: Vec<PathBuf>,
    pub removed: Vec<PathBuf>,
    pub skipped: Vec<PathBuf>,
}

impl InstallReport {
    fn record_changed(&mut self, path: PathBuf) {
        self.changed.push(path);
    }

    fn record_skipped(&mut self, path: PathBuf) {
        self.skipped.push(path);
    }

    fn record_removed(&mut self, path: PathBuf) {
        self.removed.push(path);
    }
}

pub fn install_codex(
    project: &Project,
    codex_skill_dir: Option<&Path>,
    overwrite: bool,
) -> Result<InstallReport> {
    let mut report = InstallReport::default();
    let agents_path = project.root.join("AGENTS.md");
    let agents_block = codex_agents_block(project);
    upsert_marked_markdown(
        &agents_path,
        "# AGENTS.md\n\n",
        &agents_block,
        overwrite,
        &mut report,
    )?;

    let project_skill_root = default_codex_skill_root(project);
    remove_legacy_codex_skill_root(project, &mut report)?;
    write_codex_skill_bundle(project, &project_skill_root, overwrite, &mut report)?;

    if let Some(skill_dir) = codex_skill_dir
        && skill_dir != project_skill_root.as_path()
    {
        write_codex_skill_bundle(project, skill_dir, overwrite, &mut report)?;
    }

    Ok(report)
}

pub fn install_claude(project: &Project, overwrite: bool) -> Result<InstallReport> {
    let mut report = InstallReport::default();
    let claude_path = project.root.join("CLAUDE.md");
    upsert_marked_markdown(
        &claude_path,
        "# CLAUDE.md\n\n",
        &claude_agents_block(project),
        overwrite,
        &mut report,
    )?;

    let skill_root = project
        .root
        .join(".claude")
        .join("skills")
        .join("cotext-context");
    write_file(
        &skill_root.join("SKILL.md"),
        &claude_skill_md(project),
        overwrite,
        &mut report,
    )?;

    let commands_root = project.root.join(".claude").join("commands");
    write_file(
        &commands_root.join("cotext.md"),
        &claude_context_command(project),
        overwrite,
        &mut report,
    )?;
    write_file(
        &commands_root.join("cotext-sync.md"),
        &claude_sync_command(project),
        overwrite,
        &mut report,
    )?;

    Ok(report)
}

fn upsert_marked_markdown(
    path: &Path,
    header: &str,
    block: &str,
    _overwrite: bool,
    report: &mut InstallReport,
) -> Result<()> {
    let payload = format!("{START_MARKER}\n{block}\n{END_MARKER}\n");
    let next = if path.exists() {
        let current = fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        if let Some(start) = current.find(START_MARKER) {
            if let Some(end) = current.find(END_MARKER) {
                let end = end + END_MARKER.len();
                let mut updated = String::new();
                updated.push_str(&current[..start]);
                if !updated.ends_with('\n') {
                    updated.push('\n');
                }
                updated.push_str(&payload);
                if end < current.len() {
                    updated.push_str(current[end..].trim_start_matches('\n'));
                    updated.push('\n');
                }
                updated
            } else {
                format!("{current}\n{payload}")
            }
        } else {
            format!("{current}\n{payload}")
        }
    } else {
        format!("{header}{payload}")
    };

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    fs::write(path, next).with_context(|| format!("failed to write {}", path.display()))?;
    report.record_changed(path.to_path_buf());
    Ok(())
}

fn write_codex_skill_bundle(
    project: &Project,
    root: &Path,
    overwrite: bool,
    report: &mut InstallReport,
) -> Result<()> {
    write_file(
        &root.join("SKILL.md"),
        &codex_skill_md(project),
        overwrite,
        report,
    )?;
    write_file(
        &root.join("agents").join("openai.yaml"),
        CODEX_OPENAI_YAML,
        overwrite,
        report,
    )?;
    Ok(())
}

fn default_codex_skill_root(project: &Project) -> PathBuf {
    project
        .root
        .join(".codex")
        .join("skills")
        .join("cotext-context")
}

fn legacy_codex_skill_root(project: &Project) -> PathBuf {
    project
        .root
        .join(".cotext")
        .join("agents")
        .join("codex")
        .join("cotext-context")
}

fn remove_legacy_codex_skill_root(project: &Project, report: &mut InstallReport) -> Result<()> {
    let legacy_root = legacy_codex_skill_root(project);
    if legacy_root.exists() {
        fs::remove_dir_all(&legacy_root)
            .with_context(|| format!("failed to remove {}", legacy_root.display()))?;
        report.record_removed(legacy_root);
    }
    Ok(())
}

fn write_file(
    path: &Path,
    contents: &str,
    overwrite: bool,
    report: &mut InstallReport,
) -> Result<()> {
    if path.exists() && !overwrite {
        report.record_skipped(path.to_path_buf());
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))?;
    report.record_changed(path.to_path_buf());
    Ok(())
}

fn codex_agents_block(project: &Project) -> String {
    let project_name = &project.config.name;
    format!(
        r#"## Cotext Workflow

Use `cotext` as the canonical project context manager for `{project_name}`.

### Startup

- Read the current packet with `cotext render --audience codex` before substantial work.
- Commands prefer global cotext storage by default and fall back to repo-local storage when no matching global project exists; use `--storage local` to force repo-local management.
- If the task is about "next", "continue", or resuming active work, also inspect `cotext list --category todo` and `cotext list --category deferred`.
- If the task is scoped, narrow with `cotext list --category <category>`, `cotext render --category <category> --audience codex`, or `cotext show <id>`.

### Sync Rules

- Write back meaningful design, progress, note, todo, or deferred changes through `cotext new`, `cotext update`, or `cotext tui`.
- If you append or refresh the managed cotext block in the target project's `AGENTS.md` or `CLAUDE.md`, treat that as durable guidance work and sync the relevant cotext entry before handoff.
- Prefer `cotext` commands over hand-editing the managed cotext entry markdown on disk unless you are repairing broken metadata or debugging cotext itself.
- Use `cotext update <id> --append ...` for incremental progress and `cotext update <id> --status done` when closing tracked work.
- If the work introduced a new durable decision or follow-up item, create a new entry instead of overloading an unrelated one.

### Category Guide

- `design`: architecture decisions, invariants, tradeoffs, or storage-model changes.
- `note`: warnings, operational caveats, and facts later agents should stay aware of.
- `progress`: shipped implementation state, evidence, validation, and the next step.
- `todo`: the next actionable task with a concrete goal and acceptance criteria.
- `deferred`: future work that is real but intentionally postponed.

### Generated Assets

- The project-local Codex skill scaffold lives under `.codex/skills/cotext-context/`.
- Refresh Codex guidance with `cotext agent install codex --overwrite`.
- Use `--codex-skill-dir <path>` only when you also need a second copy in another Codex skill directory.
"#
    )
}

fn claude_agents_block(project: &Project) -> String {
    let project_name = &project.config.name;
    format!(
        r#"## Cotext Workflow

Use `cotext` as the canonical project context manager for `{project_name}`.

### Startup

- Refresh context with `cotext render --audience claude` before coding.
- Commands prefer global cotext storage by default and fall back to repo-local storage when no matching global project exists; use `--storage local` to force repo-local management.
- If the task is about resuming work, next work, or deferred work, inspect `cotext list --category todo` and `cotext list --category deferred`.
- Narrow the read with `cotext render --category <category> --audience claude` or `cotext show <id>` when only one slice matters.

### Sync Rules

- Use `.claude/commands/cotext.md` to load the authoritative packet inside Claude Code.
- Use `.claude/commands/cotext-sync.md` after meaningful work to sync design, progress, note, todo, or deferred changes.
- If you append or refresh the managed cotext block in the target project's `AGENTS.md` or `CLAUDE.md`, record that guidance change in cotext before handoff.
- Prefer `cotext update` and `cotext new` over manual edits to the managed cotext entry markdown on disk unless the tool itself is the thing being repaired.

### Generated Assets

- Project-local skill instructions live under `.claude/skills/cotext-context/`.
- Refresh Claude guidance with `cotext agent install claude --overwrite`.
"#
    )
}

fn codex_skill_md(project: &Project) -> String {
    let project_name = &project.config.name;
    format!(
        r#"---
name: cotext-context
description: Read and update structured project context for {project_name} with cotext. Use when you need the current design, awareness notes, progress, active todos, deferred work, or a reliable workflow for syncing those back after implementation.
---

# Cotext Context

## Goal

Use `cotext` as the canonical context layer for `{project_name}`. The normal loop is:

1. Load the packet.
2. Narrow it if the task is scoped.
3. Perform the implementation or analysis.
4. Sync back any durable design, note, progress, todo, or deferred changes before handoff.

## Default operating sequence

1. Start with `cotext render --audience codex`.
2. Commands prefer global cotext storage by default and fall back to repo-local storage when no matching global project exists; use `--storage local` to force repo-local management.
3. If the task is about resuming work, "continue", or finding the next item, inspect `cotext list --category todo` and `cotext list --category deferred`.
4. If the task is about one slice of context, narrow with `cotext list --category <category>`, `cotext render --category <category> --audience codex`, or `cotext show <id>`.
5. Do the work.
6. If durable context changed, update the relevant entry with `cotext update` or create a new one with `cotext new`.
7. When a human wants one-screen review/editing, use `cotext tui`.

## Read patterns

- Full implementation packet: `cotext render --audience codex`
- Focused active-work packet: `cotext render --category progress --category todo --audience codex`
- Actionable queue: `cotext list --category todo --status active --status planned`
- Deferred queue: `cotext list --category deferred`
- Single-item inspection: `cotext show <id>`
- Machine-readable listing: `cotext list --format json --category todo`

## Update rules

- Prefer `cotext update <id> ...` when advancing or closing an existing tracked item.
- Use `cotext update <id> --append ...` for short progress/evidence additions.
- Use `cotext update <id> --status done` when a tracked task is complete.
- Use `cotext new <category> <title> ...` when the work introduced a new durable decision, warning, next step, or deferred item.
- If you changed the target repo's `AGENTS.md`, `CLAUDE.md`, or other generated agent guidance, sync cotext before handoff so the packet matches the instructions now on disk.
- Prefer `cotext update` / `cotext new` / `cotext tui` over direct edits to the managed cotext entry markdown on disk unless you are repairing broken metadata or debugging cotext.

## Category guide

- `design`: stable architecture decisions, invariants, tradeoffs, storage changes.
- `note`: warnings, environment quirks, operator guidance, facts later agents should remember.
- `progress`: what landed, how it was validated, and what should happen next.
- `todo`: the next actionable task with a concrete goal and acceptance criteria.
- `deferred`: real future work intentionally postponed.

## Status guide

- `draft`: rough or incomplete design state.
- `active`: currently in force or currently being worked.
- `planned`: accepted next work that has not started.
- `blocked`: valid work waiting on a dependency.
- `done`: completed work retained for history.
- `deferred`: postponed work.
- `archived`: kept for reference but no longer part of active context.

## Command cookbook

```bash
# Load the full packet before coding
cotext render --audience codex

# Resume the active frontier
cotext list --category todo
cotext list --category deferred
cotext render --category progress --category todo --audience codex

# Inspect and update an existing entry
cotext show cli-render-pipeline-and-tui-mvp-landed
cotext update cli-render-pipeline-and-tui-mvp-landed --append "Validation: cargo test"

# Close a completed todo
cotext update add-richer-metadata-editing-in-the-tui --status done

# Capture a new design decision
cotext new design "Canonical agent guidance templates" --section agents/docs --tag agents --tag docs

# Open the single-screen review surface
cotext tui
```

## Good writeback quality

- Record durable facts instead of chatty narration.
- Include concrete evidence such as commands, tests, file paths, or validation results.
- Keep titles stable and make the body rich enough that a later agent can resume without replaying the conversation.
- If code and cotext disagree, sync cotext before finishing.

## Refreshing generated guidance

- Project-local Codex guidance is generated from `cotext agent install codex`.
- The default tracked Codex skill target is `.codex/skills/cotext-context/`.
- Use `--codex-skill-dir <path>` only when you also need a second copy in another Codex skill directory.
"#
    )
}

fn claude_skill_md(project: &Project) -> String {
    let project_name = &project.config.name;
    format!(
        r#"---
name: cotext-context
description: Read and update structured project context for {project_name} with cotext. Use when you need design notes, awareness notes, progress, next todos, deferred work, or a reliable sync workflow for Claude Code.
---

# Cotext Context

## Default operating sequence

1. Run `cotext render --audience claude` to load the current project packet.
2. Commands prefer global cotext storage by default and fall back to repo-local storage when no matching global project exists; use `--storage local` to force repo-local management.
3. If the task is about continuing work or finding the next item, inspect `cotext list --category todo` and `cotext list --category deferred`.
4. If the task is scoped, narrow the context with `cotext render --category <category> --audience claude`, `cotext list --category <category>`, or `cotext show <id>`.
5. Perform the implementation or analysis.
6. After meaningful work, sync durable changes with `cotext update` or `cotext new`.
7. Use `cotext tui` when a human wants to review and edit context on a single page.

## What belongs in each category

- `design`: architecture decisions, invariants, tradeoffs.
- `note`: warnings, operating assumptions, facts that should stay top-of-mind.
- `progress`: completed implementation state, validation, next step.
- `todo`: the next concrete task.
- `deferred`: real but postponed work.

## Update guidance

- Use `cotext update <id> --append ...` for incremental progress or validation evidence.
- Use `cotext update <id> --status done` when closing work.
- Use `cotext new <category> <title> ...` for newly discovered durable context.
- If you changed the target repo's `AGENTS.md`, `CLAUDE.md`, or other generated agent guidance, sync cotext before handoff so the packet matches the instructions now on disk.
- Prefer `cotext` commands over direct edits to the managed cotext entry markdown on disk unless you are repairing the tool or broken metadata.

## Command cookbook

```bash
cotext render --audience claude
cotext list --category todo --status active --status planned
cotext show <id>
cotext update <id> --append "Validation: ..."
cotext new note "Important environment caveat" --section env/setup --tag ops
cotext tui
```

## Generated guidance

- Project-local Claude guidance lives under `.claude/skills/cotext-context/` and `.claude/commands/`.
- Refresh it with `cotext agent install claude --overwrite`.
"#
    )
}

fn claude_context_command(project: &Project) -> String {
    let project_name = &project.config.name;
    format!(
        r#"---
description: Load the current cotext packet for this repository.
---

Run `cotext render --audience claude` from the project root and treat the result as the authoritative design/notes/progress/todo context for `{project_name}`.

Then:

1. Commands prefer global cotext storage by default and fall back to repo-local storage when no matching global project exists; use `--storage local` when you need the repo-local store explicitly.
2. If the user is asking what to do next or to continue ongoing work, also run `cotext list --category todo` and `cotext list --category deferred`.
3. If only one slice matters, narrow with `cotext render --category <category> --audience claude`, `cotext list --category <category>`, or `cotext show <id>`.
4. Summarize the active items you are going to follow before you proceed with implementation.
"#
    )
}

fn claude_sync_command(project: &Project) -> String {
    let project_name = &project.config.name;
    format!(
        r#"---
description: Sync meaningful project context changes back into cotext.
---

Compare the work you just completed against the current cotext packet for `{project_name}`.

Sync context with this checklist:

1. Update an existing entry with `cotext update <id> ...` if you advanced, clarified, or closed tracked work.
2. Use `cotext update <id> --append ...` for short evidence or validation notes.
3. Use `cotext update <id> --status done` when a todo is complete.
4. Create a new entry with `cotext new <category> <title> ...` when the work introduced a new durable design decision, warning, next step, or deferred item.
5. If you appended or refreshed the managed cotext block in the target repo's `AGENTS.md` or `CLAUDE.md`, record that guidance change in cotext before handoff.
6. Prefer `cotext` commands or `cotext tui` over direct edits to the managed cotext entry markdown on disk unless you are repairing cotext itself.
7. Re-render the relevant packet or list after syncing so the final state is confirmed before handoff.
"#
    )
}

const CODEX_OPENAI_YAML: &str = "interface:\n  display_name: \"Cotext Context\"\n  short_description: \"Load, filter, and sync project context with cotext\"\n";

#[cfg(test)]
mod tests {
    use chrono::Utc;

    use super::*;
    use crate::model::{ProjectConfig, StorageScope, current_schema_version};

    fn demo_project() -> Project {
        let root = PathBuf::from("/tmp/cotext-demo");
        Project {
            data_dir: root.join(".cotext"),
            root,
            config: ProjectConfig {
                schema_version: current_schema_version(),
                name: "demo".to_string(),
                created_at: Utc::now(),
                storage: StorageScope::Local,
                project_root: None,
            },
        }
    }

    #[test]
    fn codex_agents_block_includes_startup_and_refresh_guidance() {
        let block = codex_agents_block(&demo_project());
        assert!(block.contains("### Startup"));
        assert!(block.contains("cotext render --audience codex"));
        assert!(block.contains("cotext agent install codex --overwrite"));
        assert!(block.contains(".codex/skills/cotext-context/"));
        assert!(block.contains("`AGENTS.md` or `CLAUDE.md`"));
    }

    #[test]
    fn codex_skill_includes_category_guide_and_cookbook() {
        let skill = codex_skill_md(&demo_project());
        assert!(skill.contains("## Category guide"));
        assert!(skill.contains("## Command cookbook"));
        assert!(skill.contains("cotext list --format json --category todo"));
        assert!(skill.contains("Prefer `cotext update` / `cotext new` / `cotext tui`"));
    }

    #[test]
    fn claude_guidance_mentions_load_and_sync_commands() {
        let skill = claude_skill_md(&demo_project());
        let load = claude_context_command(&demo_project());
        let sync = claude_sync_command(&demo_project());
        assert!(skill.contains("cotext render --audience claude"));
        assert!(skill.contains("`AGENTS.md`, `CLAUDE.md`, or other generated agent guidance"));
        assert!(load.contains("cotext list --category todo"));
        assert!(sync.contains("`AGENTS.md` or `CLAUDE.md`"));
        assert!(sync.contains("Re-render the relevant packet or list after syncing"));
    }
}