@stackmemoryai/stackmemory 1.0.0 → 1.2.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.
Files changed (39) hide show
  1. package/README.md +66 -270
  2. package/dist/src/cli/claude-sm.js +9 -0
  3. package/dist/src/cli/codex-sm.js +9 -0
  4. package/dist/src/cli/commands/audit.js +134 -0
  5. package/dist/src/cli/commands/bench.js +252 -0
  6. package/dist/src/cli/commands/dashboard.js +2 -1
  7. package/dist/src/cli/commands/stats.js +118 -0
  8. package/dist/src/cli/index.js +6 -0
  9. package/dist/src/core/config/feature-flags.js +7 -1
  10. package/dist/src/core/context/enhanced-rehydration.js +24 -5
  11. package/dist/src/core/extensions/cerebras-adapter.js +28 -0
  12. package/dist/src/core/extensions/deepinfra-adapter.js +32 -0
  13. package/dist/src/core/extensions/provider-adapter.js +33 -240
  14. package/dist/src/core/models/complexity-scorer.js +154 -0
  15. package/dist/src/core/models/model-router.js +230 -36
  16. package/dist/src/core/models/provider-pricing.js +63 -0
  17. package/dist/src/core/models/sensitive-guard.js +112 -0
  18. package/dist/src/core/monitoring/feedback-loops.js +88 -0
  19. package/dist/src/features/sweep/pty-wrapper.js +9 -0
  20. package/dist/src/hooks/daemon.js +8 -0
  21. package/dist/src/hooks/graphiti-hooks.js +104 -0
  22. package/dist/src/hooks/schemas.js +12 -1
  23. package/dist/src/integrations/anthropic/batch-client.js +256 -0
  24. package/dist/src/integrations/anthropic/client.js +87 -72
  25. package/dist/src/integrations/claude-code/subagent-client.js +133 -12
  26. package/dist/src/integrations/graphiti/client.js +115 -0
  27. package/dist/src/integrations/graphiti/config.js +17 -0
  28. package/dist/src/integrations/graphiti/types.js +4 -0
  29. package/dist/src/integrations/mcp/handlers/index.js +25 -1
  30. package/dist/src/integrations/mcp/handlers/provider-handlers.js +227 -0
  31. package/dist/src/integrations/mcp/server.js +207 -1
  32. package/dist/src/integrations/mcp/tool-definitions.js +38 -1
  33. package/dist/src/orchestrators/multimodal/baselines.js +128 -0
  34. package/dist/src/orchestrators/multimodal/constants.js +9 -1
  35. package/dist/src/orchestrators/multimodal/harness.js +86 -6
  36. package/dist/src/orchestrators/multimodal/providers.js +113 -2
  37. package/dist/src/skills/recursive-agent-orchestrator.js +15 -10
  38. package/dist/src/utils/fuzzy-edit.js +162 -0
  39. package/package.json +5 -1
package/README.md CHANGED
@@ -5,19 +5,19 @@
5
5
  [![Coverage](https://codecov.io/gh/stackmemoryai/stackmemory/branch/main/graph/badge.svg)](https://codecov.io/gh/stackmemoryai/stackmemory)
6
6
  [![npm version](https://img.shields.io/npm/v/@stackmemoryai/stackmemory)](https://www.npmjs.com/package/@stackmemoryai/stackmemory)
7
7
 
8
- Lossless, project-scoped memory for AI tools
8
+ Lossless, project-scoped memory for AI coding tools.
9
9
 
10
10
  StackMemory is a **production-ready memory runtime** for AI coding tools that preserves full project context across sessions:
11
11
 
12
- - **Zero-config setup** - `stackmemory init` just works, no questions asked
13
- - **26 MCP tools** for Claude Code integration
12
+ - **Zero-config setup** `stackmemory init` just works
13
+ - **25 MCP tools** for Claude Code integration
14
14
  - **Full Linear integration** with bidirectional sync
15
- - **Context persistence** that survives /clear operations
15
+ - **Context persistence** that survives `/clear` operations
16
16
  - **Hierarchical frame organization** (nested call stack model)
17
17
  - **Skills system** with `/spec` and `/linear-run` for Claude Code
18
18
  - **Automatic hooks** for task tracking, Linear sync, and spec progress
19
19
  - **Memory monitor daemon** with automatic capture/clear on RAM pressure
20
- - **650+ tests passing** with comprehensive coverage
20
+ - **652 tests passing** with comprehensive coverage
21
21
 
22
22
  Instead of a linear chat log, StackMemory organizes memory as a **call stack** of scoped work (frames), with intelligent LLM-driven retrieval and team collaboration features.
23
23
 
@@ -48,12 +48,12 @@ Tools forget decisions and constraints between sessions. StackMemory makes conte
48
48
 
49
49
  ---
50
50
 
51
- ## Features (at a glance)
51
+ ## Features
52
52
 
53
- - **MCP tools** for Claude Code: 26+ tools; context on every request
53
+ - **MCP tools** for Claude Code: 25 tools across context, tasks, Linear, traces, and discovery
54
54
  - **Skills**: `/spec` (iterative spec generation), `/linear-run` (task execution via RLM)
55
55
  - **Hooks**: automatic context save, task tracking, Linear sync, PROMPT_PLAN updates
56
- - **Prompt Forge**: watches AGENTS.md and CLAUDE.md for prompt optimization (GEPA)
56
+ - **Prompt Forge**: watches CLAUDE.md and AGENTS.md for prompt optimization (GEPA)
57
57
  - **Safe branches**: worktree isolation with `--worktree` or `-w`
58
58
  - **Persistent context**: frames, anchors, decisions, retrieval
59
59
  - **Integrations**: Linear, DiffMem, Browser MCP
@@ -68,22 +68,34 @@ Requirements: Node >= 20
68
68
  # Install globally
69
69
  npm install -g @stackmemoryai/stackmemory
70
70
 
71
- # Initialize in your project (zero-config, just works)
71
+ # Initialize in your project (zero-config)
72
72
  cd your-project
73
73
  stackmemory init
74
74
 
75
75
  # Configure Claude Code integration
76
76
  stackmemory setup-mcp
77
77
 
78
- # Minimal usage
79
- stackmemory init && stackmemory setup-mcp && stackmemory doctor
78
+ # Verify everything works
79
+ stackmemory doctor
80
80
  ```
81
81
 
82
82
  Restart Claude Code and StackMemory MCP tools will be available.
83
83
 
84
+ ### Wrapper Scripts
85
+
86
+ StackMemory ships wrapper scripts that launch your coding tool with StackMemory context pre-loaded:
87
+
88
+ ```bash
89
+ claude-sm # Claude Code with StackMemory context + Prompt Forge
90
+ claude-smd # Claude Code with --dangerously-skip-permissions
91
+ codex-sm # Codex with StackMemory context
92
+ codex-smd # Codex with --dangerously-skip-permissions
93
+ opencode-sm # OpenCode with StackMemory context
94
+ ```
95
+
84
96
  ---
85
97
 
86
- ## Core concepts (quick mental model)
98
+ ## Core Concepts
87
99
 
88
100
  | Concept | Meaning |
89
101
  | -------------- | ------------------------------------------------- |
@@ -94,56 +106,13 @@ Restart Claude Code and StackMemory MCP tools will be available.
94
106
  | **Digest** | Structured return value when a frame closes |
95
107
  | **Anchor** | Pinned fact (DECISION, CONSTRAINT, INTERFACE) |
96
108
 
97
- Frames can span:
98
-
99
- - multiple chat turns
100
- - multiple tool calls
101
- - multiple sessions
102
-
103
- ---
104
-
105
- ## Hosted vs Open Source
106
-
107
- - Hosted: cloud-backed, fast retrieval, durable, team features — works out of the box.
108
- - OSS local: SQLite, offline, inspectable — intentionally behind; no sync/org features.
109
+ Frames can span multiple chat turns, tool calls, and sessions.
109
110
 
110
111
  ---
111
112
 
112
113
  ## How it integrates
113
114
 
114
- Runs as an MCP server. Editors (e.g., Claude Code) call StackMemory on each interaction to fetch a compiled context bundle; editors dont store memory themselves.
115
-
116
- ### MCP Quick Usage
117
-
118
- Use these JSON snippets with Claude Code’s MCP “tools/call”. Responses are returned as a single text item containing JSON.
119
-
120
- - Plan only (no code):
121
- ```json
122
- {"method":"tools/call","params":{"name":"plan_only","arguments":{"task":"Refactor config loader","plannerModel":"claude-sonnet-4-20250514"}}}
123
- ```
124
-
125
- - Approval‑gated plan (phase 1):
126
- ```json
127
- {"method":"tools/call","params":{"name":"plan_gate","arguments":{"task":"Refactor config loader","compact":true}}}
128
- ```
129
-
130
- - Approve + execute (phase 2):
131
- ```json
132
- {"method":"tools/call","params":{"name":"approve_plan","arguments":{"approvalId":"<copy from plan_gate>","implementer":"codex","execute":true,"recordFrame":true,"compact":true}}}
133
- ```
134
-
135
- - Manage approvals:
136
- ```json
137
- {"method":"tools/call","params":{"name":"pending_list","arguments":{}}}
138
- {"method":"tools/call","params":{"name":"pending_show","arguments":{"approvalId":"<id>","compact":true}}}
139
- {"method":"tools/call","params":{"name":"pending_clear","arguments":{"approvalId":"<id>"}}}
140
- ```
141
-
142
- Env defaults (optional):
143
- - `STACKMEMORY_MM_PLANNER_MODEL` (e.g., `claude-sonnet-4-20250514`)
144
- - `STACKMEMORY_MM_REVIEWER_MODEL` (defaults to planner if unset)
145
- - `STACKMEMORY_MM_IMPLEMENTER` (`codex` or `claude`)
146
- - `STACKMEMORY_MM_MAX_ITERS` (e.g., `2`)
115
+ Runs as an MCP server. Editors (e.g., Claude Code) call StackMemory on each interaction to fetch a compiled context bundle; editors don't store memory themselves.
147
116
 
148
117
  ---
149
118
 
@@ -156,7 +125,7 @@ StackMemory ships Claude Code skills that integrate directly into your workflow.
156
125
  Generates iterative spec documents following a 4-doc progressive chain. Each document reads previous ones from disk for context.
157
126
 
158
127
  ```
159
- ONE_PAGER.md DEV_SPEC.md PROMPT_PLAN.md AGENTS.md
128
+ ONE_PAGER.md -> DEV_SPEC.md -> PROMPT_PLAN.md -> AGENTS.md
160
129
  (standalone) (reads 1) (reads 1+2) (reads 1+2+3)
161
130
  ```
162
131
 
@@ -217,21 +186,6 @@ StackMemory installs Claude Code hooks that run automatically during your sessio
217
186
  | `skill-eval` | User prompt | Scores prompt against 28 skill patterns, recommends relevant skills |
218
187
  | `tool-use-trace` | Tool invocation | Logs tool usage for context tracking |
219
188
 
220
- ### Skill Evaluation
221
-
222
- When you type a prompt, the `skill-eval` hook scores it against `skill-rules.json` (28 mapped skills with keyword, pattern, intent, and directory matching). Skills scoring above the threshold (default: 3) are recommended.
223
-
224
- ```json
225
- // Example: user types "generate a spec for the auth system"
226
- // skill-eval recommends:
227
- {
228
- "recommendedSkills": [
229
- { "skillName": "spec-generator", "score": 8 },
230
- { "skillName": "frame-management", "score": 5 }
231
- ]
232
- }
233
- ```
234
-
235
189
  ### Hook Installation
236
190
 
237
191
  Hooks install automatically during `npm install` (with user consent). To install or reinstall manually:
@@ -255,7 +209,7 @@ When a task completes (via hook or `/linear-run`), StackMemory fuzzy-matches the
255
209
 
256
210
  ---
257
211
 
258
- ## Memory Monitor Daemon (v0.8.0)
212
+ ## Memory Monitor Daemon
259
213
 
260
214
  Automatically monitors system RAM and Node.js heap usage, triggering capture/clear cycles when memory pressure exceeds thresholds. Prevents long-running sessions from degrading performance.
261
215
 
@@ -286,10 +240,6 @@ stackmemory daemon status # Show memory stats, trigger count, thresholds
286
240
  stackmemory daemon stop # Stop daemon
287
241
  ```
288
242
 
289
- ### Hook
290
-
291
- The memory guard hook (`.claude/hooks/memory-guard.sh`) is registered as a `user-prompt-submit` hook. When the daemon writes a signal file, the hook alerts you on the next prompt to run `/clear` and restore.
292
-
293
243
  ---
294
244
 
295
245
  ## Prompt Forge (GEPA)
@@ -306,48 +256,44 @@ claude-sm
306
256
 
307
257
  ---
308
258
 
309
- ### Install
310
-
311
- ```bash
312
- npm install -g @stackmemoryai/stackmemory@latest
313
- ```
259
+ ## RLM (Recursive Language Model) Orchestration
314
260
 
315
- During install, you'll be asked if you want to install Claude Code hooks (optional but recommended).
261
+ StackMemory includes an RLM system that handles complex tasks through recursive decomposition and parallel execution using Claude Code's Task tool.
316
262
 
317
- ### Initialize Project
263
+ ### Key Features
318
264
 
319
- ```bash
320
- cd your-project
321
- stackmemory init
322
- ```
265
+ - **Recursive Task Decomposition**: Breaks complex tasks into manageable subtasks
266
+ - **Parallel Subagent Execution**: Run multiple specialized agents concurrently
267
+ - **8 Specialized Agent Types**: Planning, Code, Testing, Linting, Review, Improve, Context, Publish
268
+ - **Multi-Stage Review**: Iterative improvement cycles with quality scoring (0-1 scale)
269
+ - **Automatic Test Generation**: Unit, integration, and E2E test creation
323
270
 
324
- This creates `.stackmemory/` with SQLite storage. No questions asked.
271
+ ### Usage
325
272
 
326
- For interactive setup with more options:
327
273
  ```bash
328
- stackmemory init --interactive
329
- ```
330
-
331
- ### Configure Claude Code
274
+ # Basic usage
275
+ stackmemory skills rlm "Your complex task description"
332
276
 
333
- ```bash
334
- stackmemory setup-mcp
277
+ # With options
278
+ stackmemory skills rlm "Refactor authentication system" \
279
+ --max-parallel 8 \
280
+ --review-stages 5 \
281
+ --quality-threshold 0.9 \
282
+ --test-mode all
335
283
  ```
336
284
 
337
- This automatically:
338
- - Creates `~/.claude/stackmemory-mcp.json` MCP configuration
339
- - Updates `~/.claude/config.json` with StackMemory integration
340
- - Validates the configuration
341
-
342
- ### Diagnose Issues
343
-
344
- ```bash
345
- stackmemory doctor
346
- ```
285
+ ### Configuration Options
347
286
 
348
- Checks project initialization, database integrity, MCP config, and suggests fixes.
287
+ | Option | Description | Default |
288
+ |--------|-------------|---------|
289
+ | `--max-parallel` | Maximum concurrent subagents | 5 |
290
+ | `--max-recursion` | Maximum recursion depth | 4 |
291
+ | `--review-stages` | Number of review iterations | 3 |
292
+ | `--quality-threshold` | Target quality score (0-1) | 0.85 |
293
+ | `--test-mode` | Test generation mode (unit/integration/e2e/all) | all |
294
+ | `--verbose` | Show all recursive operations | false |
349
295
 
350
- See [docs/setup.md](https://github.com/stackmemoryai/stackmemory/blob/main/docs/setup.md) for advanced options (hosted mode, ChromaDB, manual MCP config).
296
+ **Note**: RLM requires Claude Code Max plan for unlimited subagent execution.
351
297
 
352
298
  ---
353
299
 
@@ -370,8 +316,6 @@ npm run mcp:start
370
316
  npm run mcp:dev
371
317
  ```
372
318
 
373
- This creates `.stackmemory/` with SQLite storage.
374
-
375
319
  ### Step 3: Point your editor to local MCP
376
320
 
377
321
  ```json
@@ -385,183 +329,35 @@ This creates `.stackmemory/` with SQLite storage.
385
329
  }
386
330
  ```
387
331
 
388
- ## How it works
389
-
390
- Each interaction: ingests events → updates indices → retrieves relevant context → returns sized bundle.
391
-
392
- ---
393
-
394
- ## Example MCP response (simplified)
395
-
396
- ```json
397
- {
398
- "hot_stack": [
399
- { "frame": "Debug auth redirect", "constraints": [...] }
400
- ],
401
- "anchors": [
402
- { "type": "DECISION", "text": "Use SameSite=Lax cookies" }
403
- ],
404
- "relevant_digests": [
405
- { "frame": "Initial auth refactor", "summary": "..." }
406
- ],
407
- "pointers": [
408
- "s3://logs/auth-test-0421"
409
- ]
410
- }
411
- ```
412
-
413
- ---
414
-
415
- ## Storage & limits
416
-
417
- ### Two-Tier Storage System (v0.3.15+)
418
-
419
- StackMemory implements an intelligent two-tier storage architecture:
420
-
421
- #### Local Storage Tiers
422
- - **Young (<24h)**: Uncompressed, complete retention in memory/Redis
423
- - **Mature (1-7d)**: LZ4 compression (~2.5x), selective retention
424
- - **Old (7-30d)**: ZSTD compression (~3.5x), critical data only
425
-
426
- #### Remote Storage
427
- - **Archive (>30d)**: Infinite retention in S3 + TimeSeries DB
428
- - **Migration**: Automatic background migration based on age, size, and importance
429
- - **Offline Queue**: Persistent retry logic for failed uploads
430
-
431
- ### Free tier (hosted)
432
-
433
- - 1 project
434
- - Up to **2GB local storage**
435
- - Up to **100GB retrieval egress / month**
436
-
437
- ### Paid tiers
438
-
439
- - Per-project pricing
440
- - Unlimited storage + retrieval
441
- - Team sharing
442
- - Org controls
443
- - Custom retention policies
444
-
445
- **No seat-based pricing.**
446
-
447
332
  ---
448
333
 
449
- ## Claude Code Integration
450
-
451
- StackMemory integrates with Claude Code via MCP tools, skills, and hooks. See the [Hooks](#hooks-automatic) and [Skills](#skills-system) sections above.
452
-
453
- ```bash
454
- # Full setup (one-time)
455
- npm install -g @stackmemoryai/stackmemory # installs hooks automatically
456
- cd your-project && stackmemory init # init project
457
- stackmemory setup-mcp # configure MCP
458
- stackmemory doctor # verify everything works
459
- ```
460
-
461
- Additional integration methods: shell wrapper (`claude-sm`), Linear auto-sync daemon, background daemon, git hooks. See [docs/setup.md](https://github.com/stackmemoryai/stackmemory/blob/main/docs/setup.md).
462
-
463
- ## RLM (Recursive Language Model) Orchestration
464
-
465
- StackMemory includes an advanced RLM system that enables handling arbitrarily complex tasks through recursive decomposition and parallel execution using Claude Code's Task tool.
466
-
467
- ### Key Features
468
-
469
- - **Recursive Task Decomposition**: Breaks complex tasks into manageable subtasks
470
- - **Parallel Subagent Execution**: Run multiple specialized agents concurrently
471
- - **8 Specialized Agent Types**: Planning, Code, Testing, Linting, Review, Improve, Context, Publish
472
- - **Multi-Stage Review**: Iterative improvement cycles with quality scoring (0-1 scale)
473
- - **Automatic Test Generation**: Unit, integration, and E2E test creation
474
- - **Full Transparency**: Complete execution tree visualization
475
-
476
- ### Usage
477
-
478
- ```bash
479
- # Basic usage
480
- stackmemory skills rlm "Your complex task description"
481
-
482
- # With options
483
- stackmemory skills rlm "Refactor authentication system" \
484
- --max-parallel 8 \
485
- --review-stages 5 \
486
- --quality-threshold 0.9 \
487
- --test-mode all
488
-
489
- # Examples
490
- stackmemory skills rlm "Generate comprehensive tests for API endpoints"
491
- stackmemory skills rlm "Refactor the entire authentication system to use JWT"
492
- stackmemory skills rlm "Build, test, and publish version 2.0.0"
493
- ```
494
-
495
- ### Configuration Options
496
-
497
- | Option | Description | Default |
498
- |--------|-------------|---------|
499
- | `--max-parallel` | Maximum concurrent subagents | 5 |
500
- | `--max-recursion` | Maximum recursion depth | 4 |
501
- | `--review-stages` | Number of review iterations | 3 |
502
- | `--quality-threshold` | Target quality score (0-1) | 0.85 |
503
- | `--test-mode` | Test generation mode (unit/integration/e2e/all) | all |
504
- | `--verbose` | Show all recursive operations | false |
505
-
506
- ### How It Works
507
-
508
- 1. **Task Decomposition**: Planning agent analyzes the task and creates a dependency graph
509
- 2. **Parallel Execution**: Independent subtasks run concurrently up to the parallel limit
510
- 3. **Review Cycle**: Review agents assess quality, improve agents implement fixes
511
- 4. **Test Generation**: Testing agents create comprehensive test suites
512
- 5. **Result Aggregation**: All outputs are combined into a final deliverable
513
-
514
- **Note**: RLM requires Claude Code Max plan for unlimited subagent execution. In development mode, it uses mock responses for testing.
515
-
516
334
  ## Guarantees & Non-goals
517
335
 
518
336
  **Guarantees:** Lossless storage, project isolation, survives session/model switches, inspectable local mirror.
519
337
 
520
338
  **Non-goals:** Chat UI, vector DB replacement, tool runtime, prompt framework.
521
339
 
522
-
523
- ## CLI Commands
524
-
525
- See https://github.com/stackmemoryai/stackmemory/blob/main/docs/cli.md for the full command reference and examples.
526
-
527
- ---
528
-
529
- ## Status
530
-
531
- See https://github.com/stackmemoryai/stackmemory/blob/main/docs/status.md for current status.
532
-
533
340
  ---
534
341
 
535
- ## Changelog
342
+ ## CLI Commands
536
343
 
537
- See https://github.com/stackmemoryai/stackmemory/blob/main/docs/changelog.md for detailed release notes.
344
+ See [docs/cli.md](https://github.com/stackmemoryai/stackmemory/blob/main/docs/cli.md) for the full command reference.
538
345
 
539
346
  ---
540
347
 
541
- ## Roadmap
348
+ ## Documentation
542
349
 
543
- See https://github.com/stackmemoryai/stackmemory/blob/main/docs/roadmap.md for our current roadmap.
350
+ - [CLI Reference](./docs/cli.md) Full command reference
351
+ - [Setup Guide](./docs/SETUP.md) — Advanced setup options
352
+ - [Development Guide](./docs/DEVELOPMENT.md) — Contributing and development
353
+ - [Architecture](./docs/architecture.md) — System design
354
+ - [API Reference](./docs/API_REFERENCE.md) — API documentation
355
+ - [Vision](./vision.md) — Product vision and principles
356
+ - [Status](./docs/status.md) — Current project status
357
+ - [Roadmap](./docs/roadmap.md) — Future plans
544
358
 
545
359
  ---
546
360
 
547
361
  ## License
548
362
 
549
363
  Licensed under the [Business Source License 1.1](./LICENSE). You can use, modify, and self-host StackMemory freely. The one restriction: you may not offer it as a competing hosted service. The license converts to MIT after 4 years per release.
550
-
551
- ---
552
-
553
- ## Additional Resources
554
-
555
- ### ML System Design
556
-
557
- - [ML System Insights](./ML_SYSTEM_INSIGHTS.md) - Analysis of 300+ production ML systems
558
- - [Agent Instructions](./AGENTS.md) - Specific guidance for AI agents working with ML systems
559
-
560
- ### Documentation
561
- - [Vision](./vision.md) - Product vision, principles, roadmap, metrics
562
- - [Product Requirements](./PRD.md) - Detailed product specifications
563
- - [Technical Architecture](./TECHNICAL_ARCHITECTURE.md) - System design and database schemas
564
- - [Beads Integration](./BEADS_INTEGRATION.md) - Git-native memory patterns from Beads ecosystem
565
- - [MCP: plan_and_code](https://github.com/stackmemoryai/stackmemory/blob/main/docs/mcp.md) - Trigger planning + coding via MCP with JSON results
566
-
567
- ---
@@ -727,6 +727,15 @@ Session completed on fallback provider: ${status.currentProvider}`
727
727
  action: "session_end",
728
728
  exitCode: code
729
729
  });
730
+ if (process.env["LINEAR_API_KEY"]) {
731
+ try {
732
+ execSync("stackmemory linear sync", {
733
+ stdio: "ignore",
734
+ timeout: 1e4
735
+ });
736
+ } catch {
737
+ }
738
+ }
730
739
  if (this.config.tracingEnabled) {
731
740
  const summary = trace.getExecutionSummary();
732
741
  console.log();
@@ -339,6 +339,15 @@ class CodexSM {
339
339
  action: "session_end",
340
340
  exitCode: code
341
341
  });
342
+ if (process.env["LINEAR_API_KEY"]) {
343
+ try {
344
+ execSync("stackmemory linear sync", {
345
+ stdio: "ignore",
346
+ timeout: 1e4
347
+ });
348
+ } catch {
349
+ }
350
+ }
342
351
  if (this.config.tracingEnabled) {
343
352
  const summary = trace.getExecutionSummary();
344
353
  console.log();
@@ -0,0 +1,134 @@
1
+ import { fileURLToPath as __fileURLToPath } from 'url';
2
+ import { dirname as __pathDirname } from 'path';
3
+ const __filename = __fileURLToPath(import.meta.url);
4
+ const __dirname = __pathDirname(__filename);
5
+ import { Command } from "commander";
6
+ import { existsSync, readFileSync } from "fs";
7
+ import { join } from "path";
8
+ import { homedir } from "os";
9
+ let countTokens;
10
+ try {
11
+ const tokenizer = await import("@anthropic-ai/tokenizer");
12
+ countTokens = tokenizer.countTokens;
13
+ } catch {
14
+ countTokens = (text) => Math.ceil(text.length / 3.5);
15
+ }
16
+ function readFileSafe(filePath) {
17
+ try {
18
+ if (existsSync(filePath)) {
19
+ return readFileSync(filePath, "utf-8");
20
+ }
21
+ } catch {
22
+ }
23
+ return null;
24
+ }
25
+ function createAuditCommand() {
26
+ const audit = new Command("audit").description(
27
+ "Measure context overhead (tokens injected before first message)"
28
+ ).option("--json", "Output as JSON", false).action(async (options) => {
29
+ const projectRoot = process.cwd();
30
+ const home = homedir();
31
+ const entries = [];
32
+ const globalClaudeMd = readFileSafe(join(home, ".claude", "CLAUDE.md"));
33
+ if (globalClaudeMd) {
34
+ entries.push({
35
+ source: "~/.claude/CLAUDE.md",
36
+ tokens: countTokens(globalClaudeMd),
37
+ percent: 0
38
+ });
39
+ }
40
+ const projectClaudeMd = readFileSafe(join(projectRoot, "CLAUDE.md"));
41
+ if (projectClaudeMd) {
42
+ entries.push({
43
+ source: "./CLAUDE.md",
44
+ tokens: countTokens(projectClaudeMd),
45
+ percent: 0
46
+ });
47
+ }
48
+ const projectSlug = projectRoot.replace(/\//g, "-");
49
+ const memoryPath = join(
50
+ home,
51
+ ".claude",
52
+ "projects",
53
+ projectSlug,
54
+ "memory",
55
+ "MEMORY.md"
56
+ );
57
+ const memoryMd = readFileSafe(memoryPath);
58
+ if (memoryMd) {
59
+ entries.push({
60
+ source: "auto-memory/MEMORY.md",
61
+ tokens: countTokens(memoryMd),
62
+ percent: 0
63
+ });
64
+ }
65
+ const handoffPath = join(projectRoot, ".stackmemory", "handoff.md");
66
+ const handoffMd = readFileSafe(handoffPath);
67
+ if (handoffMd) {
68
+ entries.push({
69
+ source: ".stackmemory/handoff.md",
70
+ tokens: countTokens(handoffMd),
71
+ percent: 0
72
+ });
73
+ }
74
+ try {
75
+ const { MCPToolDefinitions } = await import("../../integrations/mcp/tool-definitions.js");
76
+ const defs = new MCPToolDefinitions();
77
+ const allTools = defs.getAllToolDefinitions();
78
+ const schemasJson = JSON.stringify(allTools);
79
+ entries.push({
80
+ source: "MCP tool schemas",
81
+ tokens: countTokens(schemasJson),
82
+ percent: 0
83
+ });
84
+ } catch {
85
+ }
86
+ try {
87
+ const dbPath = join(projectRoot, ".stackmemory", "context.db");
88
+ if (existsSync(dbPath)) {
89
+ const { default: Database } = await import("better-sqlite3");
90
+ const { FrameManager } = await import("../../core/context/index.js");
91
+ const db = new Database(dbPath);
92
+ const fm = new FrameManager(db, "cli-project");
93
+ const hotStack = fm.getHotStackContext();
94
+ if (hotStack) {
95
+ entries.push({
96
+ source: "Active frames (hot stack)",
97
+ tokens: countTokens(hotStack),
98
+ percent: 0
99
+ });
100
+ }
101
+ db.close();
102
+ }
103
+ } catch {
104
+ }
105
+ const totalTokens = entries.reduce((sum, e) => sum + e.tokens, 0);
106
+ for (const entry of entries) {
107
+ entry.percent = totalTokens > 0 ? Math.round(entry.tokens / totalTokens * 1e3) / 10 : 0;
108
+ }
109
+ if (options.json) {
110
+ console.log(JSON.stringify({ entries, totalTokens }, null, 2));
111
+ return;
112
+ }
113
+ console.log("\nContext Overhead Audit");
114
+ console.log("\u2500".repeat(60));
115
+ console.log(
116
+ `${"Source".padEnd(32)} ${"Tokens".padStart(8)} ${"%".padStart(7)}`
117
+ );
118
+ console.log("\u2500".repeat(60));
119
+ for (const entry of entries) {
120
+ console.log(
121
+ `${entry.source.padEnd(32)} ${String(entry.tokens).padStart(8)} ${(entry.percent + "%").padStart(7)}`
122
+ );
123
+ }
124
+ console.log("\u2500".repeat(60));
125
+ console.log(
126
+ `${"TOTAL".padEnd(32)} ${String(totalTokens).padStart(8)} ${"100%".padStart(7)}`
127
+ );
128
+ console.log("");
129
+ });
130
+ return audit;
131
+ }
132
+ export {
133
+ createAuditCommand
134
+ };