mdcontext 0.0.1 → 0.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.
- package/.changeset/README.md +28 -0
- package/.changeset/config.json +11 -0
- package/.claude/settings.local.json +25 -0
- package/.github/workflows/ci.yml +83 -0
- package/.github/workflows/claude-code-review.yml +44 -0
- package/.github/workflows/claude.yml +85 -0
- package/.github/workflows/release.yml +113 -0
- package/.tldrignore +112 -0
- package/BACKLOG.md +338 -0
- package/CONTRIBUTING.md +186 -0
- package/NOTES/NOTES +44 -0
- package/README.md +434 -11
- package/biome.json +36 -0
- package/cspell.config.yaml +14 -0
- package/dist/chunk-23UPXDNL.js +3044 -0
- package/dist/chunk-2W7MO2DL.js +1366 -0
- package/dist/chunk-3NUAZGMA.js +1689 -0
- package/dist/chunk-7TOWB2XB.js +366 -0
- package/dist/chunk-7XOTOADQ.js +3065 -0
- package/dist/chunk-AH2PDM2K.js +3042 -0
- package/dist/chunk-BNXWSZ63.js +3742 -0
- package/dist/chunk-BTL5DJVU.js +3222 -0
- package/dist/chunk-HDHYG7E4.js +104 -0
- package/dist/chunk-HLR4KZBP.js +3234 -0
- package/dist/chunk-IP3FRFEB.js +1045 -0
- package/dist/chunk-KHU56VDO.js +3042 -0
- package/dist/chunk-KRYIFLQR.js +88 -0
- package/dist/chunk-LBSDNLEM.js +287 -0
- package/dist/chunk-MNTQ7HCP.js +2643 -0
- package/dist/chunk-MUJELQQ6.js +1387 -0
- package/dist/chunk-MXJGMSLV.js +2199 -0
- package/dist/chunk-N6QJGC3Z.js +2636 -0
- package/dist/chunk-OBELGBPM.js +1713 -0
- package/dist/chunk-OT7R5XTA.js +3192 -0
- package/dist/chunk-P7X4RA2T.js +106 -0
- package/dist/chunk-PIDUQNC2.js +3185 -0
- package/dist/chunk-POGCDIH4.js +3187 -0
- package/dist/chunk-PSIEOQGZ.js +3043 -0
- package/dist/chunk-PVRT3IHA.js +3238 -0
- package/dist/chunk-QNN4TT23.js +1430 -0
- package/dist/chunk-RE3R45RJ.js +3042 -0
- package/dist/chunk-S7E6TFX6.js +803 -0
- package/dist/chunk-SG6GLU4U.js +1378 -0
- package/dist/chunk-SJCDV2ST.js +274 -0
- package/dist/chunk-SYE5XLF3.js +104 -0
- package/dist/chunk-T5VLYBZD.js +103 -0
- package/dist/chunk-TOQB7VWU.js +3238 -0
- package/dist/chunk-VFNMZ4ZQ.js +3228 -0
- package/dist/chunk-VVTGZNBT.js +1629 -0
- package/dist/chunk-W7Q4RFEV.js +104 -0
- package/dist/chunk-XTYYVRLO.js +3190 -0
- package/dist/chunk-Y6MDYVJD.js +3063 -0
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +5458 -0
- package/dist/index.d.ts +653 -0
- package/dist/index.js +79 -0
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +472 -0
- package/dist/schema-BAWSG7KY.js +22 -0
- package/dist/schema-E3QUPL26.js +20 -0
- package/dist/schema-EHL7WUT6.js +20 -0
- package/docs/019-USAGE.md +625 -0
- package/docs/020-current-implementation.md +364 -0
- package/docs/021-DOGFOODING-FINDINGS.md +175 -0
- package/docs/BACKLOG.md +80 -0
- package/docs/CONFIG.md +1123 -0
- package/docs/DESIGN.md +439 -0
- package/docs/ERRORS.md +383 -0
- package/docs/PROJECT.md +88 -0
- package/docs/ROADMAP.md +407 -0
- package/docs/summarization.md +320 -0
- package/docs/test-links.md +9 -0
- package/justfile +40 -0
- package/package.json +74 -9
- package/pnpm-workspace.yaml +5 -0
- package/research/INDEX.md +315 -0
- package/research/code-review/README.md +90 -0
- package/research/code-review/cli-error-handling-review.md +979 -0
- package/research/code-review/code-review-validation-report.md +464 -0
- package/research/code-review/main-ts-review.md +1128 -0
- package/research/config-analysis/01-current-implementation.md +470 -0
- package/research/config-analysis/02-strategy-recommendation.md +428 -0
- package/research/config-analysis/03-task-candidates.md +715 -0
- package/research/config-analysis/033-research-configuration-management.md +828 -0
- package/research/config-analysis/034-research-effect-cli-config.md +1504 -0
- package/research/config-analysis/04-consolidated-task-candidates.md +277 -0
- package/research/config-docs/SUMMARY.md +357 -0
- package/research/config-docs/TEST-RESULTS.md +776 -0
- package/research/config-docs/TODO.md +542 -0
- package/research/config-docs/analysis.md +744 -0
- package/research/config-docs/fix-validation.md +502 -0
- package/research/config-docs/help-audit.md +264 -0
- package/research/config-docs/help-system-analysis.md +890 -0
- package/research/dogfood/consolidated-tool-evaluation.md +373 -0
- package/research/dogfood/strategy-a/a-synthesis.md +184 -0
- package/research/dogfood/strategy-a/a1-docs.md +226 -0
- package/research/dogfood/strategy-a/a2-amorphic.md +156 -0
- package/research/dogfood/strategy-a/a3-llm.md +164 -0
- package/research/dogfood/strategy-b/b-synthesis.md +228 -0
- package/research/dogfood/strategy-b/b1-architecture.md +207 -0
- package/research/dogfood/strategy-b/b2-gaps.md +258 -0
- package/research/dogfood/strategy-b/b3-workflows.md +250 -0
- package/research/dogfood/strategy-c/c-synthesis.md +451 -0
- package/research/dogfood/strategy-c/c1-explorer.md +192 -0
- package/research/dogfood/strategy-c/c2-diver-memory.md +145 -0
- package/research/dogfood/strategy-c/c3-diver-control.md +148 -0
- package/research/dogfood/strategy-c/c4-diver-failure.md +151 -0
- package/research/dogfood/strategy-c/c5-diver-execution.md +221 -0
- package/research/dogfood/strategy-c/c6-diver-org.md +221 -0
- package/research/effect-cli-error-handling.md +845 -0
- package/research/effect-errors-as-values.md +943 -0
- package/research/errors-task-analysis/00-consolidated-tasks.md +207 -0
- package/research/errors-task-analysis/cli-commands-analysis.md +909 -0
- package/research/errors-task-analysis/embeddings-analysis.md +709 -0
- package/research/errors-task-analysis/index-search-analysis.md +812 -0
- package/research/frontmatter/COMMENTS-ARE-SKIPPED.md +149 -0
- package/research/frontmatter/LLM-CODE-NAVIGATION.md +276 -0
- package/research/issue-review.md +603 -0
- package/research/llm-summarization/agent-cli-tools-2026.md +1082 -0
- package/research/llm-summarization/alternative-providers-2026.md +1428 -0
- package/research/llm-summarization/anthropic-2026.md +367 -0
- package/research/llm-summarization/claude-cli-integration.md +1706 -0
- package/research/llm-summarization/cli-integration-patterns.md +3155 -0
- package/research/llm-summarization/openai-2026.md +473 -0
- package/research/llm-summarization/openai-compatible-providers-2026.md +1022 -0
- package/research/llm-summarization/opencode-cli-integration.md +1552 -0
- package/research/llm-summarization/prompt-engineering-2026.md +1426 -0
- package/research/llm-summarization/prototype-results.md +56 -0
- package/research/llm-summarization/provider-switching-patterns-2026.md +2153 -0
- package/research/llm-summarization/typescript-llm-libraries-2026.md +2436 -0
- package/research/mdcontext-error-analysis.md +521 -0
- package/research/mdcontext-pudding/00-EXECUTIVE-SUMMARY.md +282 -0
- package/research/mdcontext-pudding/01-index-embed.md +956 -0
- package/research/mdcontext-pudding/02-search-COMMANDS.md +142 -0
- package/research/mdcontext-pudding/02-search-SUMMARY.md +146 -0
- package/research/mdcontext-pudding/02-search.md +970 -0
- package/research/mdcontext-pudding/03-context.md +779 -0
- package/research/mdcontext-pudding/04-navigation-and-analytics.md +803 -0
- package/research/mdcontext-pudding/04-tree.md +704 -0
- package/research/mdcontext-pudding/05-config.md +1038 -0
- package/research/mdcontext-pudding/06-links-summary.txt +87 -0
- package/research/mdcontext-pudding/06-links.md +679 -0
- package/research/mdcontext-pudding/07-stats.md +693 -0
- package/research/mdcontext-pudding/BUG-FIX-PLAN.md +388 -0
- package/research/mdcontext-pudding/P0-BUG-VALIDATION.md +167 -0
- package/research/mdcontext-pudding/README.md +168 -0
- package/research/mdcontext-pudding/TESTING-SUMMARY.md +128 -0
- package/research/npm_publish/011-npm-workflow-research-agent2.md +792 -0
- package/research/npm_publish/012-npm-workflow-research-agent1.md +530 -0
- package/research/npm_publish/013-npm-workflow-research-agent3.md +722 -0
- package/research/npm_publish/014-npm-workflow-synthesis.md +556 -0
- package/research/npm_publish/031-npm-workflow-task-analysis.md +134 -0
- package/research/research-quality-review.md +834 -0
- package/research/semantic-search/002-research-embedding-models.md +490 -0
- package/research/semantic-search/003-research-rag-alternatives.md +523 -0
- package/research/semantic-search/004-research-vector-search.md +841 -0
- package/research/semantic-search/032-research-semantic-search.md +427 -0
- package/research/semantic-search/embedding-text-analysis.md +156 -0
- package/research/semantic-search/multi-word-failure-reproduction.md +171 -0
- package/research/semantic-search/query-processing-analysis.md +207 -0
- package/research/semantic-search/root-cause-and-solution.md +114 -0
- package/research/semantic-search/threshold-validation-report.md +69 -0
- package/research/semantic-search/vector-search-analysis.md +63 -0
- package/research/task-management-2026/00-synthesis-recommendations.md +295 -0
- package/research/task-management-2026/01-ai-workflow-tools.md +416 -0
- package/research/task-management-2026/02-agent-framework-patterns.md +476 -0
- package/research/task-management-2026/03-lightweight-file-based.md +567 -0
- package/research/task-management-2026/04-established-tools-ai-features.md +541 -0
- package/research/task-management-2026/linear/01-core-features-workflow.md +771 -0
- package/research/task-management-2026/linear/02-api-integrations.md +930 -0
- package/research/task-management-2026/linear/03-ai-features.md +368 -0
- package/research/task-management-2026/linear/04-pricing-setup.md +205 -0
- package/research/task-management-2026/linear/05-usage-patterns-best-practices.md +605 -0
- package/research/test-path-issues.md +276 -0
- package/review/ALP-76/1-error-type-design.md +962 -0
- package/review/ALP-76/2-error-handling-patterns.md +906 -0
- package/review/ALP-76/3-error-presentation.md +624 -0
- package/review/ALP-76/4-test-coverage.md +625 -0
- package/review/ALP-76/5-migration-completeness.md +440 -0
- package/review/ALP-76/6-effect-best-practices.md +755 -0
- package/scripts/apply-branch-protection.sh +47 -0
- package/scripts/branch-protection-templates.json +79 -0
- package/scripts/prototype-summarization.ts +346 -0
- package/scripts/rebuild-hnswlib.js +58 -0
- package/scripts/setup-branch-protection.sh +64 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/active-provider.json +7 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/bm25.json +541 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/bm25.meta.json +5 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/config.json +8 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.bin +0 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.meta.bin +0 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/indexes/documents.json +60 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/indexes/links.json +13 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/indexes/sections.json +1197 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/configuration-management.md +99 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/distributed-systems.md +92 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/error-handling.md +78 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/failure-automation.md +55 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/job-context.md +69 -0
- package/src/__tests__/fixtures/semantic-search/multi-word-corpus/process-orchestration.md +99 -0
- package/src/cli/argv-preprocessor.test.ts +210 -0
- package/src/cli/argv-preprocessor.ts +202 -0
- package/src/cli/cli.test.ts +627 -0
- package/src/cli/commands/backlinks.ts +54 -0
- package/src/cli/commands/config-cmd.ts +642 -0
- package/src/cli/commands/context.ts +285 -0
- package/src/cli/commands/duplicates.ts +122 -0
- package/src/cli/commands/embeddings.ts +529 -0
- package/src/cli/commands/index-cmd.ts +480 -0
- package/src/cli/commands/index.ts +16 -0
- package/src/cli/commands/links.ts +52 -0
- package/src/cli/commands/search.ts +1281 -0
- package/src/cli/commands/stats.ts +149 -0
- package/src/cli/commands/tree.ts +128 -0
- package/src/cli/config-layer.ts +176 -0
- package/src/cli/error-handler.test.ts +235 -0
- package/src/cli/error-handler.ts +655 -0
- package/src/cli/flag-schemas.ts +341 -0
- package/src/cli/help.ts +588 -0
- package/src/cli/index.ts +9 -0
- package/src/cli/main.ts +435 -0
- package/src/cli/options.ts +41 -0
- package/src/cli/shared-error-handling.ts +199 -0
- package/src/cli/typo-suggester.test.ts +105 -0
- package/src/cli/typo-suggester.ts +130 -0
- package/src/cli/utils.ts +259 -0
- package/src/config/file-provider.test.ts +320 -0
- package/src/config/file-provider.ts +273 -0
- package/src/config/index.ts +72 -0
- package/src/config/integration.test.ts +667 -0
- package/src/config/precedence.test.ts +277 -0
- package/src/config/precedence.ts +451 -0
- package/src/config/schema.test.ts +414 -0
- package/src/config/schema.ts +603 -0
- package/src/config/service.test.ts +320 -0
- package/src/config/service.ts +243 -0
- package/src/config/testing.test.ts +264 -0
- package/src/config/testing.ts +110 -0
- package/src/core/index.ts +1 -0
- package/src/core/types.ts +113 -0
- package/src/duplicates/detector.test.ts +183 -0
- package/src/duplicates/detector.ts +414 -0
- package/src/duplicates/index.ts +18 -0
- package/src/embeddings/embedding-namespace.test.ts +300 -0
- package/src/embeddings/embedding-namespace.ts +947 -0
- package/src/embeddings/heading-boost.test.ts +222 -0
- package/src/embeddings/hnsw-build-options.test.ts +198 -0
- package/src/embeddings/hyde.test.ts +272 -0
- package/src/embeddings/hyde.ts +264 -0
- package/src/embeddings/index.ts +10 -0
- package/src/embeddings/openai-provider.ts +414 -0
- package/src/embeddings/pricing.json +22 -0
- package/src/embeddings/provider-constants.ts +204 -0
- package/src/embeddings/provider-errors.test.ts +967 -0
- package/src/embeddings/provider-errors.ts +565 -0
- package/src/embeddings/provider-factory.test.ts +240 -0
- package/src/embeddings/provider-factory.ts +225 -0
- package/src/embeddings/provider-integration.test.ts +788 -0
- package/src/embeddings/query-preprocessing.test.ts +187 -0
- package/src/embeddings/semantic-search-threshold.test.ts +508 -0
- package/src/embeddings/semantic-search.ts +1270 -0
- package/src/embeddings/types.ts +359 -0
- package/src/embeddings/vector-store.ts +708 -0
- package/src/embeddings/voyage-provider.ts +313 -0
- package/src/errors/errors.test.ts +845 -0
- package/src/errors/index.ts +533 -0
- package/src/index/ignore-patterns.test.ts +354 -0
- package/src/index/ignore-patterns.ts +305 -0
- package/src/index/index.ts +4 -0
- package/src/index/indexer.ts +684 -0
- package/src/index/storage.ts +260 -0
- package/src/index/types.ts +147 -0
- package/src/index/watcher.ts +189 -0
- package/src/index.ts +30 -0
- package/src/integration/search-keyword.test.ts +678 -0
- package/src/mcp/server.ts +612 -0
- package/src/parser/index.ts +1 -0
- package/src/parser/parser.test.ts +291 -0
- package/src/parser/parser.ts +394 -0
- package/src/parser/section-filter.test.ts +277 -0
- package/src/parser/section-filter.ts +392 -0
- package/src/search/__tests__/hybrid-search.test.ts +650 -0
- package/src/search/bm25-store.ts +366 -0
- package/src/search/cross-encoder.test.ts +253 -0
- package/src/search/cross-encoder.ts +406 -0
- package/src/search/fuzzy-search.test.ts +419 -0
- package/src/search/fuzzy-search.ts +273 -0
- package/src/search/hybrid-search.ts +448 -0
- package/src/search/path-matcher.test.ts +276 -0
- package/src/search/path-matcher.ts +33 -0
- package/src/search/query-parser.test.ts +260 -0
- package/src/search/query-parser.ts +319 -0
- package/src/search/searcher.test.ts +280 -0
- package/src/search/searcher.ts +724 -0
- package/src/search/wink-bm25.d.ts +30 -0
- package/src/summarization/cli-providers/claude.ts +202 -0
- package/src/summarization/cli-providers/detection.test.ts +273 -0
- package/src/summarization/cli-providers/detection.ts +118 -0
- package/src/summarization/cli-providers/index.ts +8 -0
- package/src/summarization/cost.test.ts +139 -0
- package/src/summarization/cost.ts +102 -0
- package/src/summarization/error-handler.test.ts +127 -0
- package/src/summarization/error-handler.ts +111 -0
- package/src/summarization/index.ts +102 -0
- package/src/summarization/pipeline.test.ts +498 -0
- package/src/summarization/pipeline.ts +231 -0
- package/src/summarization/prompts.test.ts +269 -0
- package/src/summarization/prompts.ts +133 -0
- package/src/summarization/provider-factory.test.ts +396 -0
- package/src/summarization/provider-factory.ts +178 -0
- package/src/summarization/types.ts +184 -0
- package/src/summarize/budget-bugs.test.ts +620 -0
- package/src/summarize/formatters.ts +419 -0
- package/src/summarize/index.ts +20 -0
- package/src/summarize/summarizer.test.ts +275 -0
- package/src/summarize/summarizer.ts +597 -0
- package/src/summarize/verify-bugs.test.ts +238 -0
- package/src/types/huggingface-transformers.d.ts +66 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/tokens.test.ts +142 -0
- package/src/utils/tokens.ts +186 -0
- package/tests/fixtures/cli/.mdcontext/active-provider.json +7 -0
- package/tests/fixtures/cli/.mdcontext/config.json +8 -0
- package/tests/fixtures/cli/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.bin +0 -0
- package/tests/fixtures/cli/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.meta.bin +0 -0
- package/tests/fixtures/cli/.mdcontext/indexes/documents.json +33 -0
- package/tests/fixtures/cli/.mdcontext/indexes/links.json +12 -0
- package/tests/fixtures/cli/.mdcontext/indexes/sections.json +247 -0
- package/tests/fixtures/cli/README.md +9 -0
- package/tests/fixtures/cli/api-reference.md +11 -0
- package/tests/fixtures/cli/getting-started.md +11 -0
- package/tests/integration/embed-index.test.ts +712 -0
- package/tests/integration/search-context.test.ts +469 -0
- package/tests/integration/search-semantic.test.ts +522 -0
- package/tsconfig.json +26 -0
- package/vitest.config.ts +16 -0
- package/vitest.setup.ts +12 -0
|
@@ -0,0 +1,1706 @@
|
|
|
1
|
+
# Claude Code CLI Integration Guide (2026)
|
|
2
|
+
|
|
3
|
+
> Comprehensive guide for non-interactive programmatic usage of the `claude` command for mdcontext integration
|
|
4
|
+
|
|
5
|
+
**Last Updated**: 2026-01-26
|
|
6
|
+
**Claude Code Version**: 2.1.19
|
|
7
|
+
**Target Use Case**: Automated codebase summarization in mdcontext
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Table of Contents
|
|
12
|
+
|
|
13
|
+
1. [Overview](#overview)
|
|
14
|
+
2. [Non-Interactive Command Syntax](#non-interactive-command-syntax)
|
|
15
|
+
3. [Passing Prompts](#passing-prompts)
|
|
16
|
+
4. [Output Formats](#output-formats)
|
|
17
|
+
5. [Error Handling](#error-handling)
|
|
18
|
+
6. [Authentication](#authentication)
|
|
19
|
+
7. [Rate Limiting](#rate-limiting)
|
|
20
|
+
8. [Session Management](#session-management)
|
|
21
|
+
9. [Context & File Passing](#context--file-passing)
|
|
22
|
+
10. [Model Selection](#model-selection)
|
|
23
|
+
11. [Streaming vs Non-Streaming](#streaming-vs-non-streaming)
|
|
24
|
+
12. [Tool Management](#tool-management)
|
|
25
|
+
13. [Practical Examples](#practical-examples)
|
|
26
|
+
14. [mdcontext Integration Recommendations](#mdcontext-integration-recommendations)
|
|
27
|
+
15. [Gotchas & Limitations](#gotchas--limitations)
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Overview
|
|
32
|
+
|
|
33
|
+
The Claude Code CLI provides the `-p` (or `--print`) flag for non-interactive programmatic usage. This mode executes a single query and outputs results directly without the interactive chat interface.
|
|
34
|
+
|
|
35
|
+
**Key Features:**
|
|
36
|
+
- Non-interactive execution
|
|
37
|
+
- Multiple output formats (text, JSON, streaming JSON)
|
|
38
|
+
- Tool permission control
|
|
39
|
+
- Session continuity
|
|
40
|
+
- Structured output with JSON Schema
|
|
41
|
+
- Budget controls
|
|
42
|
+
- Custom system prompts
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## Non-Interactive Command Syntax
|
|
47
|
+
|
|
48
|
+
### Basic Usage
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
claude -p "Your prompt here"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### With Options
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
claude -p [prompt] [options]
|
|
58
|
+
|
|
59
|
+
# Or via stdin
|
|
60
|
+
echo "Your prompt" | claude -p [options]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Critical Requirements
|
|
64
|
+
|
|
65
|
+
1. **Input is mandatory**: Must provide input via prompt argument OR stdin
|
|
66
|
+
2. **Trust bypass**: The `-p` flag automatically skips workspace trust dialog - only use in trusted directories
|
|
67
|
+
3. **No interactive prompts**: All tool permissions must be pre-approved via flags
|
|
68
|
+
|
|
69
|
+
**Exit on missing input:**
|
|
70
|
+
```bash
|
|
71
|
+
claude -p
|
|
72
|
+
# Error: Input must be provided either through stdin or as a prompt argument when using --print
|
|
73
|
+
# Exit code: 1
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Passing Prompts
|
|
79
|
+
|
|
80
|
+
### Three Methods
|
|
81
|
+
|
|
82
|
+
#### 1. Command Argument (Preferred for simple prompts)
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
claude -p "Summarize this project"
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
#### 2. Stdin (Preferred for complex/multiline prompts)
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
echo "Analyze the codebase structure" | claude -p
|
|
92
|
+
|
|
93
|
+
# Or from file
|
|
94
|
+
cat prompt.txt | claude -p
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
#### 3. Piped Context (Powerful for contextual analysis)
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
# Analyze PR diff
|
|
101
|
+
gh pr diff 123 | claude -p "Review for security issues"
|
|
102
|
+
|
|
103
|
+
# Analyze logs
|
|
104
|
+
cat error.log | claude -p "Identify patterns and suggest fixes"
|
|
105
|
+
|
|
106
|
+
# Analyze specific files
|
|
107
|
+
cat src/auth.ts | claude -p "Explain this authentication flow"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Prompt Best Practices
|
|
111
|
+
|
|
112
|
+
1. **Be specific**: "Extract all function names from auth.py" > "analyze auth.py"
|
|
113
|
+
2. **Include constraints**: "Summarize in 3 bullet points" constrains output
|
|
114
|
+
3. **Specify format**: "Return as JSON array" for structured output
|
|
115
|
+
4. **Combine with context**: Pipe file contents for better analysis
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## Output Formats
|
|
120
|
+
|
|
121
|
+
### Three Format Options
|
|
122
|
+
|
|
123
|
+
Set via `--output-format` flag:
|
|
124
|
+
|
|
125
|
+
#### 1. Text Format (Default)
|
|
126
|
+
|
|
127
|
+
**Use case**: Human-readable output, simple scripts
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
claude -p "What is 2+2?"
|
|
131
|
+
# Output: 2 + 2 = 4
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**Characteristics:**
|
|
135
|
+
- Plain text response
|
|
136
|
+
- No metadata
|
|
137
|
+
- Easy to parse for simple cases
|
|
138
|
+
- Default if `--output-format` not specified
|
|
139
|
+
|
|
140
|
+
#### 2. JSON Format
|
|
141
|
+
|
|
142
|
+
**Use case**: Programmatic processing, metadata extraction
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
claude -p "Summarize this project" --output-format json
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
**Output Structure:**
|
|
149
|
+
```json
|
|
150
|
+
{
|
|
151
|
+
"type": "result",
|
|
152
|
+
"subtype": "success",
|
|
153
|
+
"is_error": false,
|
|
154
|
+
"duration_ms": 3964,
|
|
155
|
+
"duration_api_ms": 3251,
|
|
156
|
+
"num_turns": 1,
|
|
157
|
+
"result": "Project is a CLI tool for...",
|
|
158
|
+
"session_id": "e0f0783c-29c8-43fa-8e55-8c96a920644c",
|
|
159
|
+
"total_cost_usd": 0.062059500000000004,
|
|
160
|
+
"usage": {
|
|
161
|
+
"input_tokens": 2,
|
|
162
|
+
"cache_creation_input_tokens": 15322,
|
|
163
|
+
"cache_read_input_tokens": 14070,
|
|
164
|
+
"output_tokens": 25,
|
|
165
|
+
"server_tool_use": {
|
|
166
|
+
"web_search_requests": 0,
|
|
167
|
+
"web_fetch_requests": 0
|
|
168
|
+
},
|
|
169
|
+
"service_tier": "standard",
|
|
170
|
+
"cache_creation": {
|
|
171
|
+
"ephemeral_1h_input_tokens": 0,
|
|
172
|
+
"ephemeral_5m_input_tokens": 15322
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
"modelUsage": {
|
|
176
|
+
"claude-sonnet-4-5-20250929": {
|
|
177
|
+
"inputTokens": 2,
|
|
178
|
+
"outputTokens": 25,
|
|
179
|
+
"cacheReadInputTokens": 14070,
|
|
180
|
+
"cacheCreationInputTokens": 15322,
|
|
181
|
+
"webSearchRequests": 0,
|
|
182
|
+
"costUSD": 0.062059500000000004,
|
|
183
|
+
"contextWindow": 200000,
|
|
184
|
+
"maxOutputTokens": 64000
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
"permission_denials": [],
|
|
188
|
+
"uuid": "feeed03d-a79c-442f-9040-0be9f0a45ea8"
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
**Extract result with jq:**
|
|
193
|
+
```bash
|
|
194
|
+
claude -p "Summarize this project" --output-format json | jq -r '.result'
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
**Extract cost:**
|
|
198
|
+
```bash
|
|
199
|
+
claude -p "Analyze code" --output-format json | jq -r '.total_cost_usd'
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
#### 3. Stream-JSON Format
|
|
203
|
+
|
|
204
|
+
**Use case**: Real-time streaming, progress monitoring, event processing
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
claude -p "Long analysis task" --output-format stream-json --verbose
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
**Requires**: `--verbose` flag when used with `--print`
|
|
211
|
+
|
|
212
|
+
**Output Format**: Newline-delimited JSON (NDJSON)
|
|
213
|
+
|
|
214
|
+
**Event Types:**
|
|
215
|
+
```json
|
|
216
|
+
{"type":"system","subtype":"init","session_id":"...","tools":[...],"model":"claude-sonnet-4-5-20250929"}
|
|
217
|
+
{"type":"assistant","message":{"content":[{"type":"text","text":"Analyzing..."}]}}
|
|
218
|
+
{"type":"result","subtype":"success","result":"Final answer","total_cost_usd":0.05}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
**Process with jq:**
|
|
222
|
+
```bash
|
|
223
|
+
# Extract only text deltas
|
|
224
|
+
claude -p "Analyze" --output-format stream-json --verbose |
|
|
225
|
+
jq -j '.event.delta.text? // empty'
|
|
226
|
+
|
|
227
|
+
# Filter specific event types
|
|
228
|
+
claude -p "Analyze" --output-format stream-json --verbose |
|
|
229
|
+
jq 'select(.type == "assistant")'
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
**Note**: When using `--json-schema`, structured output only appears in final result, not during streaming.
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
## Error Handling
|
|
237
|
+
|
|
238
|
+
### Exit Codes
|
|
239
|
+
|
|
240
|
+
| Exit Code | Meaning | Example |
|
|
241
|
+
|-----------|---------|---------|
|
|
242
|
+
| 0 | Success | Normal completion |
|
|
243
|
+
| 1 | General failure | Invalid input, API errors, budget exceeded |
|
|
244
|
+
| 124 | Timeout (via external timeout) | `timeout 5 claude -p "..."` |
|
|
245
|
+
| 127 | Command not found | Claude CLI not installed |
|
|
246
|
+
|
|
247
|
+
### Error Detection
|
|
248
|
+
|
|
249
|
+
```bash
|
|
250
|
+
# Check exit code
|
|
251
|
+
claude -p "test" --output-format json
|
|
252
|
+
if [ $? -eq 0 ]; then
|
|
253
|
+
echo "Success"
|
|
254
|
+
else
|
|
255
|
+
echo "Failed"
|
|
256
|
+
fi
|
|
257
|
+
|
|
258
|
+
# With JSON output
|
|
259
|
+
result=$(claude -p "test" --output-format json)
|
|
260
|
+
is_error=$(echo "$result" | jq -r '.is_error')
|
|
261
|
+
if [ "$is_error" = "true" ]; then
|
|
262
|
+
echo "Error occurred"
|
|
263
|
+
fi
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
### Common Errors
|
|
267
|
+
|
|
268
|
+
#### 1. Missing Input
|
|
269
|
+
|
|
270
|
+
```bash
|
|
271
|
+
claude -p
|
|
272
|
+
# Error: Input must be provided either through stdin or as a prompt argument when using --print
|
|
273
|
+
# Exit code: 1
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
#### 2. Invalid Model
|
|
277
|
+
|
|
278
|
+
```bash
|
|
279
|
+
claude -p "test" --model invalid-model
|
|
280
|
+
# API Error: 404 {"type":"error","error":{"type":"not_found_error","message":"model: invalid-model"}}
|
|
281
|
+
# Exit code: 1
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
#### 3. Budget Exceeded
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
claude -p "Analyze everything" --max-budget-usd 0.01
|
|
288
|
+
# Error: Exceeded USD budget (0.01)
|
|
289
|
+
# Exit code: 1
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
#### 4. Rate Limiting (429 Error)
|
|
293
|
+
|
|
294
|
+
```bash
|
|
295
|
+
# Too many requests
|
|
296
|
+
# API Error: 429 {"type":"error","error":{"type":"rate_limit_error","message":"..."}}
|
|
297
|
+
# Exit code: 1
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
**Response includes `retry-after` header indicating wait time**
|
|
301
|
+
|
|
302
|
+
#### 5. Authentication Error (401)
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
# Invalid or missing API key
|
|
306
|
+
# API Error: 401 {"type":"error","error":{"type":"authentication_error"}}
|
|
307
|
+
# Exit code: 1
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
### Error Handling Pattern
|
|
311
|
+
|
|
312
|
+
```bash
|
|
313
|
+
#!/bin/bash
|
|
314
|
+
|
|
315
|
+
handle_claude_error() {
|
|
316
|
+
local exit_code=$?
|
|
317
|
+
local stderr_output="$1"
|
|
318
|
+
|
|
319
|
+
case $exit_code in
|
|
320
|
+
0)
|
|
321
|
+
return 0
|
|
322
|
+
;;
|
|
323
|
+
1)
|
|
324
|
+
if echo "$stderr_output" | grep -q "rate_limit_error"; then
|
|
325
|
+
echo "Rate limited, retrying in 60s..."
|
|
326
|
+
sleep 60
|
|
327
|
+
return 2 # Retry signal
|
|
328
|
+
elif echo "$stderr_output" | grep -q "Budget exceeded"; then
|
|
329
|
+
echo "Budget exceeded, aborting"
|
|
330
|
+
return 1
|
|
331
|
+
else
|
|
332
|
+
echo "API error: $stderr_output"
|
|
333
|
+
return 1
|
|
334
|
+
fi
|
|
335
|
+
;;
|
|
336
|
+
124)
|
|
337
|
+
echo "Timeout"
|
|
338
|
+
return 1
|
|
339
|
+
;;
|
|
340
|
+
*)
|
|
341
|
+
echo "Unknown error: $exit_code"
|
|
342
|
+
return 1
|
|
343
|
+
;;
|
|
344
|
+
esac
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
# Usage
|
|
348
|
+
output=$(claude -p "test" 2>&1)
|
|
349
|
+
exit_code=$?
|
|
350
|
+
handle_claude_error "$output" || exit 1
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
---
|
|
354
|
+
|
|
355
|
+
## Authentication
|
|
356
|
+
|
|
357
|
+
### Authentication Methods
|
|
358
|
+
|
|
359
|
+
Claude Code supports multiple authentication methods, prioritized in this order:
|
|
360
|
+
|
|
361
|
+
1. **Environment variable API key** (highest priority)
|
|
362
|
+
2. **Subscription-based authentication** (Claude Pro/Team via browser login)
|
|
363
|
+
3. **Azure Auth**
|
|
364
|
+
4. **Bedrock Auth**
|
|
365
|
+
5. **Vertex Auth**
|
|
366
|
+
|
|
367
|
+
### Setting API Key
|
|
368
|
+
|
|
369
|
+
```bash
|
|
370
|
+
# Environment variable (priority over subscription)
|
|
371
|
+
export ANTHROPIC_API_KEY="sk-ant-api03-..."
|
|
372
|
+
|
|
373
|
+
# Now all claude commands use API key
|
|
374
|
+
claude -p "test"
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
**Warning**: When API key is set via environment variable, you're charged via API pay-as-you-go rates, even if you have a subscription.
|
|
378
|
+
|
|
379
|
+
### Check Authentication Status
|
|
380
|
+
|
|
381
|
+
```bash
|
|
382
|
+
# In interactive mode (not available in -p mode)
|
|
383
|
+
/status
|
|
384
|
+
|
|
385
|
+
# Shows which authentication method is active
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
### Programmatic API Key Management
|
|
389
|
+
|
|
390
|
+
Use `apiKeyHelper` setting to run a shell script that returns an API key:
|
|
391
|
+
|
|
392
|
+
```bash
|
|
393
|
+
# In settings.json
|
|
394
|
+
{
|
|
395
|
+
"apiKeyHelper": "/path/to/script-that-returns-key.sh"
|
|
396
|
+
}
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
**Behavior:**
|
|
400
|
+
- Called after 5 minutes of inactivity
|
|
401
|
+
- Called on HTTP 401 response
|
|
402
|
+
- Can refresh expired keys automatically
|
|
403
|
+
|
|
404
|
+
### Authentication Check Pattern
|
|
405
|
+
|
|
406
|
+
```bash
|
|
407
|
+
# Test if authenticated
|
|
408
|
+
if claude -p "test" --output-format json >/dev/null 2>&1; then
|
|
409
|
+
echo "Authenticated"
|
|
410
|
+
else
|
|
411
|
+
echo "Authentication failed"
|
|
412
|
+
exit 1
|
|
413
|
+
fi
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
### Credential Storage
|
|
417
|
+
|
|
418
|
+
- **macOS**: API keys and OAuth tokens stored in encrypted Keychain
|
|
419
|
+
- **Linux/Windows**: Implementation-specific secure storage
|
|
420
|
+
|
|
421
|
+
---
|
|
422
|
+
|
|
423
|
+
## Rate Limiting
|
|
424
|
+
|
|
425
|
+
### Rate Limit Types
|
|
426
|
+
|
|
427
|
+
Claude API enforces organization-level rate limits:
|
|
428
|
+
|
|
429
|
+
1. **Requests per minute (RPM)**: Total API requests
|
|
430
|
+
2. **Input tokens per minute (ITPM)**: Input token consumption
|
|
431
|
+
3. **Output tokens per minute (OTPM)**: Output token generation
|
|
432
|
+
|
|
433
|
+
**Important**: Limits are **organization-wide**, not per API key. All keys under your account share the same limit pool.
|
|
434
|
+
|
|
435
|
+
### Rate Limit Algorithm
|
|
436
|
+
|
|
437
|
+
Uses **token bucket algorithm**:
|
|
438
|
+
- Capacity continuously replenished up to maximum
|
|
439
|
+
- Not reset at fixed intervals
|
|
440
|
+
- Smooth rate limiting, not burst-then-wait
|
|
441
|
+
|
|
442
|
+
### Rate Limit Errors
|
|
443
|
+
|
|
444
|
+
When exceeded, you receive:
|
|
445
|
+
```json
|
|
446
|
+
{
|
|
447
|
+
"type": "error",
|
|
448
|
+
"error": {
|
|
449
|
+
"type": "rate_limit_error",
|
|
450
|
+
"message": "Number of requests has exceeded your per-minute rate limit"
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
**Includes `retry-after` header** with wait time in seconds.
|
|
456
|
+
|
|
457
|
+
### Handling Rate Limits
|
|
458
|
+
|
|
459
|
+
```bash
|
|
460
|
+
#!/bin/bash
|
|
461
|
+
|
|
462
|
+
MAX_RETRIES=3
|
|
463
|
+
RETRY_DELAY=60
|
|
464
|
+
|
|
465
|
+
for i in $(seq 1 $MAX_RETRIES); do
|
|
466
|
+
output=$(claude -p "Analyze code" --output-format json 2>&1)
|
|
467
|
+
exit_code=$?
|
|
468
|
+
|
|
469
|
+
if [ $exit_code -eq 0 ]; then
|
|
470
|
+
echo "$output"
|
|
471
|
+
exit 0
|
|
472
|
+
fi
|
|
473
|
+
|
|
474
|
+
if echo "$output" | grep -q "rate_limit_error"; then
|
|
475
|
+
echo "Rate limited, retry $i/$MAX_RETRIES in ${RETRY_DELAY}s"
|
|
476
|
+
sleep $RETRY_DELAY
|
|
477
|
+
else
|
|
478
|
+
echo "Error: $output"
|
|
479
|
+
exit 1
|
|
480
|
+
fi
|
|
481
|
+
done
|
|
482
|
+
|
|
483
|
+
echo "Max retries exceeded"
|
|
484
|
+
exit 1
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
### Cost Tracking
|
|
488
|
+
|
|
489
|
+
Track costs in real-time with JSON output:
|
|
490
|
+
|
|
491
|
+
```bash
|
|
492
|
+
total_cost=0
|
|
493
|
+
|
|
494
|
+
for file in src/*.ts; do
|
|
495
|
+
result=$(claude -p "Summarize $file" --output-format json)
|
|
496
|
+
cost=$(echo "$result" | jq -r '.total_cost_usd')
|
|
497
|
+
total_cost=$(echo "$total_cost + $cost" | bc)
|
|
498
|
+
echo "Processed $file (cost: $cost)"
|
|
499
|
+
done
|
|
500
|
+
|
|
501
|
+
echo "Total cost: $total_cost"
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
### Budget Controls
|
|
505
|
+
|
|
506
|
+
Set maximum spend:
|
|
507
|
+
|
|
508
|
+
```bash
|
|
509
|
+
# Limit to $1 per operation (only works with -p)
|
|
510
|
+
claude -p "Expensive operation" --max-budget-usd 1.0
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
**Behavior:**
|
|
514
|
+
- Aborts if estimated cost exceeds budget
|
|
515
|
+
- Exit code 1 with error message
|
|
516
|
+
- Prevents runaway costs in automation
|
|
517
|
+
|
|
518
|
+
---
|
|
519
|
+
|
|
520
|
+
## Session Management
|
|
521
|
+
|
|
522
|
+
### Session Modes
|
|
523
|
+
|
|
524
|
+
#### 1. Stateless (Default with --no-session-persistence)
|
|
525
|
+
|
|
526
|
+
```bash
|
|
527
|
+
# No session saved to disk
|
|
528
|
+
claude -p "test" --no-session-persistence
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
**Use case**: One-off queries, CI/CD, stateless automation
|
|
532
|
+
|
|
533
|
+
#### 2. Stateful (Default)
|
|
534
|
+
|
|
535
|
+
```bash
|
|
536
|
+
# Session saved and resumable
|
|
537
|
+
claude -p "Start analysis"
|
|
538
|
+
# Returns session_id in JSON output
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
**Session ID available in JSON output:**
|
|
542
|
+
```json
|
|
543
|
+
{
|
|
544
|
+
"session_id": "e0f0783c-29c8-43fa-8e55-8c96a920644c"
|
|
545
|
+
}
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
### Continuing Conversations
|
|
549
|
+
|
|
550
|
+
#### Continue Most Recent
|
|
551
|
+
|
|
552
|
+
```bash
|
|
553
|
+
# First request
|
|
554
|
+
claude -p "Review this codebase for performance issues"
|
|
555
|
+
|
|
556
|
+
# Continue most recent conversation
|
|
557
|
+
claude -p "Now focus on the database queries" --continue
|
|
558
|
+
claude -p "Generate a summary of all issues found" --continue
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
#### Resume Specific Session
|
|
562
|
+
|
|
563
|
+
```bash
|
|
564
|
+
# Capture session ID
|
|
565
|
+
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
|
|
566
|
+
|
|
567
|
+
# Resume later
|
|
568
|
+
claude -p "Continue that review" --resume "$session_id"
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
#### Fork Session
|
|
572
|
+
|
|
573
|
+
```bash
|
|
574
|
+
# Create new session ID when resuming (branch conversation)
|
|
575
|
+
claude -p "Try different approach" --resume "$session_id" --fork-session
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
### Session Use Cases
|
|
579
|
+
|
|
580
|
+
**Multi-step analysis:**
|
|
581
|
+
```bash
|
|
582
|
+
#!/bin/bash
|
|
583
|
+
|
|
584
|
+
# Step 1: Initial analysis
|
|
585
|
+
claude -p "Analyze codebase architecture" > step1.txt
|
|
586
|
+
|
|
587
|
+
# Step 2: Deep dive
|
|
588
|
+
claude -p "Focus on authentication module" --continue > step2.txt
|
|
589
|
+
|
|
590
|
+
# Step 3: Recommendations
|
|
591
|
+
claude -p "List top 3 improvements" --continue > step3.txt
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
**Parallel analysis with forking:**
|
|
595
|
+
```bash
|
|
596
|
+
# Create base analysis
|
|
597
|
+
base_session=$(claude -p "Analyze API" --output-format json | jq -r '.session_id')
|
|
598
|
+
|
|
599
|
+
# Fork for security review
|
|
600
|
+
claude -p "Security concerns?" --resume "$base_session" --fork-session > security.txt
|
|
601
|
+
|
|
602
|
+
# Fork for performance review
|
|
603
|
+
claude -p "Performance issues?" --resume "$base_session" --fork-session > performance.txt
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
---
|
|
607
|
+
|
|
608
|
+
## Context & File Passing
|
|
609
|
+
|
|
610
|
+
### Methods to Provide Context
|
|
611
|
+
|
|
612
|
+
#### 1. Current Working Directory
|
|
613
|
+
|
|
614
|
+
Claude automatically has access to current directory:
|
|
615
|
+
|
|
616
|
+
```bash
|
|
617
|
+
cd /path/to/project
|
|
618
|
+
claude -p "Analyze this project structure"
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
#### 2. Additional Directories
|
|
622
|
+
|
|
623
|
+
```bash
|
|
624
|
+
# Grant access to specific directories
|
|
625
|
+
claude -p "Analyze both projects" --add-dir /path/to/project1 --add-dir /path/to/project2
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
#### 3. Piped File Contents
|
|
629
|
+
|
|
630
|
+
```bash
|
|
631
|
+
# Single file
|
|
632
|
+
cat src/main.ts | claude -p "Explain this code"
|
|
633
|
+
|
|
634
|
+
# Multiple files
|
|
635
|
+
cat src/*.ts | claude -p "Summarize all TypeScript files"
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
#### 4. File Attachments (Via MCP/Tools)
|
|
639
|
+
|
|
640
|
+
```bash
|
|
641
|
+
# Claude can use Read tool to access files
|
|
642
|
+
claude -p "Read and analyze src/auth.ts" --allowed-tools "Read"
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
#### 5. Explicit File Resources
|
|
646
|
+
|
|
647
|
+
```bash
|
|
648
|
+
# Download files at startup (from Claude API file resources)
|
|
649
|
+
claude -p "Analyze these files" --file file_abc:doc.txt --file file_def:img.png
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
### Context Best Practices
|
|
653
|
+
|
|
654
|
+
**For mdcontext use case:**
|
|
655
|
+
|
|
656
|
+
1. **Pipe file tree for structure:**
|
|
657
|
+
```bash
|
|
658
|
+
tree -L 3 | claude -p "Summarize project structure"
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
2. **Pipe specific files for analysis:**
|
|
662
|
+
```bash
|
|
663
|
+
cat README.md src/main.ts | claude -p "Create project overview"
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
3. **Use Read tool for file access:**
|
|
667
|
+
```bash
|
|
668
|
+
claude -p "Read all .ts files and create summary" --allowed-tools "Read,Grep,Glob"
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
4. **Combine with git context:**
|
|
672
|
+
```bash
|
|
673
|
+
git log --oneline -20 | claude -p "Summarize recent changes"
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
### Context Limits
|
|
677
|
+
|
|
678
|
+
**Token limits:**
|
|
679
|
+
- Sonnet 4.5: 200,000 token context window
|
|
680
|
+
- Opus 4.5: 200,000 token context window
|
|
681
|
+
|
|
682
|
+
**Estimation:**
|
|
683
|
+
- ~4 characters per token (English)
|
|
684
|
+
- ~200,000 chars = ~50,000 tokens
|
|
685
|
+
- Monitor with JSON output: `usage.input_tokens`
|
|
686
|
+
|
|
687
|
+
**Stay within limits:**
|
|
688
|
+
```bash
|
|
689
|
+
# Check token usage
|
|
690
|
+
result=$(claude -p "Large prompt" --output-format json)
|
|
691
|
+
input_tokens=$(echo "$result" | jq -r '.usage.input_tokens')
|
|
692
|
+
|
|
693
|
+
if [ "$input_tokens" -gt 100000 ]; then
|
|
694
|
+
echo "Warning: High token usage ($input_tokens)"
|
|
695
|
+
fi
|
|
696
|
+
```
|
|
697
|
+
|
|
698
|
+
---
|
|
699
|
+
|
|
700
|
+
## Model Selection
|
|
701
|
+
|
|
702
|
+
### Available Models (2026)
|
|
703
|
+
|
|
704
|
+
```bash
|
|
705
|
+
# Latest Sonnet (default)
|
|
706
|
+
claude -p "test" --model sonnet
|
|
707
|
+
|
|
708
|
+
# Latest Opus (most capable)
|
|
709
|
+
claude -p "complex task" --model opus
|
|
710
|
+
|
|
711
|
+
# Specific version
|
|
712
|
+
claude -p "test" --model claude-sonnet-4-5-20250929
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
### Model Aliases
|
|
716
|
+
|
|
717
|
+
- `sonnet` → Latest Sonnet 4.5
|
|
718
|
+
- `opus` → Latest Opus 4.5
|
|
719
|
+
- Full names: `claude-sonnet-4-5-20250929`, `claude-opus-4-5-20251101`
|
|
720
|
+
|
|
721
|
+
### Fallback Models
|
|
722
|
+
|
|
723
|
+
```bash
|
|
724
|
+
# Auto-fallback if primary model is overloaded (only with -p)
|
|
725
|
+
claude -p "test" --model sonnet --fallback-model opus
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
**Behavior:**
|
|
729
|
+
- Automatically switches to fallback on overload (529 error)
|
|
730
|
+
- No manual intervention needed
|
|
731
|
+
- Transparent failover
|
|
732
|
+
|
|
733
|
+
### Model Selection Strategy
|
|
734
|
+
|
|
735
|
+
**For mdcontext:**
|
|
736
|
+
|
|
737
|
+
1. **Use Sonnet for most tasks** (fast, cost-effective)
|
|
738
|
+
```bash
|
|
739
|
+
claude -p "Summarize codebase" --model sonnet
|
|
740
|
+
```
|
|
741
|
+
|
|
742
|
+
2. **Use Opus for complex analysis** (deeper understanding)
|
|
743
|
+
```bash
|
|
744
|
+
claude -p "Architectural review with recommendations" --model opus
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
3. **Always set fallback** (reliability)
|
|
748
|
+
```bash
|
|
749
|
+
claude -p "Critical analysis" --model sonnet --fallback-model opus
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
### Model Costs (From JSON Output)
|
|
753
|
+
|
|
754
|
+
Track per-model usage:
|
|
755
|
+
```json
|
|
756
|
+
{
|
|
757
|
+
"modelUsage": {
|
|
758
|
+
"claude-sonnet-4-5-20250929": {
|
|
759
|
+
"inputTokens": 2,
|
|
760
|
+
"outputTokens": 25,
|
|
761
|
+
"costUSD": 0.062059500000000004
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
```
|
|
766
|
+
|
|
767
|
+
---
|
|
768
|
+
|
|
769
|
+
## Streaming vs Non-Streaming
|
|
770
|
+
|
|
771
|
+
### Non-Streaming (Default)
|
|
772
|
+
|
|
773
|
+
**Text format:**
|
|
774
|
+
```bash
|
|
775
|
+
claude -p "What is 2+2?"
|
|
776
|
+
# Waits for complete response
|
|
777
|
+
# Output: 2 + 2 = 4
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
**JSON format:**
|
|
781
|
+
```bash
|
|
782
|
+
claude -p "Analyze code" --output-format json
|
|
783
|
+
# Waits for complete response
|
|
784
|
+
# Returns single JSON object
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
**Characteristics:**
|
|
788
|
+
- Blocks until complete
|
|
789
|
+
- Single output
|
|
790
|
+
- Easy to process
|
|
791
|
+
- No real-time feedback
|
|
792
|
+
|
|
793
|
+
### Streaming (stream-json)
|
|
794
|
+
|
|
795
|
+
```bash
|
|
796
|
+
claude -p "Long analysis" --output-format stream-json --verbose
|
|
797
|
+
```
|
|
798
|
+
|
|
799
|
+
**Requires:** `--verbose` flag
|
|
800
|
+
|
|
801
|
+
**Characteristics:**
|
|
802
|
+
- Real-time events
|
|
803
|
+
- Newline-delimited JSON (NDJSON)
|
|
804
|
+
- Progress monitoring
|
|
805
|
+
- Can process incrementally
|
|
806
|
+
|
|
807
|
+
### Event Types
|
|
808
|
+
|
|
809
|
+
```json
|
|
810
|
+
// Initialization
|
|
811
|
+
{"type":"system","subtype":"init","session_id":"...","model":"..."}
|
|
812
|
+
|
|
813
|
+
// Assistant messages
|
|
814
|
+
{"type":"assistant","message":{"content":[{"type":"text","text":"..."}]}}
|
|
815
|
+
|
|
816
|
+
// Final result
|
|
817
|
+
{"type":"result","subtype":"success","result":"...","total_cost_usd":0.05}
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
### Processing Streaming Output
|
|
821
|
+
|
|
822
|
+
**Extract text only:**
|
|
823
|
+
```bash
|
|
824
|
+
claude -p "Analyze" --output-format stream-json --verbose |
|
|
825
|
+
jq -j '.event.delta.text? // empty'
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
**Monitor progress:**
|
|
829
|
+
```bash
|
|
830
|
+
claude -p "Long task" --output-format stream-json --verbose |
|
|
831
|
+
while IFS= read -r line; do
|
|
832
|
+
type=$(echo "$line" | jq -r '.type')
|
|
833
|
+
case $type in
|
|
834
|
+
system)
|
|
835
|
+
echo "Initialized"
|
|
836
|
+
;;
|
|
837
|
+
assistant)
|
|
838
|
+
echo -n "."
|
|
839
|
+
;;
|
|
840
|
+
result)
|
|
841
|
+
echo " Done!"
|
|
842
|
+
echo "$line" | jq -r '.result'
|
|
843
|
+
;;
|
|
844
|
+
esac
|
|
845
|
+
done
|
|
846
|
+
```
|
|
847
|
+
|
|
848
|
+
### Structured Output with Streaming
|
|
849
|
+
|
|
850
|
+
**Limitation**: When using `--json-schema`, structured output only appears in final result:
|
|
851
|
+
|
|
852
|
+
```bash
|
|
853
|
+
claude -p "Extract functions" \
|
|
854
|
+
--output-format stream-json \
|
|
855
|
+
--json-schema '{"type":"object","properties":{"functions":{"type":"array"}}}' \
|
|
856
|
+
--verbose
|
|
857
|
+
# Streams natural language, structured output only in final result.structured_output
|
|
858
|
+
```
|
|
859
|
+
|
|
860
|
+
**Extract structured output:**
|
|
861
|
+
```bash
|
|
862
|
+
result=$(claude -p "Extract data" \
|
|
863
|
+
--output-format stream-json \
|
|
864
|
+
--json-schema '...' \
|
|
865
|
+
--verbose | tail -1)
|
|
866
|
+
|
|
867
|
+
structured=$(echo "$result" | jq '.structured_output')
|
|
868
|
+
```
|
|
869
|
+
|
|
870
|
+
### When to Use Each
|
|
871
|
+
|
|
872
|
+
**Use non-streaming (text/json):**
|
|
873
|
+
- Simple queries
|
|
874
|
+
- Scripts that need complete result
|
|
875
|
+
- Single-step processing
|
|
876
|
+
- Cost tracking (easier with single JSON)
|
|
877
|
+
|
|
878
|
+
**Use streaming (stream-json):**
|
|
879
|
+
- Long-running tasks
|
|
880
|
+
- Progress monitoring needed
|
|
881
|
+
- Multi-agent pipelines
|
|
882
|
+
- Real-time feedback for users
|
|
883
|
+
|
|
884
|
+
---
|
|
885
|
+
|
|
886
|
+
## Tool Management
|
|
887
|
+
|
|
888
|
+
### Tool Permission Modes
|
|
889
|
+
|
|
890
|
+
```bash
|
|
891
|
+
# Default: Prompt for each tool (not usable in -p mode)
|
|
892
|
+
claude -p "Analyze" --permission-mode default
|
|
893
|
+
|
|
894
|
+
# Auto-accept edits
|
|
895
|
+
claude -p "Fix bugs" --permission-mode acceptEdits
|
|
896
|
+
|
|
897
|
+
# Bypass all permissions (dangerous, sandbox only)
|
|
898
|
+
claude -p "Analyze" --dangerously-skip-permissions
|
|
899
|
+
|
|
900
|
+
# Don't ask (but still track permissions)
|
|
901
|
+
claude -p "Analyze" --permission-mode dontAsk
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
### Allowed Tools
|
|
905
|
+
|
|
906
|
+
**Syntax:**
|
|
907
|
+
```bash
|
|
908
|
+
# Specific tools
|
|
909
|
+
claude -p "Fix tests" --allowed-tools "Bash,Read,Edit"
|
|
910
|
+
|
|
911
|
+
# Tool with command filtering
|
|
912
|
+
claude -p "Review" --allowed-tools "Bash(git:*)"
|
|
913
|
+
|
|
914
|
+
# Permission rule syntax with prefix matching
|
|
915
|
+
claude -p "Commit" --allowed-tools "Bash(git diff:*),Bash(git log:*),Bash(git status:*),Bash(git commit:*)"
|
|
916
|
+
```
|
|
917
|
+
|
|
918
|
+
**Available built-in tools:**
|
|
919
|
+
- `Bash` - Execute shell commands
|
|
920
|
+
- `Read` - Read files
|
|
921
|
+
- `Write` - Write files
|
|
922
|
+
- `Edit` - Edit files
|
|
923
|
+
- `Glob` - Find files by pattern
|
|
924
|
+
- `Grep` - Search file contents
|
|
925
|
+
- `NotebookEdit` - Edit Jupyter notebooks
|
|
926
|
+
- `WebFetch` - Fetch web content
|
|
927
|
+
- `WebSearch` - Search the web
|
|
928
|
+
- `Task` - Run sub-agents
|
|
929
|
+
- `TodoWrite` - Task management
|
|
930
|
+
- MCP tools (if configured)
|
|
931
|
+
|
|
932
|
+
### Disallowed Tools
|
|
933
|
+
|
|
934
|
+
```bash
|
|
935
|
+
# Prevent specific tools
|
|
936
|
+
claude -p "Analyze" --disallowed-tools "WebSearch,WebFetch"
|
|
937
|
+
|
|
938
|
+
# Prevent specific commands
|
|
939
|
+
claude -p "Analyze" --disallowed-tools "Bash(rm:*)"
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
### Disable All Tools
|
|
943
|
+
|
|
944
|
+
```bash
|
|
945
|
+
# Pure LLM, no tool use
|
|
946
|
+
claude -p "Explain concept" --tools ""
|
|
947
|
+
```
|
|
948
|
+
|
|
949
|
+
### Tool Selection Strategy
|
|
950
|
+
|
|
951
|
+
**For mdcontext (read-only analysis):**
|
|
952
|
+
|
|
953
|
+
```bash
|
|
954
|
+
# Safe, read-only tools
|
|
955
|
+
claude -p "Summarize codebase" \
|
|
956
|
+
--allowed-tools "Read,Grep,Glob,Bash(git:*)" \
|
|
957
|
+
--disallowed-tools "Write,Edit"
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
**For automated fixes (requires trust):**
|
|
961
|
+
|
|
962
|
+
```bash
|
|
963
|
+
# Allow edits with git safety
|
|
964
|
+
claude -p "Fix linting errors" \
|
|
965
|
+
--allowed-tools "Read,Edit,Bash(npm:*),Bash(git diff:*)" \
|
|
966
|
+
--disallowed-tools "Bash(rm:*),Bash(git push:*)"
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
### Permission Denials
|
|
970
|
+
|
|
971
|
+
Track denied permissions in JSON output:
|
|
972
|
+
|
|
973
|
+
```json
|
|
974
|
+
{
|
|
975
|
+
"permission_denials": [
|
|
976
|
+
{
|
|
977
|
+
"tool": "Write",
|
|
978
|
+
"reason": "Tool not in allowed list"
|
|
979
|
+
}
|
|
980
|
+
]
|
|
981
|
+
}
|
|
982
|
+
```
|
|
983
|
+
|
|
984
|
+
---
|
|
985
|
+
|
|
986
|
+
## Practical Examples
|
|
987
|
+
|
|
988
|
+
### 1. Simple Codebase Summary
|
|
989
|
+
|
|
990
|
+
```bash
|
|
991
|
+
claude -p "Summarize the architecture of this project"
|
|
992
|
+
```
|
|
993
|
+
|
|
994
|
+
### 2. Structured Function Extraction
|
|
995
|
+
|
|
996
|
+
```bash
|
|
997
|
+
claude -p "Extract all function names from src/auth.ts" \
|
|
998
|
+
--output-format json \
|
|
999
|
+
--json-schema '{
|
|
1000
|
+
"type": "object",
|
|
1001
|
+
"properties": {
|
|
1002
|
+
"functions": {
|
|
1003
|
+
"type": "array",
|
|
1004
|
+
"items": {"type": "string"}
|
|
1005
|
+
}
|
|
1006
|
+
},
|
|
1007
|
+
"required": ["functions"]
|
|
1008
|
+
}' | jq '.structured_output.functions'
|
|
1009
|
+
```
|
|
1010
|
+
|
|
1011
|
+
### 3. Security Review Pipeline
|
|
1012
|
+
|
|
1013
|
+
```bash
|
|
1014
|
+
#!/bin/bash
|
|
1015
|
+
|
|
1016
|
+
# Review PR for security issues
|
|
1017
|
+
gh pr diff "$1" | claude -p \
|
|
1018
|
+
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
|
|
1019
|
+
--output-format json \
|
|
1020
|
+
--allowed-tools "Read,Grep" > security-report.json
|
|
1021
|
+
|
|
1022
|
+
# Extract issues
|
|
1023
|
+
jq -r '.result' security-report.json
|
|
1024
|
+
```
|
|
1025
|
+
|
|
1026
|
+
### 4. Multi-Step Analysis with Session
|
|
1027
|
+
|
|
1028
|
+
```bash
|
|
1029
|
+
#!/bin/bash
|
|
1030
|
+
|
|
1031
|
+
# Step 1: Architecture overview
|
|
1032
|
+
claude -p "Analyze the architecture of this project" > arch.txt
|
|
1033
|
+
|
|
1034
|
+
# Step 2: Security deep-dive
|
|
1035
|
+
claude -p "Now focus on security concerns" --continue > security.txt
|
|
1036
|
+
|
|
1037
|
+
# Step 3: Performance analysis
|
|
1038
|
+
claude -p "Now analyze performance bottlenecks" --continue > performance.txt
|
|
1039
|
+
|
|
1040
|
+
# Step 4: Final recommendations
|
|
1041
|
+
claude -p "Provide top 5 actionable recommendations" --continue > recommendations.txt
|
|
1042
|
+
```
|
|
1043
|
+
|
|
1044
|
+
### 5. Batch Processing with Cost Tracking
|
|
1045
|
+
|
|
1046
|
+
```bash
|
|
1047
|
+
#!/bin/bash
|
|
1048
|
+
|
|
1049
|
+
total_cost=0
|
|
1050
|
+
results_file="summaries.json"
|
|
1051
|
+
echo "[]" > "$results_file"
|
|
1052
|
+
|
|
1053
|
+
for file in src/**/*.ts; do
|
|
1054
|
+
echo "Processing $file..."
|
|
1055
|
+
|
|
1056
|
+
result=$(claude -p "Summarize this file: $(cat $file)" \
|
|
1057
|
+
--output-format json \
|
|
1058
|
+
--model sonnet \
|
|
1059
|
+
--max-budget-usd 0.50)
|
|
1060
|
+
|
|
1061
|
+
# Extract cost
|
|
1062
|
+
cost=$(echo "$result" | jq -r '.total_cost_usd')
|
|
1063
|
+
total_cost=$(echo "$total_cost + $cost" | bc)
|
|
1064
|
+
|
|
1065
|
+
# Append result
|
|
1066
|
+
summary=$(echo "$result" | jq -r '.result')
|
|
1067
|
+
jq --arg file "$file" --arg summary "$summary" \
|
|
1068
|
+
'. += [{"file": $file, "summary": $summary}]' \
|
|
1069
|
+
"$results_file" > tmp.json && mv tmp.json "$results_file"
|
|
1070
|
+
|
|
1071
|
+
echo " Cost: \$$cost"
|
|
1072
|
+
done
|
|
1073
|
+
|
|
1074
|
+
echo "Total cost: \$$total_cost"
|
|
1075
|
+
echo "Results written to $results_file"
|
|
1076
|
+
```
|
|
1077
|
+
|
|
1078
|
+
### 6. Stream Processing with Progress
|
|
1079
|
+
|
|
1080
|
+
```bash
|
|
1081
|
+
#!/bin/bash
|
|
1082
|
+
|
|
1083
|
+
echo "Analyzing codebase..."
|
|
1084
|
+
|
|
1085
|
+
claude -p "Comprehensive architecture analysis" \
|
|
1086
|
+
--output-format stream-json \
|
|
1087
|
+
--verbose \
|
|
1088
|
+
--allowed-tools "Read,Grep,Glob,Bash(git:*)" |
|
|
1089
|
+
while IFS= read -r line; do
|
|
1090
|
+
type=$(echo "$line" | jq -r '.type // empty')
|
|
1091
|
+
|
|
1092
|
+
case $type in
|
|
1093
|
+
system)
|
|
1094
|
+
echo "Initialized session"
|
|
1095
|
+
;;
|
|
1096
|
+
assistant)
|
|
1097
|
+
# Show progress dots
|
|
1098
|
+
echo -n "."
|
|
1099
|
+
;;
|
|
1100
|
+
result)
|
|
1101
|
+
echo ""
|
|
1102
|
+
echo "Complete!"
|
|
1103
|
+
echo "$line" | jq -r '.result' > analysis.txt
|
|
1104
|
+
echo "Cost: $(echo "$line" | jq -r '.total_cost_usd')"
|
|
1105
|
+
;;
|
|
1106
|
+
esac
|
|
1107
|
+
done
|
|
1108
|
+
|
|
1109
|
+
echo "Analysis written to analysis.txt"
|
|
1110
|
+
```
|
|
1111
|
+
|
|
1112
|
+
### 7. Parallel Analysis with Forking
|
|
1113
|
+
|
|
1114
|
+
```bash
|
|
1115
|
+
#!/bin/bash
|
|
1116
|
+
|
|
1117
|
+
# Base analysis
|
|
1118
|
+
echo "Creating base analysis..."
|
|
1119
|
+
base_session=$(claude -p "Analyze this codebase" \
|
|
1120
|
+
--output-format json | jq -r '.session_id')
|
|
1121
|
+
|
|
1122
|
+
echo "Session: $base_session"
|
|
1123
|
+
|
|
1124
|
+
# Fork for different perspectives
|
|
1125
|
+
(
|
|
1126
|
+
echo "Security review..."
|
|
1127
|
+
claude -p "Security concerns?" \
|
|
1128
|
+
--resume "$base_session" \
|
|
1129
|
+
--fork-session > security.txt
|
|
1130
|
+
) &
|
|
1131
|
+
|
|
1132
|
+
(
|
|
1133
|
+
echo "Performance review..."
|
|
1134
|
+
claude -p "Performance issues?" \
|
|
1135
|
+
--resume "$base_session" \
|
|
1136
|
+
--fork-session > performance.txt
|
|
1137
|
+
) &
|
|
1138
|
+
|
|
1139
|
+
(
|
|
1140
|
+
echo "Maintainability review..."
|
|
1141
|
+
claude -p "Code quality and maintainability?" \
|
|
1142
|
+
--resume "$base_session" \
|
|
1143
|
+
--fork-session > maintainability.txt
|
|
1144
|
+
) &
|
|
1145
|
+
|
|
1146
|
+
# Wait for all forks
|
|
1147
|
+
wait
|
|
1148
|
+
|
|
1149
|
+
echo "All reviews complete!"
|
|
1150
|
+
cat security.txt performance.txt maintainability.txt > full-review.txt
|
|
1151
|
+
```
|
|
1152
|
+
|
|
1153
|
+
### 8. Git Commit Automation
|
|
1154
|
+
|
|
1155
|
+
```bash
|
|
1156
|
+
#!/bin/bash
|
|
1157
|
+
|
|
1158
|
+
# Review staged changes and create commit
|
|
1159
|
+
claude -p "Look at my staged changes and create an appropriate commit" \
|
|
1160
|
+
--allowed-tools "Bash(git diff:*),Bash(git log:*),Bash(git status:*),Bash(git commit:*)"
|
|
1161
|
+
```
|
|
1162
|
+
|
|
1163
|
+
### 9. Error Recovery with Retry
|
|
1164
|
+
|
|
1165
|
+
```bash
|
|
1166
|
+
#!/bin/bash
|
|
1167
|
+
|
|
1168
|
+
MAX_RETRIES=3
|
|
1169
|
+
RETRY_DELAY=60
|
|
1170
|
+
|
|
1171
|
+
analyze_with_retry() {
|
|
1172
|
+
local prompt="$1"
|
|
1173
|
+
local attempt=1
|
|
1174
|
+
|
|
1175
|
+
while [ $attempt -le $MAX_RETRIES ]; do
|
|
1176
|
+
echo "Attempt $attempt/$MAX_RETRIES..."
|
|
1177
|
+
|
|
1178
|
+
output=$(claude -p "$prompt" --output-format json 2>&1)
|
|
1179
|
+
exit_code=$?
|
|
1180
|
+
|
|
1181
|
+
if [ $exit_code -eq 0 ]; then
|
|
1182
|
+
echo "$output"
|
|
1183
|
+
return 0
|
|
1184
|
+
fi
|
|
1185
|
+
|
|
1186
|
+
if echo "$output" | grep -q "rate_limit_error"; then
|
|
1187
|
+
echo "Rate limited, waiting ${RETRY_DELAY}s..."
|
|
1188
|
+
sleep $RETRY_DELAY
|
|
1189
|
+
attempt=$((attempt + 1))
|
|
1190
|
+
else
|
|
1191
|
+
echo "Error: $output" >&2
|
|
1192
|
+
return 1
|
|
1193
|
+
fi
|
|
1194
|
+
done
|
|
1195
|
+
|
|
1196
|
+
echo "Max retries exceeded" >&2
|
|
1197
|
+
return 1
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
# Usage
|
|
1201
|
+
result=$(analyze_with_retry "Analyze this codebase")
|
|
1202
|
+
if [ $? -eq 0 ]; then
|
|
1203
|
+
echo "$result" | jq -r '.result'
|
|
1204
|
+
fi
|
|
1205
|
+
```
|
|
1206
|
+
|
|
1207
|
+
### 10. Custom System Prompt for Specialized Output
|
|
1208
|
+
|
|
1209
|
+
```bash
|
|
1210
|
+
#!/bin/bash
|
|
1211
|
+
|
|
1212
|
+
# Generate structured documentation
|
|
1213
|
+
claude -p "Document the main entry point" \
|
|
1214
|
+
--system-prompt "You are a technical documentation generator.
|
|
1215
|
+
Output only valid Markdown with the following structure:
|
|
1216
|
+
# Overview
|
|
1217
|
+
# API Reference
|
|
1218
|
+
# Examples
|
|
1219
|
+
# Error Handling" \
|
|
1220
|
+
--allowed-tools "Read,Grep" > API_DOCS.md
|
|
1221
|
+
```
|
|
1222
|
+
|
|
1223
|
+
---
|
|
1224
|
+
|
|
1225
|
+
## mdcontext Integration Recommendations
|
|
1226
|
+
|
|
1227
|
+
### Use Case: Automated LLM Summarization
|
|
1228
|
+
|
|
1229
|
+
**Goal**: Generate project summaries for large codebases programmatically
|
|
1230
|
+
|
|
1231
|
+
### Recommended Approach
|
|
1232
|
+
|
|
1233
|
+
#### 1. Read-Only Analysis (Safest)
|
|
1234
|
+
|
|
1235
|
+
```typescript
|
|
1236
|
+
import { Effect, pipe } from 'effect';
|
|
1237
|
+
import { $ } from 'effect/Function';
|
|
1238
|
+
import { spawn } from 'child_process';
|
|
1239
|
+
|
|
1240
|
+
// Wrapper for claude -p
|
|
1241
|
+
const analyzeClaude = (prompt: string, options?: {
|
|
1242
|
+
model?: string;
|
|
1243
|
+
tools?: string[];
|
|
1244
|
+
maxBudget?: number;
|
|
1245
|
+
}) => Effect.async<string, Error>((resume) => {
|
|
1246
|
+
const args = ['-p', prompt, '--output-format', 'json'];
|
|
1247
|
+
|
|
1248
|
+
if (options?.model) args.push('--model', options.model);
|
|
1249
|
+
if (options?.tools) args.push('--allowed-tools', options.tools.join(','));
|
|
1250
|
+
if (options?.maxBudget) args.push('--max-budget-usd', String(options.maxBudget));
|
|
1251
|
+
|
|
1252
|
+
const proc = spawn('claude', args, { cwd: process.cwd() });
|
|
1253
|
+
let stdout = '';
|
|
1254
|
+
let stderr = '';
|
|
1255
|
+
|
|
1256
|
+
proc.stdout.on('data', (data) => stdout += data);
|
|
1257
|
+
proc.stderr.on('data', (data) => stderr += data);
|
|
1258
|
+
|
|
1259
|
+
proc.on('close', (code) => {
|
|
1260
|
+
if (code === 0) {
|
|
1261
|
+
try {
|
|
1262
|
+
const result = JSON.parse(stdout);
|
|
1263
|
+
resume(Effect.succeed(result.result));
|
|
1264
|
+
} catch (e) {
|
|
1265
|
+
resume(Effect.fail(new Error('Failed to parse JSON: ' + e)));
|
|
1266
|
+
}
|
|
1267
|
+
} else {
|
|
1268
|
+
resume(Effect.fail(new Error(`Claude failed (${code}): ${stderr}`)));
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
});
|
|
1272
|
+
|
|
1273
|
+
// Generate summary
|
|
1274
|
+
const generateSummary = pipe(
|
|
1275
|
+
analyzeClaude(
|
|
1276
|
+
'Analyze this codebase and provide a comprehensive summary',
|
|
1277
|
+
{
|
|
1278
|
+
model: 'sonnet',
|
|
1279
|
+
tools: ['Read', 'Grep', 'Glob', 'Bash(git:*)'],
|
|
1280
|
+
maxBudget: 1.0
|
|
1281
|
+
}
|
|
1282
|
+
),
|
|
1283
|
+
Effect.tap((summary) =>
|
|
1284
|
+
Effect.log(`Generated summary (${summary.length} chars)`)
|
|
1285
|
+
)
|
|
1286
|
+
);
|
|
1287
|
+
```
|
|
1288
|
+
|
|
1289
|
+
#### 2. Structured Data Extraction
|
|
1290
|
+
|
|
1291
|
+
```typescript
|
|
1292
|
+
interface CodebaseSummary {
|
|
1293
|
+
overview: string;
|
|
1294
|
+
architecture: string[];
|
|
1295
|
+
mainComponents: Array<{
|
|
1296
|
+
name: string;
|
|
1297
|
+
purpose: string;
|
|
1298
|
+
path: string;
|
|
1299
|
+
}>;
|
|
1300
|
+
dependencies: string[];
|
|
1301
|
+
recommendations: string[];
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
const extractStructuredSummary = (cwd: string) =>
|
|
1305
|
+
Effect.async<CodebaseSummary, Error>((resume) => {
|
|
1306
|
+
const schema = JSON.stringify({
|
|
1307
|
+
type: 'object',
|
|
1308
|
+
properties: {
|
|
1309
|
+
overview: { type: 'string' },
|
|
1310
|
+
architecture: { type: 'array', items: { type: 'string' } },
|
|
1311
|
+
mainComponents: {
|
|
1312
|
+
type: 'array',
|
|
1313
|
+
items: {
|
|
1314
|
+
type: 'object',
|
|
1315
|
+
properties: {
|
|
1316
|
+
name: { type: 'string' },
|
|
1317
|
+
purpose: { type: 'string' },
|
|
1318
|
+
path: { type: 'string' }
|
|
1319
|
+
},
|
|
1320
|
+
required: ['name', 'purpose', 'path']
|
|
1321
|
+
}
|
|
1322
|
+
},
|
|
1323
|
+
dependencies: { type: 'array', items: { type: 'string' } },
|
|
1324
|
+
recommendations: { type: 'array', items: { type: 'string' } }
|
|
1325
|
+
},
|
|
1326
|
+
required: ['overview', 'architecture', 'mainComponents', 'dependencies', 'recommendations']
|
|
1327
|
+
});
|
|
1328
|
+
|
|
1329
|
+
const proc = spawn('claude', [
|
|
1330
|
+
'-p',
|
|
1331
|
+
'Analyze this codebase and extract structured information',
|
|
1332
|
+
'--output-format', 'json',
|
|
1333
|
+
'--json-schema', schema,
|
|
1334
|
+
'--allowed-tools', 'Read,Grep,Glob',
|
|
1335
|
+
'--model', 'sonnet'
|
|
1336
|
+
], { cwd });
|
|
1337
|
+
|
|
1338
|
+
let stdout = '';
|
|
1339
|
+
let stderr = '';
|
|
1340
|
+
|
|
1341
|
+
proc.stdout.on('data', (data) => stdout += data);
|
|
1342
|
+
proc.stderr.on('data', (data) => stderr += data);
|
|
1343
|
+
|
|
1344
|
+
proc.on('close', (code) => {
|
|
1345
|
+
if (code === 0) {
|
|
1346
|
+
try {
|
|
1347
|
+
const result = JSON.parse(stdout);
|
|
1348
|
+
resume(Effect.succeed(result.structured_output));
|
|
1349
|
+
} catch (e) {
|
|
1350
|
+
resume(Effect.fail(new Error('Failed to parse: ' + e)));
|
|
1351
|
+
}
|
|
1352
|
+
} else {
|
|
1353
|
+
resume(Effect.fail(new Error(`Failed (${code}): ${stderr}`)));
|
|
1354
|
+
}
|
|
1355
|
+
});
|
|
1356
|
+
});
|
|
1357
|
+
```
|
|
1358
|
+
|
|
1359
|
+
#### 3. Cost-Aware Batch Processing
|
|
1360
|
+
|
|
1361
|
+
```typescript
|
|
1362
|
+
interface AnalysisResult {
|
|
1363
|
+
file: string;
|
|
1364
|
+
summary: string;
|
|
1365
|
+
cost: number;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
const analyzeFilesWithBudget = (
|
|
1369
|
+
files: string[],
|
|
1370
|
+
totalBudget: number
|
|
1371
|
+
) => Effect.gen(function* (_) {
|
|
1372
|
+
let remainingBudget = totalBudget;
|
|
1373
|
+
const results: AnalysisResult[] = [];
|
|
1374
|
+
|
|
1375
|
+
for (const file of files) {
|
|
1376
|
+
if (remainingBudget <= 0) {
|
|
1377
|
+
yield* _(Effect.log('Budget exhausted'));
|
|
1378
|
+
break;
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
const perFileBudget = Math.min(0.50, remainingBudget);
|
|
1382
|
+
|
|
1383
|
+
const result = yield* _(
|
|
1384
|
+
analyzeClaude(
|
|
1385
|
+
`Summarize this file:\n\n${yield* _(readFile(file))}`,
|
|
1386
|
+
{
|
|
1387
|
+
model: 'sonnet',
|
|
1388
|
+
maxBudget: perFileBudget,
|
|
1389
|
+
tools: []
|
|
1390
|
+
}
|
|
1391
|
+
).pipe(
|
|
1392
|
+
Effect.map((summary) => {
|
|
1393
|
+
// Parse cost from JSON
|
|
1394
|
+
return { file, summary, cost: 0.05 }; // Simplified
|
|
1395
|
+
})
|
|
1396
|
+
)
|
|
1397
|
+
);
|
|
1398
|
+
|
|
1399
|
+
results.push(result);
|
|
1400
|
+
remainingBudget -= result.cost;
|
|
1401
|
+
|
|
1402
|
+
yield* _(Effect.log(`Processed ${file} (cost: $${result.cost}, remaining: $${remainingBudget})`));
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
return results;
|
|
1406
|
+
});
|
|
1407
|
+
```
|
|
1408
|
+
|
|
1409
|
+
#### 4. Integration with mdcontext CLI
|
|
1410
|
+
|
|
1411
|
+
Add new command:
|
|
1412
|
+
|
|
1413
|
+
```typescript
|
|
1414
|
+
// src/cli/commands/summarize.ts
|
|
1415
|
+
|
|
1416
|
+
import { Command } from '@effect/cli';
|
|
1417
|
+
import { Effect } from 'effect';
|
|
1418
|
+
|
|
1419
|
+
const summarizeCommand = Command.make('summarize', {
|
|
1420
|
+
provider: Options.choice('provider', ['anthropic-api', 'claude-cli']).pipe(
|
|
1421
|
+
Options.withDefault('claude-cli')
|
|
1422
|
+
),
|
|
1423
|
+
model: Options.choice('model', ['sonnet', 'opus']).pipe(
|
|
1424
|
+
Options.withDefault('sonnet')
|
|
1425
|
+
),
|
|
1426
|
+
budget: Options.float('budget').pipe(
|
|
1427
|
+
Options.withDefault(1.0)
|
|
1428
|
+
),
|
|
1429
|
+
output: Options.text('output').pipe(
|
|
1430
|
+
Options.optional
|
|
1431
|
+
)
|
|
1432
|
+
}).pipe(
|
|
1433
|
+
Command.withHandler((args) =>
|
|
1434
|
+
Effect.gen(function* (_) {
|
|
1435
|
+
if (args.provider === 'claude-cli') {
|
|
1436
|
+
// Use claude -p integration
|
|
1437
|
+
const summary = yield* _(
|
|
1438
|
+
analyzeClaude('Generate project summary', {
|
|
1439
|
+
model: args.model,
|
|
1440
|
+
maxBudget: args.budget,
|
|
1441
|
+
tools: ['Read', 'Grep', 'Glob']
|
|
1442
|
+
})
|
|
1443
|
+
);
|
|
1444
|
+
|
|
1445
|
+
if (args.output) {
|
|
1446
|
+
yield* _(writeFile(args.output, summary));
|
|
1447
|
+
yield* _(Effect.log(`Summary written to ${args.output}`));
|
|
1448
|
+
} else {
|
|
1449
|
+
yield* _(Console.log(summary));
|
|
1450
|
+
}
|
|
1451
|
+
} else {
|
|
1452
|
+
// Use direct API integration
|
|
1453
|
+
// ...
|
|
1454
|
+
}
|
|
1455
|
+
})
|
|
1456
|
+
)
|
|
1457
|
+
);
|
|
1458
|
+
|
|
1459
|
+
// mdcontext summarize --provider claude-cli --model sonnet --budget 1.0 --output SUMMARY.md
|
|
1460
|
+
```
|
|
1461
|
+
|
|
1462
|
+
### Key Integration Points
|
|
1463
|
+
|
|
1464
|
+
1. **Provider abstraction**: Support both direct API and CLI
|
|
1465
|
+
2. **Cost tracking**: Monitor and report costs
|
|
1466
|
+
3. **Error handling**: Graceful degradation, retries
|
|
1467
|
+
4. **Structured output**: Use JSON schema for consistency
|
|
1468
|
+
5. **Session management**: Multi-step analysis
|
|
1469
|
+
6. **Tool safety**: Read-only by default
|
|
1470
|
+
|
|
1471
|
+
### Configuration Options
|
|
1472
|
+
|
|
1473
|
+
```json
|
|
1474
|
+
// .mdcontext/config.json
|
|
1475
|
+
{
|
|
1476
|
+
"summarization": {
|
|
1477
|
+
"provider": "claude-cli",
|
|
1478
|
+
"model": "sonnet",
|
|
1479
|
+
"fallbackModel": "opus",
|
|
1480
|
+
"maxBudget": 5.0,
|
|
1481
|
+
"allowedTools": ["Read", "Grep", "Glob", "Bash(git:*)"],
|
|
1482
|
+
"sessionPersistence": true,
|
|
1483
|
+
"outputFormat": "json"
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
```
|
|
1487
|
+
|
|
1488
|
+
---
|
|
1489
|
+
|
|
1490
|
+
## Gotchas & Limitations
|
|
1491
|
+
|
|
1492
|
+
### 1. No Interactive Prompts in -p Mode
|
|
1493
|
+
|
|
1494
|
+
Skills and built-in commands like `/commit` are **not available** in `-p` mode:
|
|
1495
|
+
|
|
1496
|
+
```bash
|
|
1497
|
+
# Won't work
|
|
1498
|
+
claude -p "/commit"
|
|
1499
|
+
|
|
1500
|
+
# Instead, describe the task
|
|
1501
|
+
claude -p "Look at my staged changes and create an appropriate commit" \
|
|
1502
|
+
--allowed-tools "Bash(git:*)"
|
|
1503
|
+
```
|
|
1504
|
+
|
|
1505
|
+
### 2. Tool Permissions Must Be Pre-Approved
|
|
1506
|
+
|
|
1507
|
+
Can't prompt for approval in non-interactive mode:
|
|
1508
|
+
|
|
1509
|
+
```bash
|
|
1510
|
+
# Will fail if tools not allowed
|
|
1511
|
+
claude -p "Fix all bugs" # Tries to use Edit tool but can't ask
|
|
1512
|
+
|
|
1513
|
+
# Must pre-approve
|
|
1514
|
+
claude -p "Fix all bugs" --allowed-tools "Read,Edit,Bash"
|
|
1515
|
+
```
|
|
1516
|
+
|
|
1517
|
+
### 3. Trust Dialog Bypassed
|
|
1518
|
+
|
|
1519
|
+
`-p` flag **skips workspace trust dialog** - only use in trusted directories:
|
|
1520
|
+
|
|
1521
|
+
```bash
|
|
1522
|
+
# Dangerous in untrusted directory
|
|
1523
|
+
cd /tmp/sketchy-repo
|
|
1524
|
+
claude -p "Analyze this" --allowed-tools "Bash" # Could run malicious code
|
|
1525
|
+
```
|
|
1526
|
+
|
|
1527
|
+
### 4. Stream-JSON Requires --verbose
|
|
1528
|
+
|
|
1529
|
+
```bash
|
|
1530
|
+
# Won't work
|
|
1531
|
+
claude -p "test" --output-format stream-json
|
|
1532
|
+
|
|
1533
|
+
# Error: When using --print, --output-format=stream-json requires --verbose
|
|
1534
|
+
|
|
1535
|
+
# Correct
|
|
1536
|
+
claude -p "test" --output-format stream-json --verbose
|
|
1537
|
+
```
|
|
1538
|
+
|
|
1539
|
+
### 5. JSON Schema Only in Final Result
|
|
1540
|
+
|
|
1541
|
+
When streaming with `--json-schema`, structured output only appears at the end:
|
|
1542
|
+
|
|
1543
|
+
```bash
|
|
1544
|
+
claude -p "Extract data" \
|
|
1545
|
+
--output-format stream-json \
|
|
1546
|
+
--json-schema '...' \
|
|
1547
|
+
--verbose
|
|
1548
|
+
# Streams text, structured_output only in final event
|
|
1549
|
+
```
|
|
1550
|
+
|
|
1551
|
+
### 6. Session Persistence Default
|
|
1552
|
+
|
|
1553
|
+
Sessions are saved by default, consuming disk space:
|
|
1554
|
+
|
|
1555
|
+
```bash
|
|
1556
|
+
# Sessions accumulate
|
|
1557
|
+
claude -p "test1"
|
|
1558
|
+
claude -p "test2"
|
|
1559
|
+
claude -p "test3"
|
|
1560
|
+
# All saved to ~/.claude/sessions/
|
|
1561
|
+
|
|
1562
|
+
# Disable for stateless operation
|
|
1563
|
+
claude -p "test" --no-session-persistence
|
|
1564
|
+
```
|
|
1565
|
+
|
|
1566
|
+
### 7. Organization-Wide Rate Limits
|
|
1567
|
+
|
|
1568
|
+
Rate limits are **shared across all API keys** in your organization:
|
|
1569
|
+
|
|
1570
|
+
```bash
|
|
1571
|
+
# Multiple processes hitting same limit
|
|
1572
|
+
for i in {1..100}; do
|
|
1573
|
+
claude -p "test $i" & # All share same rate limit pool
|
|
1574
|
+
done
|
|
1575
|
+
# Will quickly hit rate limit
|
|
1576
|
+
```
|
|
1577
|
+
|
|
1578
|
+
### 8. API Key Priority Over Subscription
|
|
1579
|
+
|
|
1580
|
+
If `ANTHROPIC_API_KEY` is set, it **takes priority** and you'll be charged API rates:
|
|
1581
|
+
|
|
1582
|
+
```bash
|
|
1583
|
+
export ANTHROPIC_API_KEY="sk-ant-..."
|
|
1584
|
+
claude -p "test" # Uses API key, not subscription - charged per token!
|
|
1585
|
+
```
|
|
1586
|
+
|
|
1587
|
+
### 9. Model Selection Doesn't Affect Cost in JSON
|
|
1588
|
+
|
|
1589
|
+
JSON output shows actual model used and cost, which may differ from requested:
|
|
1590
|
+
|
|
1591
|
+
```bash
|
|
1592
|
+
# Request sonnet
|
|
1593
|
+
claude -p "test" --model sonnet --output-format json
|
|
1594
|
+
|
|
1595
|
+
# But modelUsage may show different model if fallback triggered
|
|
1596
|
+
{
|
|
1597
|
+
"modelUsage": {
|
|
1598
|
+
"claude-opus-4-5-20251101": { // Fallback was used
|
|
1599
|
+
"costUSD": 0.12 // Higher than expected
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
```
|
|
1604
|
+
|
|
1605
|
+
### 10. Timeout Behavior
|
|
1606
|
+
|
|
1607
|
+
No built-in timeout - use external `timeout` command:
|
|
1608
|
+
|
|
1609
|
+
```bash
|
|
1610
|
+
# Will run indefinitely
|
|
1611
|
+
claude -p "Analyze everything forever"
|
|
1612
|
+
|
|
1613
|
+
# Add timeout
|
|
1614
|
+
timeout 300 claude -p "Long task" # 5 minute timeout
|
|
1615
|
+
# Exit code 124 on timeout
|
|
1616
|
+
```
|
|
1617
|
+
|
|
1618
|
+
### 11. No Progress for Long Operations
|
|
1619
|
+
|
|
1620
|
+
With default text/json output, no feedback during long operations:
|
|
1621
|
+
|
|
1622
|
+
```bash
|
|
1623
|
+
# Appears frozen
|
|
1624
|
+
claude -p "Analyze 10000 files" # No output until complete
|
|
1625
|
+
|
|
1626
|
+
# Use streaming for feedback
|
|
1627
|
+
claude -p "Analyze 10000 files" --output-format stream-json --verbose
|
|
1628
|
+
```
|
|
1629
|
+
|
|
1630
|
+
### 12. Input Format Limitations
|
|
1631
|
+
|
|
1632
|
+
`--input-format stream-json` has limited documentation and complex requirements:
|
|
1633
|
+
|
|
1634
|
+
```bash
|
|
1635
|
+
# Requires specific JSON format per line
|
|
1636
|
+
echo '{"type":"user","content":"Hello"}' | \
|
|
1637
|
+
claude -p --input-format stream-json --output-format stream-json --verbose
|
|
1638
|
+
# Often fails with parsing errors
|
|
1639
|
+
```
|
|
1640
|
+
|
|
1641
|
+
Stick to text input for reliability.
|
|
1642
|
+
|
|
1643
|
+
### 13. Context Window Exceeds Silently
|
|
1644
|
+
|
|
1645
|
+
If context exceeds window, request may fail without clear error:
|
|
1646
|
+
|
|
1647
|
+
```bash
|
|
1648
|
+
# Large file
|
|
1649
|
+
cat 500MB.log | claude -p "Analyze"
|
|
1650
|
+
# May fail with generic error, not "context too large"
|
|
1651
|
+
```
|
|
1652
|
+
|
|
1653
|
+
Monitor `input_tokens` in JSON output to track usage.
|
|
1654
|
+
|
|
1655
|
+
### 14. No Streaming Text Output
|
|
1656
|
+
|
|
1657
|
+
Can't stream plain text - must use stream-json:
|
|
1658
|
+
|
|
1659
|
+
```bash
|
|
1660
|
+
# No streaming equivalent for text format
|
|
1661
|
+
claude -p "Long task" --output-format text # Blocks until complete
|
|
1662
|
+
```
|
|
1663
|
+
|
|
1664
|
+
### 15. MCP Servers May Require Configuration
|
|
1665
|
+
|
|
1666
|
+
If using MCP tools, they must be configured beforehand:
|
|
1667
|
+
|
|
1668
|
+
```bash
|
|
1669
|
+
# Won't work if Linear not configured
|
|
1670
|
+
claude -p "Create Linear issue" --allowed-tools "mcp__linear-server__create_issue"
|
|
1671
|
+
|
|
1672
|
+
# Must configure first via interactive mode or --mcp-config
|
|
1673
|
+
```
|
|
1674
|
+
|
|
1675
|
+
---
|
|
1676
|
+
|
|
1677
|
+
## References & Sources
|
|
1678
|
+
|
|
1679
|
+
### Official Documentation
|
|
1680
|
+
- [Run Claude Code programmatically - Claude Code Docs](https://code.claude.com/docs/en/headless)
|
|
1681
|
+
- [Claude API Rate Limits](https://platform.claude.com/docs/en/api/rate-limits)
|
|
1682
|
+
- [Structured outputs - Claude API Docs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
|
|
1683
|
+
- [Streaming Messages - Claude API Docs](https://platform.claude.com/docs/en/build-with-claude/streaming)
|
|
1684
|
+
|
|
1685
|
+
### Community Resources
|
|
1686
|
+
- [GitHub - disler/claude-code-is-programmable](https://github.com/disler/claude-code-is-programmable)
|
|
1687
|
+
- [What is the --print Flag in Claude Code | ClaudeLog](https://claudelog.com/faqs/what-is-print-flag-in-claude-code/)
|
|
1688
|
+
- [Managing API Key Environment Variables in Claude Code | Claude Help Center](https://support.claude.com/en/articles/12304248-managing-api-key-environment-variables-in-claude-code)
|
|
1689
|
+
- [Stream-JSON Chaining - ruvnet/claude-flow Wiki](https://github.com/ruvnet/claude-flow/wiki/Stream-Chaining)
|
|
1690
|
+
|
|
1691
|
+
### Error Handling & Troubleshooting
|
|
1692
|
+
- [Troubleshooting - Claude Code Docs](https://code.claude.com/docs/en/troubleshooting)
|
|
1693
|
+
- [How to Fix Claude Code Process Exited With Code 1?](https://www.navthemes.com/how-to-fix-claude-code-process-exited-with-code-1/)
|
|
1694
|
+
- [Rate limits - Claude API Docs](https://platform.claude.com/docs/en/api/rate-limits)
|
|
1695
|
+
|
|
1696
|
+
---
|
|
1697
|
+
|
|
1698
|
+
## Changelog
|
|
1699
|
+
|
|
1700
|
+
- **2026-01-26**: Initial comprehensive guide for Claude Code CLI 2.1.19
|
|
1701
|
+
- Documented all -p flag options and behaviors
|
|
1702
|
+
- Tested output formats (text, json, stream-json)
|
|
1703
|
+
- Verified error handling and exit codes
|
|
1704
|
+
- Researched authentication, rate limiting, and session management
|
|
1705
|
+
- Created practical examples for mdcontext integration
|
|
1706
|
+
- Cataloged gotchas and limitations
|