clearctx 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,1006 @@
1
+ # clearctx
2
+
3
+ [![npm version](https://img.shields.io/npm/v/clearctx.svg)](https://www.npmjs.com/package/clearctx)
4
+ [![license](https://img.shields.io/npm/l/clearctx.svg)](https://github.com/)
5
+ [![node](https://img.shields.io/node/v/clearctx.svg)](https://nodejs.org)
6
+
7
+ > Multi-session orchestration system for Claude Code CLI. Spawn parallel workers that coordinate via artifacts and phase gates. 68 MCP tools. v2.9.0.
8
+
9
+ ---
10
+
11
+ **Multi-session orchestrator for Claude Code CLI** — spawn, control, pause, resume, and send multiple inputs to Claude Code sessions programmatically.
12
+
13
+ Built on Claude CLI's `stream-json` protocol for efficient multi-turn conversations using a single long-lived process per session.
14
+
15
+ ## Why?
16
+
17
+ Claude Code's `-p` (print) mode is one-shot: one prompt, one response. For larger projects you need:
18
+
19
+ - **Multi-turn conversations** — send follow-ups without restarting
20
+ - **Parallel sessions** — work on multiple tasks simultaneously
21
+ - **Pause & Resume** — stop a session and come back later
22
+ - **Session forking** — branch off to try different approaches
23
+ - **Cost tracking** — know what each session costs
24
+ - **Programmatic control** — use from scripts or other tools
25
+
26
+ This package solves all of the above with zero dependencies.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npm install -g clearctx
32
+ ```
33
+
34
+ ### Quick Setup (MCP Integration)
35
+
36
+ After installing, run the setup wizard to register the MCP server with Claude Code:
37
+
38
+ ```bash
39
+ clearctx setup
40
+ ```
41
+
42
+ This adds 17 native tools to Claude Code (spawn_session, delegate_task, etc.) so Claude can manage sessions directly — no Bash commands needed.
43
+
44
+ **Non-interactive options:**
45
+ ```bash
46
+ clearctx setup --global # Register for all projects
47
+ clearctx setup --local # Register for current project only
48
+ clearctx setup --global --guide # Also add strategy guide to CLAUDE.md
49
+ clearctx setup --uninstall # Remove MCP integration
50
+ ```
51
+
52
+ ### CLI Usage
53
+
54
+ Use `cms` (or `clearctx`) from anywhere:
55
+
56
+ ```bash
57
+ clearctx spawn --name my-task --prompt "Fix the auth bug"
58
+ clearctx send --name my-task --message "Also add tests"
59
+ ```
60
+
61
+ **Or use without installing:**
62
+ ```bash
63
+ npx clearctx spawn --name my-task --prompt "Fix the auth bug"
64
+ ```
65
+
66
+ **Prerequisites:** [Claude Code CLI](https://claude.ai/code) must be installed and authenticated.
67
+
68
+ ## Quick Start
69
+
70
+ ```bash
71
+ # Start a session with a prompt
72
+ clearctx spawn --name fix-auth --prompt "Fix the authentication bug in auth.service.ts" --model sonnet
73
+
74
+ # Send follow-up messages (same session, full context retained)
75
+ clearctx send --name fix-auth --message "Also add input validation"
76
+ clearctx send --name fix-auth --message "Now write tests for it"
77
+
78
+ # Stop when done (can resume later)
79
+ clearctx stop --name fix-auth
80
+
81
+ # Resume days later
82
+ clearctx resume --name fix-auth --message "Actually, handle the edge case too"
83
+
84
+ # Check what happened
85
+ clearctx output --name fix-auth --full
86
+ ```
87
+
88
+ ## Commands
89
+
90
+ | Command | Description |
91
+ |---------|-------------|
92
+ | `spawn` | Start a new session |
93
+ | `send` | Send follow-up message (auto-resumes if stopped) |
94
+ | `resume` | Restore a stopped/paused session |
95
+ | `pause` | Pause session (process stays alive) |
96
+ | `fork` | Branch off into new session (keeps parent context) |
97
+ | `stop` | Gracefully stop (saves state, can resume later) |
98
+ | `kill` | Force kill a session |
99
+ | `status` | Show detailed session info |
100
+ | `output` | Get last response text |
101
+ | `list` | List all sessions |
102
+ | `history` | Show full interaction history |
103
+ | `delete` | Permanently remove a session |
104
+ | `batch` | Spawn multiple sessions from JSON file |
105
+ | `cleanup` | Remove old sessions |
106
+ | `delegate` | Smart task delegation with safety limits + control loop |
107
+ | `continue` | Send follow-up to a delegated session |
108
+
109
+ ## How It Works
110
+
111
+ ### Streaming Mode (Default)
112
+
113
+ Uses Claude CLI's `--input-format stream-json` to keep **one process alive** per session:
114
+
115
+ ```
116
+ spawn → starts ONE claude process (stays alive)
117
+ send → pipes message into stdin → reads response from stdout
118
+ send → pipes again → reads again (same process, no reload)
119
+ ```
120
+
121
+ **Benefits over the resume approach:**
122
+ - No process restart overhead (~2-3s saved per message)
123
+ - No conversation history reload (lower token cost)
124
+ - Instant follow-up responses
125
+
126
+ ### Session Persistence
127
+
128
+ Sessions are saved to `~/.clearctx/sessions.json`. When a session is stopped, its Claude session ID is saved. When you resume it later, the system uses `--resume <session-id>` to restore the full conversation context.
129
+
130
+ ## Parallel Tasks
131
+
132
+ ### Batch Mode
133
+ ```bash
134
+ # Create a tasks.json file
135
+ echo '[
136
+ { "name": "task-1", "prompt": "Build login page", "model": "sonnet" },
137
+ { "name": "task-2", "prompt": "Build signup page", "model": "sonnet" },
138
+ { "name": "task-3", "prompt": "Build dashboard", "model": "sonnet" }
139
+ ]' > tasks.json
140
+
141
+ # Spawn all in parallel
142
+ clearctx batch --file tasks.json
143
+ ```
144
+
145
+ ### Programmatic API
146
+ ```javascript
147
+ const { SessionManager } = require('clearctx');
148
+ const mgr = new SessionManager();
149
+
150
+ // Spawn multiple sessions in parallel
151
+ const results = await mgr.batch([
152
+ { name: 'task-1', prompt: 'Build login page', model: 'sonnet' },
153
+ { name: 'task-2', prompt: 'Build signup page', model: 'sonnet' },
154
+ ]);
155
+
156
+ // Send follow-ups
157
+ const r1 = await mgr.send('task-1', 'Add form validation');
158
+ const r2 = await mgr.send('task-2', 'Add password strength meter');
159
+
160
+ console.log(r1.text); // The response
161
+ console.log(r1.cost); // Cost in USD
162
+
163
+ mgr.stopAll();
164
+ ```
165
+
166
+ ## Forking Sessions
167
+
168
+ Fork creates a new session that starts with all the parent's conversation context:
169
+
170
+ ```bash
171
+ # Original session
172
+ clearctx spawn --name approach-a --prompt "Implement auth with sessions"
173
+ clearctx send --name approach-a --message "Add login endpoint"
174
+
175
+ # Fork to try a different approach (keeps all context from approach-a)
176
+ clearctx fork --name approach-a --new-name approach-b --message "Actually, use JWT instead"
177
+
178
+ # Now both sessions exist independently
179
+ clearctx send --name approach-a --message "Add session storage"
180
+ clearctx send --name approach-b --message "Add token refresh"
181
+ ```
182
+
183
+ ## Delegate (Control Loop + Safety Net)
184
+
185
+ The `delegate` system gives the parent Claude (or any automation) human-like control over child sessions:
186
+
187
+ 1. **Spawns** a session with the right permissions
188
+ 2. **Sends** the task
189
+ 3. **Monitors** for issues (permission denials, cost overruns, turn limits)
190
+ 4. **Auto-handles** permission retries
191
+ 5. **Returns** structured output for the parent to evaluate
192
+ 6. **Accepts** follow-up corrections via `continue`
193
+
194
+ ### CLI Usage
195
+
196
+ ```bash
197
+ # Delegate a task with a $1 budget limit
198
+ clearctx delegate --name fix-bug --task "Fix the auth bug in auth.service.ts" --max-cost 1.00
199
+
200
+ # Delegate with read-only mode (no file edits allowed)
201
+ clearctx delegate --name review --task "Review code quality of src/" --preset read-only
202
+
203
+ # Get structured JSON output (for programmatic use)
204
+ clearctx delegate --name task-1 --task "Count all TypeScript files" --model haiku --json
205
+
206
+ # Send follow-up corrections
207
+ clearctx continue --name fix-bug --message "Also add input validation"
208
+
209
+ # Full control with context and custom limits
210
+ clearctx delegate --name big-refactor --task "Refactor the auth module" \
211
+ --model opus --preset full --max-cost 5.00 --max-turns 100 \
212
+ --context "Use JWT tokens, not sessions"
213
+
214
+ # Disable safety net entirely (no cost/turn/path limits)
215
+ clearctx delegate --name trusted-task --task "Build the feature" --no-safety
216
+ ```
217
+
218
+ ### Permission Presets
219
+
220
+ | Preset | Permission Mode | Description |
221
+ |--------|----------------|-------------|
222
+ | `read-only` | default | Can search and read files only |
223
+ | `review` | default | Same as read-only (code review) |
224
+ | `edit` | acceptEdits | Can read and edit files (default) |
225
+ | `full` | bypassPermissions | Full access (use with caution) |
226
+ | `plan` | plan | Explore only, no execution |
227
+
228
+ ### Safety Net
229
+
230
+ Every delegated session has automatic safety limits:
231
+
232
+ - **Cost limit** — Auto-kills if cumulative cost exceeds threshold (default: $2.00)
233
+ - **Turn limit** — Auto-kills if agent turns exceed threshold (default: 50)
234
+ - **Time limit** — Timeout per interaction (default: 5 minutes)
235
+ - **Protected paths** — Warns on modifications to `.env`, `.git/`, `node_modules/`, etc.
236
+
237
+ ### Structured Output (--json)
238
+
239
+ When using `--json`, delegate returns machine-readable output:
240
+
241
+ ```json
242
+ {
243
+ "status": "completed",
244
+ "response": "Fixed the auth bug by...",
245
+ "cost": 0.0342,
246
+ "turns": 5,
247
+ "duration": 12340,
248
+ "sessionId": "abc123",
249
+ "name": "fix-bug",
250
+ "canContinue": true,
251
+ "toolsUsed": ["Read", "Edit", "Grep"],
252
+ "safety": {
253
+ "totalViolations": 0,
254
+ "violations": [],
255
+ "limits": { "maxCostUsd": 1.00, "maxTurns": 50 }
256
+ },
257
+ "error": null
258
+ }
259
+ ```
260
+
261
+ **Status values:** `completed`, `needs_input`, `failed`, `cost_exceeded`, `turns_exceeded`
262
+
263
+ ### Programmatic Delegate API
264
+
265
+ ```javascript
266
+ const { SessionManager, Delegate } = require('clearctx');
267
+
268
+ const mgr = new SessionManager();
269
+ const delegate = new Delegate(mgr);
270
+
271
+ // One-shot delegation
272
+ const result = await delegate.run('fix-bug', {
273
+ task: 'Fix the authentication bug in auth.service.ts',
274
+ model: 'sonnet',
275
+ preset: 'edit',
276
+ maxCost: 1.00,
277
+ maxTurns: 30,
278
+ });
279
+
280
+ console.log(result.status); // 'completed'
281
+ console.log(result.response); // What the session did
282
+ console.log(result.cost); // $0.0342
283
+
284
+ // Disable safety net entirely
285
+ const noSafety = await delegate.run('trusted', {
286
+ task: 'Build the whole feature',
287
+ safety: false, // No cost/turn/path limits
288
+ });
289
+
290
+ // Multi-step with evaluation
291
+ const r1 = await delegate.run('feature', { task: 'Build login page' });
292
+ // Parent evaluates r1.response...
293
+ const r2 = await delegate.continue('feature', 'Good, now add form validation');
294
+ // Parent evaluates r2.response...
295
+ const r3 = await delegate.continue('feature', 'Perfect. Now write tests.');
296
+ delegate.finish('feature');
297
+ ```
298
+
299
+ ### SafetyNet Standalone
300
+
301
+ ```javascript
302
+ const { SafetyNet, StreamSession } = require('clearctx');
303
+
304
+ const safety = new SafetyNet({
305
+ maxCostUsd: 0.50,
306
+ maxTurns: 20,
307
+ protectedPaths: ['.env', 'credentials/', '.git/'],
308
+ });
309
+
310
+ const session = new StreamSession({ name: 'task', model: 'haiku' });
311
+ session.start();
312
+ safety.attach(session);
313
+
314
+ // Safety net monitors all interactions
315
+ safety.on('violation', (v) => console.log('VIOLATION:', v.message));
316
+ safety.on('kill', (v) => console.log('SESSION KILLED:', v.message));
317
+
318
+ await session.send('Do something');
319
+ ```
320
+
321
+ ## Options
322
+
323
+ ### spawn
324
+ ```
325
+ --name <name> Session name (required)
326
+ --prompt <text> Initial prompt (required)
327
+ --model <model> Model: sonnet, opus, haiku (default: sonnet)
328
+ --stop Stop after first response (one-shot mode)
329
+ --work-dir <path> Working directory for claude
330
+ --permission-mode <mode> Permission mode: default, acceptEdits, bypassPermissions
331
+ --allowed-tools <t1,t2> Restrict available tools
332
+ --system-prompt <text> Append to system prompt
333
+ --max-budget <usd> Max budget in USD
334
+ --agent <name> Use a specific agent
335
+ ```
336
+
337
+ ### send
338
+ ```
339
+ --name <name> Session name (required)
340
+ --message <text> Message to send (required)
341
+ --stop Stop session after response
342
+ ```
343
+
344
+ ### delegate
345
+ ```
346
+ --name <name> Session name (required)
347
+ --task <text> Task description (required)
348
+ --model <model> Model: sonnet, opus, haiku (default: sonnet)
349
+ --preset <preset> Permission preset (default: edit)
350
+ --max-cost <usd> Max cost in USD (default: 2.00)
351
+ --max-turns <n> Max agent turns (default: 50)
352
+ --no-safety Disable safety net entirely (no cost/turn/path limits)
353
+ --context <text> Extra context to prepend to the task
354
+ --work-dir <path> Working directory
355
+ --system-prompt <text> Append to system prompt
356
+ --agent <name> Use a specific agent
357
+ --json Output structured JSON
358
+ ```
359
+
360
+ ### continue
361
+ ```
362
+ --name <name> Session name (required)
363
+ --message <text> Follow-up message (required)
364
+ --json Output structured JSON
365
+ ```
366
+
367
+ ## Programmatic API
368
+
369
+ ```javascript
370
+ const { SessionManager, StreamSession } = require('clearctx');
371
+
372
+ // High-level API (recommended)
373
+ const mgr = new SessionManager({
374
+ defaultModel: 'sonnet',
375
+ defaultPermissionMode: 'default',
376
+ });
377
+
378
+ const { session, response } = await mgr.spawn('my-task', {
379
+ prompt: 'Fix the auth bug',
380
+ model: 'sonnet',
381
+ workDir: '/path/to/project',
382
+ });
383
+
384
+ const r2 = await mgr.send('my-task', 'Add tests');
385
+ mgr.stop('my-task');
386
+
387
+ // Low-level API (single session)
388
+ const session = new StreamSession({
389
+ name: 'direct',
390
+ model: 'haiku',
391
+ });
392
+ session.start();
393
+ const r1 = await session.send('Hello');
394
+ const r2 = await session.send('Follow up');
395
+ session.stop();
396
+ ```
397
+
398
+ ### Events
399
+
400
+ ```javascript
401
+ session.on('text', (text) => { /* partial text chunks */ });
402
+ session.on('tool-use', ({ name, input }) => { /* tool calls */ });
403
+ session.on('result', (response) => { /* complete response */ });
404
+ session.on('init', (data) => { /* session initialized */ });
405
+ session.on('error', (err) => { /* error occurred */ });
406
+ session.on('close', (code) => { /* process exited */ });
407
+ ```
408
+
409
+ ## Cost Tracking
410
+
411
+ Every interaction tracks cost:
412
+
413
+ ```bash
414
+ clearctx status --name my-task
415
+ # Shows: total cost, turns, interactions
416
+
417
+ clearctx history --name my-task
418
+ # Shows: cost per interaction
419
+ ```
420
+
421
+ ## Data Storage
422
+
423
+ Session data is stored in `~/.clearctx/`:
424
+ - `sessions.json` — Session metadata, history, and config
425
+
426
+ Clean up old sessions:
427
+ ```bash
428
+ clearctx cleanup --days 7
429
+ ```
430
+
431
+ ## MCP Server (Claude Code Native Integration)
432
+
433
+ The MCP server exposes all multi-session tools as **native Claude Code tools**. Instead of running CLI commands via Bash, Claude calls tools directly — just like Read, Edit, or Grep.
434
+
435
+ ### Setup
436
+
437
+ **Automatic (recommended):**
438
+ ```bash
439
+ clearctx setup
440
+ ```
441
+ This interactive wizard registers the MCP server for you. See [Quick Setup](#quick-setup-mcp-integration) above.
442
+
443
+ **Manual — Option 1: Global install**
444
+ ```bash
445
+ npm install -g clearctx
446
+ ```
447
+
448
+ Add to your Claude Code MCP config (`~/.claude/settings.json` or project `.claude/settings.json`):
449
+ ```json
450
+ {
451
+ "mcpServers": {
452
+ "multi-session": {
453
+ "command": "cms-mcp"
454
+ }
455
+ }
456
+ }
457
+ ```
458
+
459
+ **Manual — Option 2: Local (no install)**
460
+ ```json
461
+ {
462
+ "mcpServers": {
463
+ "multi-session": {
464
+ "command": "node",
465
+ "args": ["/absolute/path/to/clearctx/bin/mcp.js"]
466
+ }
467
+ }
468
+ }
469
+ ```
470
+
471
+ ### Available MCP Tools
472
+
473
+ Once configured, Claude sees these tools:
474
+
475
+ **Session Management:**
476
+ | Tool | Description |
477
+ |------|-------------|
478
+ | `spawn_session` | Start a new session |
479
+ | `send_message` | Send message (auto-resumes if stopped) |
480
+ | `resume_session` | Resume a stopped session |
481
+ | `pause_session` | Pause a session |
482
+ | `fork_session` | Fork into a new session |
483
+ | `stop_session` | Gracefully stop |
484
+ | `kill_session` | Force kill |
485
+
486
+ **Information:**
487
+ | Tool | Description |
488
+ |------|-------------|
489
+ | `get_session_status` | Detailed session info |
490
+ | `get_last_output` | Last response text |
491
+ | `list_sessions` | List all sessions |
492
+ | `get_history` | Full interaction history |
493
+ | `delete_session` | Permanently delete |
494
+
495
+ **Delegate (Control Loop + Safety):**
496
+ | Tool | Description |
497
+ |------|-------------|
498
+ | `delegate_task` | Smart delegation with safety limits |
499
+ | `continue_task` | Send corrections to a delegated task |
500
+ | `finish_task` | Finish a task cleanly |
501
+ | `abort_task` | Emergency abort |
502
+
503
+ **Batch:**
504
+ | Tool | Description |
505
+ |------|-------------|
506
+ | `batch_spawn` | Spawn multiple sessions in parallel |
507
+
508
+ ### How Claude Uses It
509
+
510
+ With MCP configured, Claude can autonomously:
511
+
512
+ ```
513
+ User: "Build auth with login, signup, and password reset"
514
+
515
+ Claude thinks: "This has 3 independent parts. I'll delegate in parallel."
516
+
517
+ Claude calls:
518
+ → delegate_task(name="auth-login", task="Build login with JWT", model="sonnet")
519
+ → delegate_task(name="auth-signup", task="Build signup with validation", model="sonnet")
520
+ → delegate_task(name="auth-reset", task="Build password reset with email", model="sonnet")
521
+
522
+ Claude reads results, notices signup is missing email validation...
523
+
524
+ Claude calls:
525
+ → continue_task(name="auth-signup", message="Add email format validation")
526
+
527
+ All good now. Claude calls:
528
+ → finish_task(name="auth-login")
529
+ → finish_task(name="auth-signup")
530
+ → finish_task(name="auth-reset")
531
+
532
+ Claude: "Done! All 3 auth features implemented."
533
+ ```
534
+
535
+ ### Strategy Guide
536
+
537
+ See `STRATEGY.md` for the complete guide on:
538
+ - When to delegate vs do it yourself
539
+ - How to decompose tasks
540
+ - Model selection (haiku/sonnet/opus)
541
+ - Budget allocation
542
+ - The correction loop pattern
543
+ - Parallel coordination
544
+
545
+ ## Requirements
546
+
547
+ - **Node.js** >= 18
548
+ - **Claude Code CLI** installed and authenticated
549
+ - Zero npm dependencies
550
+
551
+ ---
552
+
553
+ ## Team Hub v2 — Multi-Session Collaboration
554
+
555
+ **Team Hub v2** transforms isolated Claude sessions into **self-organizing teams** that exchange structured data, auto-resolve dependencies, and heal themselves when things break. Instead of talking in natural language (which degrades over time), sessions coordinate through **versioned artifacts** and **formal contracts**.
556
+
557
+ This is the only multi-agent system for Claude Code that uses **transactional coordination** instead of conversational coordination.
558
+
559
+ ### The Three-Layer Architecture
560
+
561
+ **Layer 1: Chat** — Sessions message each other directly (like Slack)
562
+ - Send DMs, broadcasts, and blocking ask/reply questions
563
+ - Check inbox before starting work, after major steps
564
+ - Rate-limited and loop-protected to prevent message storms
565
+
566
+ **Layer 2: Artifacts & Contracts** — Sessions exchange structured, versioned data (like Git + Jira)
567
+ - **Artifacts:** Immutable, versioned outputs with JSON schema validation
568
+ - **Contracts:** Formal task assignments with auto-resolving dependencies
569
+ - **Peer-to-peer:** ANY session can create contracts for ANY other session (not just the orchestrator)
570
+
571
+ **Layer 3: Reactive Intelligence** — The system monitors itself and auto-heals (like a self-driving car)
572
+ - **Lineage Graph:** Track data provenance, detect stale artifacts, analyze impact radius
573
+ - **Reactive Pipelines:** Event-driven trigger→action rules (e.g., "when tests fail, reopen the API contract")
574
+ - **Snapshot & Replay:** Capture full state, rollback, replay workflows with different parameters
575
+
576
+ ### Quick Start
577
+
578
+ ```bash
579
+ # Spawn 3 team members
580
+ clearctx team-spawn --name db-dev --role database --prompt "Create User model"
581
+ clearctx team-spawn --name api-dev --role backend --prompt "Build auth API"
582
+ clearctx team-spawn --name qa-dev --role QA --prompt "Write auth tests"
583
+
584
+ # Create a contract chain (Layer 2)
585
+ clearctx contract-create setup-user-model --assignee db-dev \
586
+ --title "Create User schema" \
587
+ --expected-output schema-change
588
+
589
+ clearctx contract-create build-auth-api --assignee api-dev \
590
+ --title "Build auth endpoints" \
591
+ --depends-on setup-user-model \
592
+ --expected-output api-contract
593
+
594
+ clearctx contract-create write-auth-tests --assignee qa-dev \
595
+ --title "Write integration tests" \
596
+ --depends-on build-auth-api \
597
+ --expected-output test-results
598
+
599
+ # Watch the contracts auto-resolve as artifacts are published
600
+ clearctx contract-list
601
+
602
+ # DB session publishes schema
603
+ clearctx artifact-publish schema-user-model --type schema-change \
604
+ --name "User model schema" \
605
+ --data '{"models":[{"name":"User","fields":["email","phone","password"]}]}'
606
+ # → setup-user-model auto-completes → build-auth-api becomes "ready"
607
+
608
+ # API session publishes contract (derived from schema)
609
+ clearctx artifact-publish api-contract-user-auth --type api-contract \
610
+ --name "Auth API contract" \
611
+ --derived-from schema-user-model@v1 \
612
+ --data '{"endpoints":[{"method":"POST","path":"/login"}]}'
613
+ # → build-auth-api auto-completes → write-auth-tests becomes "ready"
614
+
615
+ # QA session publishes test results (derived from API contract)
616
+ clearctx artifact-publish test-results-auth --type test-results \
617
+ --name "Auth integration tests" \
618
+ --derived-from api-contract-user-auth@v1 \
619
+ --data '{"total":12,"passed":12,"failed":0}'
620
+ # → write-auth-tests auto-completes → entire chain done
621
+
622
+ # Query the lineage graph (Layer 3)
623
+ clearctx artifact-lineage test-results-auth --direction upstream
624
+ # Shows: test-results → api-contract → schema
625
+
626
+ # Take a snapshot before trying a different approach
627
+ clearctx team-snapshot pre-graphql --label "Auth feature complete with REST"
628
+
629
+ # Replay with overrides to try GraphQL instead
630
+ clearctx team-replay pre-graphql --overrides '{"build-auth-api":{"inputs":{"context":"Use GraphQL instead of REST"}}}'
631
+ # → Entire workflow re-executes with GraphQL approach
632
+ ```
633
+
634
+ ---
635
+
636
+ ## Layer 1: Chat (8 MCP Tools)
637
+
638
+ Sessions can communicate directly without routing through the orchestrator.
639
+
640
+ | Tool | Description |
641
+ |------|-------------|
642
+ | `team_spawn` | Spawn a session with team system prompt injected (includes roster, artifact/contract tools) |
643
+ | `team_send_message` | Send a DM to a specific teammate |
644
+ | `team_broadcast` | Send a message to all team members |
645
+ | `team_check_inbox` | Check unread messages (do this before starting work and after major steps) |
646
+ | `team_ask` | Ask a question and WAIT for reply (blocking poll) |
647
+ | `team_reply` | Reply to a question received in inbox |
648
+ | `team_roster` | View all team members with roles, status, and lastSeen times |
649
+ | `team_update_status` | Update your own status, task, or role |
650
+
651
+ **Safety features:**
652
+ - Rate limit: 10 messages/minute per session
653
+ - Loop detection: >5 exchanges between same pair in 60s = blocked
654
+ - Auto-compaction: Inbox files auto-compact when they exceed 1000 lines
655
+
656
+ **When to use chat vs artifacts:**
657
+ - Use **chat** for quick questions, coordination, status updates
658
+ - Use **artifacts** for actual work outputs (schemas, API contracts, test results)
659
+ - Use **contracts** to assign work and track progress
660
+
661
+ ---
662
+
663
+ ## Layer 2: Artifacts & Contracts (12 MCP Tools)
664
+
665
+ ### Versioned Artifacts (6 Tools)
666
+
667
+ Artifacts are **immutable, versioned outputs** with JSON schema validation for well-known types.
668
+
669
+ | Tool | Description |
670
+ |------|-------------|
671
+ | `artifact_publish` | Publish structured data (creates new version, validates schema, records lineage, triggers resolution + pipelines) |
672
+ | `artifact_get` | Read an artifact (latest or specific version) |
673
+ | `artifact_list` | List all artifacts with optional filters (type, publisher, tag) |
674
+ | `artifact_history` | View all versions of an artifact |
675
+
676
+ **Well-known artifact types** (validated against JSON schemas):
677
+
678
+ | Type | Data Shape |
679
+ |------|-----------|
680
+ | `api-contract` | `{ endpoints: [{ method, path, request, response }] }` |
681
+ | `schema-change` | `{ models: [{ name, action, fields }] }` |
682
+ | `component-spec` | `{ componentName, props, states, events }` |
683
+ | `test-results` | `{ total, passed, failed, failures: [...] }` |
684
+ | `file-manifest` | `{ files: [{ path, action, description }] }` |
685
+ | `config-change` | `{ changes: [{ key, oldValue, newValue }] }` |
686
+ | `custom` | Any JSON (no schema validation) |
687
+
688
+ **Immutability:** Version files are write-once. First writer wins, second gets an error. This prevents version conflicts.
689
+
690
+ **Schema validation:** When publishing a well-known artifact type, the `data` field is validated against the JSON schema. If validation fails, the publish is rejected with a clear error message.
691
+
692
+ ### Contracts (6 Tools)
693
+
694
+ Contracts are **formal task assignments** with auto-resolving dependencies. ANY session can create contracts for ANY other session (not just the orchestrator) — this is what makes the system truly **peer-to-peer**.
695
+
696
+ | Tool | Description |
697
+ |------|-------------|
698
+ | `contract_create` | Create a task contract and assign it to any teammate (peer-to-peer) |
699
+ | `contract_start` | Start working on an assigned contract (returns inputs + resolved artifacts) |
700
+ | `contract_complete` | Mark a contract as done (triggers cascade + pipelines) |
701
+ | `contract_fail` | Mark a contract as failed (notifies assigner) |
702
+ | `contract_reopen` | Reopen a failed/completed contract for retry (increments retryCount) |
703
+ | `contract_get` | Get full contract details |
704
+ | `contract_list` | List all contracts with optional filters (status, assignee, assigner) |
705
+ | `contract_reassign` | Change who's assigned to a contract |
706
+
707
+ **Contract lifecycle:**
708
+
709
+ ```
710
+ pending → ready → in_progress → completed
711
+ ↑ ↓
712
+ └─ (reopen) ─ failed
713
+ ```
714
+
715
+ - **pending:** Waiting for dependencies (other contracts or artifacts)
716
+ - **ready:** All dependencies satisfied, ready to start
717
+ - **in_progress:** Assignee is working on it
718
+ - **completed:** Auto-completed when acceptance criteria are met
719
+ - **failed:** Assignee marked it as failed OR timeout exceeded
720
+
721
+ **Acceptance criteria types:**
722
+
723
+ | Type | Met when |
724
+ |------|----------|
725
+ | `artifact_published` | Matching artifact exists at required version |
726
+ | `tests_passing` | test-results artifact meets pass/fail thresholds |
727
+ | `contract_completed` | Referenced contract is completed |
728
+ | `all_outputs_published` | All required expectedOutputs have matching artifacts |
729
+
730
+ **Safety features:**
731
+ - **Timeout:** Contracts can have `timeoutMs` — auto-failed if not completed in time
732
+ - **Retry limit:** `maxRetries` (default 3) — reopen rejected after too many failures
733
+ - **Circular dependency detection:** DFS cycle detection on contract creation
734
+ - **Cascade depth guard:** Max 10 levels of auto-resolution to prevent infinite loops
735
+
736
+ ---
737
+
738
+ ## Layer 3: Reactive Intelligence (12 MCP Tools)
739
+
740
+ This is the layer that makes the system **unbeatable**. Each feature depends on Layer 2's versioned artifacts and contract state machine — competitors cannot bolt these on because they lack the foundation.
741
+
742
+ ### 3a. Lineage Graph (4 Tools)
743
+
744
+ Track **data provenance** and analyze impact.
745
+
746
+ | Tool | Description |
747
+ |------|-------------|
748
+ | `artifact_lineage` | Query the provenance DAG (upstream: what inputs? downstream: what depends on this?) |
749
+ | `artifact_impact` | "If I change this artifact, what downstream artifacts and contracts break?" |
750
+ | `artifact_stale` | List all artifacts derived from outdated sources (e.g., derived from v1 but v2 now exists) |
751
+ | `team_audit` | Full provenance trail: who created it, from what inputs, under which contract, at what time |
752
+
753
+ **How lineage is captured:**
754
+
755
+ Every `artifact_publish` can include a `derivedFrom` array listing input artifacts. Additionally, when a contract completes, the system auto-links published artifacts to the contract's input artifacts. This builds a full DAG (directed acyclic graph) of how data flowed through the system.
756
+
757
+ **Example:**
758
+
759
+ ```
760
+ schema-user-model@v1 (root)
761
+ └─► api-contract-user-auth@v2 (derivedFrom schema@v1)
762
+ └─► test-results-auth@v1 (derivedFrom api-contract@v2)
763
+
764
+ If schema-user-model gets bumped to v2:
765
+ → artifact_stale() reports api-contract-user-auth@v2 as stale
766
+ → artifact_impact("schema-user-model") shows 2 downstream artifacts affected
767
+ ```
768
+
769
+ ### 3b. Reactive Pipelines (4 Tools)
770
+
771
+ Event-driven **trigger→condition→action** rules. "When X happens, automatically do Y."
772
+
773
+ | Tool | Description |
774
+ |------|-------------|
775
+ | `pipeline_create` | Define trigger→condition→action rules |
776
+ | `pipeline_list` | View active pipelines and execution counts |
777
+ | `pipeline_pause` | Disable a pipeline without deleting |
778
+ | `pipeline_resume` | Re-enable a paused pipeline |
779
+
780
+ **Trigger types:**
781
+
782
+ | Trigger | Fires when |
783
+ |---------|-----------|
784
+ | `artifact_published` | Any artifact of matching type/id is published |
785
+ | `artifact_version_bumped` | An existing artifact gets a new version |
786
+ | `contract_completed` | A contract transitions to completed |
787
+ | `contract_failed` | A contract transitions to failed |
788
+ | `artifact_stale` | An artifact is detected as stale |
789
+
790
+ **Action types:**
791
+
792
+ | Action | What it does |
793
+ |--------|-------------|
794
+ | `notify_session` | Send an inbox message to a specific session |
795
+ | `broadcast` | Send inbox message to all team members |
796
+ | `reopen_contract` | Call contract_reopen with given reason |
797
+ | `create_contract` | Create a new contract (deduplication: skips if already exists) |
798
+ | `invalidate_downstream` | Mark all downstream artifacts as stale via lineage graph |
799
+
800
+ **Example pipeline (self-healing CI loop):**
801
+
802
+ ```javascript
803
+ {
804
+ rules: [
805
+ {
806
+ trigger: { type: "artifact_published", artifactType: "api-contract" },
807
+ action: { type: "notify_session", target: "qa-dev",
808
+ message: "API contract updated — re-run tests" }
809
+ },
810
+ {
811
+ trigger: { type: "artifact_published", artifactType: "test-results" },
812
+ condition: "data.failed > 0",
813
+ action: { type: "reopen_contract", contractId: "build-auth-api",
814
+ reason: "Tests failing: ${data.failed} failures" }
815
+ }
816
+ ]
817
+ }
818
+ ```
819
+
820
+ When tests fail, the API contract is **automatically reopened** without human intervention. When the API is fixed and tests pass, the contract auto-completes. This is a **self-healing CI loop** with zero conversation.
821
+
822
+ ### 3c. Snapshot & Replay (4 Tools)
823
+
824
+ **Time-travel** for workflows. Capture full state, rollback, replay with different parameters.
825
+
826
+ | Tool | Description |
827
+ |------|-------------|
828
+ | `team_snapshot` | Capture current state of all contracts + artifacts + pipelines |
829
+ | `team_snapshot_list` | View all snapshots with timestamp and summary |
830
+ | `team_rollback` | Reset contract/pipeline state to a previous snapshot |
831
+ | `team_replay` | Rollback + apply overrides + re-trigger dependency resolution |
832
+
833
+ **Why this matters:**
834
+
835
+ Because artifacts are **immutable** (version files never change) and contracts have a well-defined **state machine**, the entire system state can be captured as a snapshot and restored later.
836
+
837
+ **Rollback:** Undo a bad workflow execution and restore to a known-good state.
838
+
839
+ **Replay:** Re-execute from a snapshot with different parameters (e.g., "try GraphQL instead of REST"). The entire downstream chain re-executes with the new approach. Original artifacts are preserved as historical versions for comparison.
840
+
841
+ **Example:**
842
+
843
+ ```bash
844
+ # Take a snapshot before a risky operation
845
+ clearctx team-snapshot pre-refactor --label "Before auth refactor"
846
+
847
+ # Do the refactor... oops, tests are broken
848
+ clearctx contract-list # shows multiple failed contracts
849
+
850
+ # Rollback to the snapshot
851
+ clearctx team-rollback pre-refactor
852
+ # → Contracts reset to their pre-refactor state
853
+ # → Post-snapshot artifacts marked as "rolled-back" (files preserved)
854
+ # → Sessions notified to restart
855
+
856
+ # Or replay with different parameters
857
+ clearctx team-replay pre-refactor --overrides '{"build-auth-api":{"inputs":{"context":"Use JWT instead of sessions"}}}'
858
+ # → Entire workflow re-executes with JWT approach
859
+ # → Compare test-results artifacts from both runs
860
+ ```
861
+
862
+ ---
863
+
864
+ ## CLI Commands (Team Hub v2)
865
+
866
+ ### Chat Commands
867
+
868
+ ```bash
869
+ clearctx team-send --from db-dev --to api-dev --message "Schema is ready"
870
+ clearctx team-broadcast --from orchestrator --message "Deploy in 10 minutes"
871
+ clearctx team-roster # View all team members
872
+ clearctx team-inbox --name db-dev # Check unread messages
873
+ ```
874
+
875
+ ### Artifact Commands
876
+
877
+ ```bash
878
+ clearctx artifact-publish schema-user-model --type schema-change \
879
+ --name "User schema" --data '{"models":[...]}'
880
+
881
+ clearctx artifact-get api-contract-user-auth # Latest version
882
+ clearctx artifact-get api-contract-user-auth --version 2 # Specific version
883
+ clearctx artifact-list --type api-contract
884
+ clearctx artifact-history api-contract-user-auth
885
+ ```
886
+
887
+ ### Contract Commands
888
+
889
+ ```bash
890
+ clearctx contract-create setup-user-model --assignee db-dev \
891
+ --title "Create User schema" \
892
+ --expected-output schema-change
893
+
894
+ clearctx contract-start setup-user-model
895
+ clearctx contract-complete setup-user-model --summary "User model created"
896
+ clearctx contract-fail setup-user-model --reason "Missing field validation"
897
+ clearctx contract-reopen setup-user-model --reason "Add phone field"
898
+ clearctx contract-list --status ready
899
+ ```
900
+
901
+ ### Lineage Commands
902
+
903
+ ```bash
904
+ clearctx artifact-lineage test-results-auth --direction upstream
905
+ clearctx artifact-lineage schema-user-model --direction downstream
906
+ clearctx artifact-impact schema-user-model # What breaks if I change this?
907
+ clearctx artifact-stale # List all artifacts derived from outdated sources
908
+ clearctx team-audit test-results-auth # Full provenance trail
909
+ ```
910
+
911
+ ### Pipeline Commands
912
+
913
+ ```bash
914
+ clearctx pipeline-create ci-loop --rules ci-rules.json
915
+ clearctx pipeline-list
916
+ clearctx pipeline-pause ci-loop
917
+ clearctx pipeline-resume ci-loop
918
+ ```
919
+
920
+ ### Snapshot Commands
921
+
922
+ ```bash
923
+ clearctx team-snapshot pre-work --label "All contracts created"
924
+ clearctx team-snapshot-list
925
+ clearctx team-rollback pre-work
926
+ clearctx team-replay pre-work --overrides overrides.json
927
+ ```
928
+
929
+ ---
930
+
931
+ ## Architecture & Directory Structure
932
+
933
+ ```
934
+ ~/.clearctx/
935
+ sessions.json # Existing session metadata (unchanged)
936
+ team/
937
+ default/ # Team namespace
938
+ roster.json # Layer 1: who's active, role, status
939
+ inbox/
940
+ {session}.jsonl # Layer 1: chat messages (append-only)
941
+ asks/
942
+ ask_{id}.json # Layer 1: pending ask-and-wait
943
+ artifacts/
944
+ index.json # Layer 2: artifact registry
945
+ schemas/ # Layer 2: JSON schemas for well-known types
946
+ api-contract.json
947
+ schema-change.json
948
+ test-results.json
949
+ data/
950
+ {artifactId}/
951
+ v1.json # Immutable version files
952
+ v2.json
953
+ contracts/
954
+ index.json # Layer 2: contract state
955
+ pipelines/
956
+ index.json # Layer 3: reactive pipeline rules
957
+ log.jsonl # Layer 3: pipeline execution history
958
+ snapshots/
959
+ snap_{id}.json # Layer 3: full state snapshots
960
+ locks/
961
+ artifacts-index.lock # Cross-process lock files
962
+ contracts-index.lock
963
+ pipelines-index.lock
964
+ ```
965
+
966
+ **Key design choices:**
967
+
968
+ - **JSONL for inboxes:** Append-only, safe for concurrent writers
969
+ - **JSON for indexes:** Atomic temp+rename for safe updates
970
+ - **Immutable version files:** Write-once (wx flag), first writer wins
971
+ - **File locks:** PID-aware locking with staleness detection
972
+ - **Team namespaces:** Multiple teams can coexist in separate directories
973
+
974
+ ---
975
+
976
+ ## Comparison: Why This Is Revolutionary
977
+
978
+ | | Agent Teams | claude-flow | CrewAI | **clearctx v2.0** |
979
+ |---|---|---|---|---|
980
+ | Coordination model | Conversational | Conversational | Conversational | **Transactional** |
981
+ | Structured data exchange | No | No | No | **Versioned artifacts** |
982
+ | Schema validation | No | No | No | **JSON schema on publish** |
983
+ | Auto-resolving dependencies | No | No | No | **Contract system** |
984
+ | Peer-to-peer task assignment | No | No | No | **Any session → any session** |
985
+ | Contract timeout + retry | No | No | No | **Yes** |
986
+ | Direct session messaging | Yes (text only) | No | No | **Yes (text + structured artifacts)** |
987
+ | Data lineage / provenance | No | No | No | **Full DAG** |
988
+ | Impact analysis | No | No | No | **"What breaks if I change X?"** |
989
+ | Reactive pipelines | No | No | No | **Event-driven trigger→action** |
990
+ | Self-healing CI loops | No | No | No | **Auto-reopen + re-test** |
991
+ | Workflow snapshots | No | No | No | **Full state capture** |
992
+ | Rollback + replay | No | No | No | **Time-travel with overrides** |
993
+ | Each session: own context | No (shared) | No | No | **100K each** |
994
+ | Resume team next day | No | No | No | **Yes** |
995
+ | Quality over time | Degrades | Degrades | Degrades | **Stays consistent** |
996
+ | Zero dependencies | N/A | No (46MB) | No | **Yes** |
997
+
998
+ **The key insight:** Every competitor uses conversational coordination — agents talk in natural language, summaries pile up, quality degrades over time. We use **transactional coordination** — agents exchange structured data, operate on formal contracts, and auto-resolve dependencies. The result is a system that **stays consistent** instead of degrading.
999
+
1000
+ **The moat:** Layer 3 features (lineage, pipelines, snapshots) cannot be bolted onto conversational systems because they require Layer 2 (versioned artifacts + contracts) to exist first. Competitors would need to rebuild their entire coordination layer to replicate this.
1001
+
1002
+ ---
1003
+
1004
+ ## License
1005
+
1006
+ MIT