@lornatang/dsh-caveman 0.1.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 (112) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/NOTICE +51 -0
  5. package/README.md +218 -0
  6. package/README.zh.md +218 -0
  7. package/cordis.patch.yml +3 -0
  8. package/examples/caveman-anthropic.patch.yml +14 -0
  9. package/examples/caveman-auto.patch.yml +15 -0
  10. package/lib/attribution.js +24 -0
  11. package/lib/blocks.js +80 -0
  12. package/lib/cavecrew-git.js +83 -0
  13. package/lib/cavecrew.js +67 -0
  14. package/lib/compression.js +434 -0
  15. package/lib/index.js +127 -0
  16. package/lib/memory.js +35 -0
  17. package/lib/mode.js +71 -0
  18. package/lib/native.js +357 -0
  19. package/lib/runtime.js +199 -0
  20. package/lib/skills.js +75 -0
  21. package/lib/stats.js +189 -0
  22. package/lib/types/attribution.d.ts +8 -0
  23. package/lib/types/blocks.d.ts +12 -0
  24. package/lib/types/cavecrew-git.d.ts +5 -0
  25. package/lib/types/cavecrew.d.ts +10 -0
  26. package/lib/types/compression.d.ts +50 -0
  27. package/lib/types/index.d.ts +30 -0
  28. package/lib/types/memory.d.ts +3 -0
  29. package/lib/types/mode.d.ts +33 -0
  30. package/lib/types/native.d.ts +43 -0
  31. package/lib/types/runtime.d.ts +23 -0
  32. package/lib/types/skills.d.ts +3 -0
  33. package/lib/types/stats.d.ts +6 -0
  34. package/package.json +129 -0
  35. package/presets/cavecrew.patch.yml +54 -0
  36. package/scripts/benchmark.mjs +79 -0
  37. package/scripts/caveman-cli.mjs +30 -0
  38. package/scripts/learn-binary.mjs +82 -0
  39. package/scripts/learn-checksums.json +29 -0
  40. package/vendor/caveman/LICENSE +202 -0
  41. package/vendor/caveman/LICENSE-MIT +21 -0
  42. package/vendor/caveman/NOTICE +49 -0
  43. package/vendor/caveman/agents/cavecrew-builder.md +46 -0
  44. package/vendor/caveman/agents/cavecrew-investigator.md +56 -0
  45. package/vendor/caveman/agents/cavecrew-reviewer.md +47 -0
  46. package/vendor/caveman/skills/activation-rule.mjs +43 -0
  47. package/vendor/caveman/skills/cavecrew/README.md +67 -0
  48. package/vendor/caveman/skills/cavecrew/SKILL.md +78 -0
  49. package/vendor/caveman/skills/caveman/README.md +68 -0
  50. package/vendor/caveman/skills/caveman/SKILL.md +89 -0
  51. package/vendor/caveman/skills/caveman-commit/README.md +44 -0
  52. package/vendor/caveman/skills/caveman-commit/SKILL.md +63 -0
  53. package/vendor/caveman/skills/caveman-compress/README.md +262 -0
  54. package/vendor/caveman/skills/caveman-compress/SECURITY.md +55 -0
  55. package/vendor/caveman/skills/caveman-compress/SKILL.md +114 -0
  56. package/vendor/caveman/skills/caveman-compress/scripts/__init__.py +9 -0
  57. package/vendor/caveman/skills/caveman-compress/scripts/__main__.py +3 -0
  58. package/vendor/caveman/skills/caveman-compress/scripts/benchmark.py +80 -0
  59. package/vendor/caveman/skills/caveman-compress/scripts/cli.py +94 -0
  60. package/vendor/caveman/skills/caveman-compress/scripts/compress.py +1331 -0
  61. package/vendor/caveman/skills/caveman-compress/scripts/detect.py +192 -0
  62. package/vendor/caveman/skills/caveman-compress/scripts/validate.py +440 -0
  63. package/vendor/caveman/skills/caveman-discover/SKILL.md +115 -0
  64. package/vendor/caveman/skills/caveman-evidence-review/SKILL.md +142 -0
  65. package/vendor/caveman/skills/caveman-explore/SKILL.md +42 -0
  66. package/vendor/caveman/skills/caveman-explore/package.json +12 -0
  67. package/vendor/caveman/skills/caveman-explore/tests/skill-file.test.mjs +44 -0
  68. package/vendor/caveman/skills/caveman-help/README.md +39 -0
  69. package/vendor/caveman/skills/caveman-help/SKILL.md +62 -0
  70. package/vendor/caveman/skills/caveman-learn/CLAUDE.md +32 -0
  71. package/vendor/caveman/skills/caveman-learn/README.md +38 -0
  72. package/vendor/caveman/skills/caveman-learn/SKILL.md +185 -0
  73. package/vendor/caveman/skills/caveman-learn/package.json +12 -0
  74. package/vendor/caveman/skills/caveman-learn/tests/index.js +1 -0
  75. package/vendor/caveman/skills/caveman-learn/tests/skill-file.test.mjs +54 -0
  76. package/vendor/caveman/skills/caveman-manage/SKILL.md +112 -0
  77. package/vendor/caveman/skills/caveman-optimize/SKILL.md +111 -0
  78. package/vendor/caveman/skills/caveman-review/README.md +33 -0
  79. package/vendor/caveman/skills/caveman-review/SKILL.md +53 -0
  80. package/vendor/caveman/skills/caveman-setup/SKILL.md +222 -0
  81. package/vendor/caveman/skills/caveman-stats/README.md +48 -0
  82. package/vendor/caveman/skills/caveman-stats/SKILL.md +17 -0
  83. package/vendor/caveman/skills/compile.mjs +298 -0
  84. package/vendor/caveman/skills/engine-mcp-tools.json +10 -0
  85. package/vendor/caveman/skills/generated/aider/pack.json +163 -0
  86. package/vendor/caveman/skills/generated/claude/pack.json +163 -0
  87. package/vendor/caveman/skills/generated/codex/pack.json +163 -0
  88. package/vendor/caveman/skills/generated/gemini/pack.json +163 -0
  89. package/vendor/caveman/skills/generated/hermes/pack.json +163 -0
  90. package/vendor/caveman/skills/generated/opencode/pack.json +163 -0
  91. package/vendor/caveman/skills/investigate-first/SKILL.md +16 -0
  92. package/vendor/caveman/skills/investigate-first/agents/openai.yaml +4 -0
  93. package/vendor/caveman/skills/lean-build/SKILL.md +18 -0
  94. package/vendor/caveman/skills/lean-build/agents/openai.yaml +4 -0
  95. package/vendor/caveman/skills/megacave/README.md +11 -0
  96. package/vendor/caveman/skills/megacave/SKILL.md +65 -0
  97. package/vendor/caveman/skills/migration/SKILL.md +17 -0
  98. package/vendor/caveman/skills/migration/agents/openai.yaml +4 -0
  99. package/vendor/caveman/skills/native/native-core.md +16 -0
  100. package/vendor/caveman/skills/registry.json +283 -0
  101. package/vendor/caveman/skills/safe-refactor/SKILL.md +16 -0
  102. package/vendor/caveman/skills/safe-refactor/agents/openai.yaml +4 -0
  103. package/vendor/caveman/skills/surgical-patch/SKILL.md +16 -0
  104. package/vendor/caveman/skills/surgical-patch/agents/openai.yaml +4 -0
  105. package/vendor/caveman/skills/ultracave/README.md +13 -0
  106. package/vendor/caveman/skills/ultracave/SKILL.md +63 -0
  107. package/vendor/caveman/skills/verbs-gate.mjs +213 -0
  108. package/vendor/caveman/skills/verify-and-stop/SKILL.md +16 -0
  109. package/vendor/caveman/skills/verify-and-stop/agents/openai.yaml +4 -0
  110. package/vendor/caveman/src/hooks/caveman-config.js +921 -0
  111. package/vendor/caveman/src/hooks/caveman-parse.js +342 -0
  112. package/vendor/caveman/src/hooks/package.json +3 -0
@@ -0,0 +1,222 @@
1
+ ---
2
+ name: caveman-setup
3
+ description: >
4
+ Wire a repository through the Caveman Cloud gateway so every LLM request is
5
+ measured, with no behavior change. Use for "set up caveman" or adding LLM
6
+ spend observability.
7
+ ---
8
+
9
+ You are wiring this repository through the Caveman gateway. Caveman is a
10
+ byte-preserving LLM proxy: in record mode it measures what your app sends and
11
+ what it costs, and changes nothing else. Your job is a minimal, verified
12
+ integration — not a refactor.
13
+
14
+ The prompt that sent you here provides four values. Refer to them as:
15
+
16
+ - `GATEWAY` — the gateway base URL (e.g. `https://gateway.caveman.so` or `http://127.0.0.1:8787`)
17
+ - `CAVE_API_KEY` — the gateway auth secret (treat like any API key: env var only, never committed, never printed in full)
18
+ - `PROVIDER_KEYS` — `stored` (provider keys live encrypted in Caveman Cloud) or `byok` (this app sends its own provider key per request)
19
+ - `DASHBOARD` — the dashboard base URL (e.g. `https://app.caveman.so`)
20
+
21
+ If any value is missing, stop and ask for it. Do not guess a URL or mint a key.
22
+
23
+ ## Rules (non-negotiable)
24
+
25
+ 1. **Coherent integration.** Wire every live LLM callsite through existing
26
+ configuration and responsible seams. Touch each layer correctness requires.
27
+ No drive-by refactors or formatting sweeps; add an abstraction only when it
28
+ clarifies ownership or lowers lifecycle cost.
29
+ 2. **Secrets stay in env vars.** `CAVE_API_KEY` goes into the env file the repo
30
+ already uses (`.env`, `.env.local`, …). If that file isn't gitignored, add it
31
+ to `.gitignore` and say so. Never hardcode the key in source.
32
+ 3. **Report only what you observed.** The final report states the HTTP status
33
+ and usage numbers from the real verification response — never assumed
34
+ success. If verification fails, report the failure template instead.
35
+ 4. **Record mode only.** You are adding measurement. You do not enable any
36
+ optimization, and you do not claim any savings — verified savings are $0
37
+ until an optimizer is explicitly turned on and passes its eval gate.
38
+ 5. **Provider keys are not your business.** With `PROVIDER_KEYS: stored` you
39
+ never see one. With `byok`, the app's existing provider key stays exactly
40
+ where it already is.
41
+
42
+ ## Step 1 — Find every live LLM callsite
43
+
44
+ Read dependency files (`package.json`, `requirements.txt`, `pyproject.toml`,
45
+ `go.mod`, lockfiles) and search the source for LLM clients:
46
+
47
+ - SDK imports: `openai`, `@anthropic-ai/sdk`, `anthropic`, `ai` +
48
+ `@ai-sdk/*` (Vercel), `langchain*`, `litellm`, `google-genai` /
49
+ `@google/genai`, `crewai`, `pydantic_ai`, `openai-agents` / `agents`
50
+ - Raw HTTP to `api.openai.com`, `api.anthropic.com`, `generativelanguage.googleapis.com`
51
+ - Existing base-URL env vars: `OPENAI_BASE_URL`, `OPENAI_API_BASE`,
52
+ `ANTHROPIC_BASE_URL`, `GEMINI_BASE_URL`, `GOOGLE_GEMINI_BASE_URL`
53
+
54
+ List what you found (file:line per callsite) before changing anything. If you
55
+ find **no** LLM callsites, stop and report the "nothing to wire" template at
56
+ the end of this file — do not invent an integration.
57
+
58
+ ## Step 2 — Pick the app slug
59
+
60
+ One slug names this app in the gateway path: `GATEWAY/w/<app>`. Derive it from
61
+ the package/module name (e.g. `support-bot`, `acme-api`). Grammar:
62
+ lowercase `[a-z0-9]` first, then `[a-z0-9._-]`, max 64 chars. Spend for this
63
+ whole app groups under that slug on the dashboard.
64
+
65
+ ## Step 3 — Wire each callsite
66
+
67
+ The pattern is always the same: **base URL → the gateway with `/w/<app>`,
68
+ plus one auth header.** Gateway auth is `x-cave-api-key: CAVE_API_KEY`
69
+ (`Authorization: Bearer CAVE_API_KEY` also works where a header is awkward).
70
+ With `PROVIDER_KEYS: byok`, also send `x-cave-upstream-key: <the provider key
71
+ the app already uses>`.
72
+
73
+ Two facts that make the wiring safe (both are gateway-enforced, not hopes):
74
+ the gateway rebuilds upstream auth headers from scratch, so a client's
75
+ `Authorization`/`x-api-key` value is never forwarded to the provider; and with
76
+ `stored`, upstream auth comes from the encrypted connection server-side. So in
77
+ `stored` mode, where an SDK insists on an api-key parameter, set it to the
78
+ Cave key — it authenticates the gateway and goes no further.
79
+
80
+ Exact shapes (use the one matching each callsite — these are the product's
81
+ published recipes, not suggestions):
82
+
83
+ **OpenAI SDK (TS)** — Chat Completions and Responses both route through:
84
+ ```ts
85
+ const client = new OpenAI({
86
+ baseURL: `${process.env.CAVE_GATEWAY_URL}/w/<app>/openai/v1`,
87
+ apiKey: process.env.OPENAI_API_KEY, // byok: unchanged · stored: use CAVE_API_KEY
88
+ defaultHeaders: {
89
+ "x-cave-api-key": process.env.CAVE_API_KEY!,
90
+ // byok only:
91
+ "x-cave-upstream-key": process.env.OPENAI_API_KEY!,
92
+ },
93
+ });
94
+ ```
95
+
96
+ **OpenAI SDK (Python)** — same shape: `base_url=f"{gw}/w/<app>/openai/v1"`,
97
+ `default_headers={"x-cave-api-key": ..., "x-cave-upstream-key": ...}`.
98
+
99
+ **Anthropic SDK (TS/Python)** — the SDK appends `/v1/messages` itself. The
100
+ `x-cave-api-key` header is required here in both modes (this SDK's own key
101
+ param rides `x-api-key`, which is not a gateway-auth header):
102
+ ```python
103
+ client = anthropic.Anthropic(
104
+ base_url=f"{os.environ['CAVE_GATEWAY_URL']}/w/<app>",
105
+ api_key=os.environ["ANTHROPIC_API_KEY"], # byok: unchanged · stored: use CAVE_API_KEY
106
+ default_headers={
107
+ "x-cave-api-key": os.environ["CAVE_API_KEY"],
108
+ # byok only:
109
+ "x-cave-upstream-key": os.environ["ANTHROPIC_API_KEY"],
110
+ },
111
+ )
112
+ ```
113
+
114
+ **Vercel AI SDK** — `createOpenAICompatible({ baseURL: `${gw}/w/<app>/openai/v1`,
115
+ headers: { "x-cave-api-key": ... } })`; Anthropic models via
116
+ `createAnthropic({ baseURL: `${gw}/w/<app>/v1`, headers: { ... } })`.
117
+
118
+ **LangChain / LangGraph** — `ChatOpenAI(base_url=f"{gw}/w/<app>/openai/v1",
119
+ default_headers={...})`; `ChatAnthropic(base_url=f"{gw}/w/<app>",
120
+ default_headers={...})`. LangGraph inherits whatever model you pass it.
121
+
122
+ **LiteLLM** — per call `api_base=f"{gw}/w/<app>/openai/v1"` +
123
+ `extra_headers={...}`, or fleet-wide in the LiteLLM proxy `config.yaml`.
124
+
125
+ **Raw HTTP / anything else** — swap the host, keep the provider's native path:
126
+ `GATEWAY/w/<app>/v1/chat/completions` (OpenAI protocol) or
127
+ `GATEWAY/w/<app>/v1/messages` (Anthropic protocol), add the header(s).
128
+
129
+ Concretely, with slug `support-bot` and the hosted gateway, an OpenAI-SDK base
130
+ URL reads `https://gateway.caveman.so/w/support-bot/openai/v1`. And in `stored`
131
+ mode, drop every `x-cave-upstream-key` line entirely — it is byok-only.
132
+
133
+ For frameworks not listed (google-genai, crewai, pydantic-ai, openai-agents),
134
+ fetch the matching page under `<docs origin>/docs/integrations/` — same origin
135
+ this skill came from — and follow it.
136
+
137
+ Add to the repo's env file (and reference from code — no literals):
138
+
139
+ ```
140
+ CAVE_GATEWAY_URL=<GATEWAY>
141
+ CAVE_API_KEY=<CAVE_API_KEY>
142
+ ```
143
+
144
+ ## Step 4 — Verify with one real request
145
+
146
+ The user pasted the setup prompt to authorize exactly this: one small
147
+ verification request. Send it now — do not pause to ask permission for it.
148
+ An integration that ends unverified because you hesitated is a worse outcome
149
+ than one tiny request; finishing the verification and the report autonomously
150
+ is the point of this skill.
151
+
152
+ Send one minimal request through the wiring you just built — the app's own
153
+ cheapest path if it has a script for it, otherwise curl **on the path matching
154
+ the protocol you just wired** with the app's own model and a small cap
155
+ (`max_tokens` ≤ 32):
156
+
157
+ ```bash
158
+ # OpenAI-protocol wiring:
159
+ curl -sS "$CAVE_GATEWAY_URL/w/<app>/v1/chat/completions" \
160
+ -H "x-cave-api-key: $CAVE_API_KEY" \
161
+ -H "content-type: application/json" \
162
+ -d '{"model":"<model the repo already uses>","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}'
163
+
164
+ # Anthropic-protocol wiring:
165
+ curl -sS "$CAVE_GATEWAY_URL/w/<app>/v1/messages" \
166
+ -H "x-cave-api-key: $CAVE_API_KEY" \
167
+ -H "anthropic-version: 2023-06-01" \
168
+ -H "content-type: application/json" \
169
+ -d '{"model":"<model the repo already uses>","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}'
170
+ ```
171
+
172
+ (byok: add `-H "x-cave-upstream-key: $PROVIDER_KEY"`.) This is one real,
173
+ billable provider request — that is the point: real traffic, real measurement.
174
+
175
+ Read the response. Success = HTTP 200 with a `usage` block. Anything else =
176
+ the matching failure template below.
177
+
178
+ ## Step 5 — Report
179
+
180
+ End with exactly this shape, values filled from what you actually did and saw:
181
+
182
+ ```
183
+ ## Caveman is live in this repo
184
+
185
+ Wired: <n> callsite(s) in <n> file(s)
186
+ - <file> — <one-line what changed>
187
+ App slug: <app> — spend for this app groups under it
188
+ Verified: HTTP 200 · model <model> · <in> in / <out> out tokens (one real request)
189
+ Mode: record — measured only. No model-visible bytes changed, no optimization
190
+ enabled. Verified savings are $0 until you turn an optimizer on and it passes
191
+ its eval gate. That honesty is the product.
192
+
193
+ See the dollars: <DASHBOARD>/traces — your request is the top row, priced from
194
+ the public catalog. <DASHBOARD>/getting-started flips to "First request received."
195
+
196
+ Want spend split by workflow (e.g. support-reply vs nightly-digest), not just
197
+ by app? Say "discover workflows" — I'll fetch <docs origin>/docs/discover-workflows.md
198
+ and label every callsite by the job it does.
199
+ ```
200
+
201
+ ## Failure templates (use verbatim, filled in — never soften)
202
+
203
+ - **Nothing to wire**: "I found no LLM callsites in this repo (searched SDKs,
204
+ raw provider HTTP, base-URL env vars). If this repo runs a coding agent
205
+ rather than shipping LLM code, use `caveman wrap <agent>` instead — see
206
+ <DASHBOARD>/getting-started."
207
+ - **Gateway unreachable**: "The verification request could not reach GATEWAY
208
+ (<error>). Wiring is in place but unverified — nothing will be measured
209
+ until the gateway is reachable. Check the URL and network, then re-run the
210
+ verification curl above."
211
+ - **401 cave_invalid_api_key**: "The gateway rejected CAVE_API_KEY. Mint a new
212
+ key at <DASHBOARD>/getting-started and update the env file; the wiring
213
+ itself is unchanged."
214
+ - **404 cave_route_not_found**: "The gateway matched no route — usually a
215
+ malformed /w/<app> slug (lowercase [a-z0-9] first, then [a-z0-9._-], max 64)
216
+ or a path that doesn't match the SDK's protocol. Fix the URL and re-verify."
217
+ - **Provider error (4xx/5xx via gateway)**: report status + body verbatim; the
218
+ gateway is reachable and auth passed, the upstream call failed — usually a
219
+ provider key or model-name issue in the app itself.
220
+
221
+ Never report success on any of these. An unverified integration is reported as
222
+ unverified.
@@ -0,0 +1,48 @@
1
+ # caveman-stats
2
+
3
+ Recorded session usage. Savings stay unknown without a measured comparison.
4
+
5
+ ## What it does
6
+
7
+ Reads the current Claude Code session log and reports output tokens, cache-read input tokens, and response counts. When a mode-transition log is available, it separates output by the mode active for each response. Missing mode attribution stays unknown. Numbers come from the JSONL session log on disk — the model itself does not compute or estimate them. Output is injected by the `caveman-mode-tracker` hook, which intercepts `/caveman-stats`, runs the stats script, and hands the formatted block back as `additionalContext` with an instruction to print it verbatim.
8
+
9
+ The transcript does not contain the same session without Caveman, so the report cannot calculate tokens saved, a reduction percentage, dollars saved, rule overhead, or a net result. Earlier releases applied a fixed ratio without a committed reviewed benchmark. Those estimates no longer appear in session reports, lifetime totals, shared summaries, or the statusline.
10
+
11
+ In Claude Code, every session also writes a snapshot when it ends (a `SessionEnd` hook runs the same script with `--record`, silently), so `--all` and `--since` count every session, not only the ones where you ran `/caveman-stats`.
12
+
13
+ Recorded history stays on disk. New snapshots contain observed usage and mode attribution; historical estimated-savings fields are ignored. Original/current memory-file pairs show byte-size differences separately, without treating them as provider savings.
14
+
15
+ ## How to invoke
16
+
17
+ ```
18
+ /caveman-stats
19
+ /caveman-stats --all
20
+ /caveman-stats --since 7d
21
+ /caveman-stats --share
22
+ ```
23
+
24
+ Claude Code's hook runs `src/hooks/caveman-stats.js` and tells the model to relay the generated report verbatim. The model does not estimate the numbers.
25
+
26
+ ## Example output
27
+
28
+ An illustrative transcript with one response and 1,000 output tokens produces:
29
+
30
+ ```
31
+ Turns: 1
32
+ ──────────────────────────────────
33
+ Output tokens: 1,000
34
+ Cache-read tokens: 2,400
35
+ ──────────────────────────────────
36
+ Mode: full (current mode; no transition log)
37
+ Savings: unknown — no measured comparison for this session.
38
+ ```
39
+
40
+ ## See also
41
+
42
+ - [`SKILL.md`](./SKILL.md) — hook contract
43
+ - [Honest Numbers](../../docs/HONEST-NUMBERS.md) — measurement limits
44
+ - [Caveman README](../../README.md) — repo overview
45
+
46
+ Gemini CLI uses its native `/stats model` or `/stats session` report. The Caveman
47
+ command points there; it cannot access Gemini's live metrics or aggregate Claude
48
+ transcripts as Gemini usage. [Gemini command reference](https://geminicli.com/docs/reference/commands/).
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: caveman-stats
3
+ description: >
4
+ Show recorded output and cache-read token usage and mode attribution for
5
+ the current Claude Code session, or locate the host's native usage report.
6
+ Trigger: /caveman-stats.
7
+ ---
8
+
9
+ In Claude Code, `src/hooks/caveman-mode-tracker.js` resolves `src/hooks/caveman-stats.js` next to itself and runs it on `/caveman-stats`. The hook does not block the prompt: it supplies the report through `hookSpecificOutput.additionalContext` with an instruction to print it verbatim inside a fenced code block. Do exactly that, and do not calculate, recompute or re-round the numbers yourself.
10
+
11
+ In Gemini CLI, direct the user to `/stats model` for current session token usage or `/stats session` for session statistics. Gemini custom commands are prompts; they cannot invoke the built-in command or read its live session metrics. Never read Claude Code transcripts as Gemini usage. In other hosts, use a native usage report if one is available; otherwise say that current session usage is unavailable. The Claude reader and its lifetime history apply only to Claude Code. Savings remain unknown in every host without a measured comparison.
12
+
13
+ The report shows recorded output and cache-read tokens, response counts, and mode attribution where available. Savings are unknown: the transcript has no measured comparison without Caveman. Do not infer saved tokens, percentages, dollars, rule overhead, or a net result from output counts or the current mode.
14
+
15
+ `--all` and `--since 7d` aggregate the latest recorded output count per session. `--share` reports observed usage with savings unknown. Historical `est_saved_*` fields are ignored; their original history rows remain on disk. The statusline shows the active mode without the retired savings badge.
16
+
17
+ Original/current memory-file pairs are reported by their measured byte sizes. Those file-size differences do not establish provider token or billing savings. See `docs/HONEST-NUMBERS.md`.
@@ -0,0 +1,298 @@
1
+ // compile.mjs — validates canonical agent skills and generates delivery embeds.
2
+ //
3
+ // Every skill body lives once at skills/<id>/SKILL.md. registry.json
4
+ // decides which delivery surfaces receive it and which install suites include
5
+ // it. The CLI and web import generated TypeScript; neither hand-copies prompts.
6
+
7
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { loadSurfaces, scanSkillBody } from "./verbs-gate.mjs";
11
+ import { activationRule, embedRuleBody } from "./activation-rule.mjs";
12
+
13
+ const here = dirname(fileURLToPath(import.meta.url));
14
+ const BANNED = ["TO" + "DO", "FIX" + "ME", "not " + "implemented", "not-" + "implemented"];
15
+ const DELIVERIES = new Set(["cli", "web", "native"]);
16
+ const REGISTRY_KEYS = new Set(["schema_version", "native_pack", "preserved_skill_ids", "skills", "suites"]);
17
+ const SKILL_KEYS = new Set([
18
+ "id", "summary", "delivery", "suites", "activation", "task_types", "evidence_status",
19
+ "prompt_byte_budget", "conflicts", "precedence", "guardrails", "entry_condition", "stop_condition",
20
+ ]);
21
+ const NATIVE_PACK_KEYS = new Set(["id", "version", "protocol", "core_source", "core_prompt_token_budget", "targets"]);
22
+ const NATIVE_TARGETS = new Set(["claude", "codex", "hermes", "gemini", "opencode", "aider"]);
23
+ const NATIVE_ACTIVATION = {
24
+ claude: { core: "SessionStart", task: "UserPromptSubmit" },
25
+ codex: { core: "developer_instructions+SessionStart", task: "UserPromptSubmit" },
26
+ hermes: { core: "pre_llm_call", task: "pre_llm_call" },
27
+ gemini: { core: "BeforeAgent", task: "BeforeAgent" },
28
+ opencode: { core: "experimental.chat.system.transform", task: "chat.message" },
29
+ aider: { core: "read_only_conventions", task: "native_repository_map_authoritative" },
30
+ };
31
+
32
+ function die(message) {
33
+ console.error(`agent-skill compile failed: ${message}`);
34
+ process.exit(1);
35
+ }
36
+
37
+ function object(value, label) {
38
+ if (!value || typeof value !== "object" || Array.isArray(value)) die(`${label} must be an object`);
39
+ return value;
40
+ }
41
+
42
+ function exactKeys(value, allowed, label) {
43
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
44
+ if (unknown.length > 0) die(`${label} has unknown keys: ${unknown.sort().join(", ")}`);
45
+ }
46
+
47
+ const registry = object(JSON.parse(readFileSync(join(here, "registry.json"), "utf8")), "registry");
48
+ exactKeys(registry, REGISTRY_KEYS, "registry");
49
+ if (registry.schema_version !== "2") die(`unsupported schema_version ${JSON.stringify(registry.schema_version)}`);
50
+ if (!Array.isArray(registry.skills) || registry.skills.length === 0) die("skills must be a non-empty array");
51
+ const suites = object(registry.suites, "suites");
52
+ if (!Array.isArray(registry.preserved_skill_ids) || registry.preserved_skill_ids.some((id) => typeof id !== "string" || !/^[a-z0-9-]+$/.test(id))) {
53
+ die("preserved_skill_ids must be skill ids");
54
+ }
55
+ const preservedSkillIDs = new Set(registry.preserved_skill_ids);
56
+ if (preservedSkillIDs.size !== registry.preserved_skill_ids.length) die("preserved_skill_ids contains duplicates");
57
+ const nativePackMeta = object(registry.native_pack, "native_pack");
58
+ exactKeys(nativePackMeta, NATIVE_PACK_KEYS, "native_pack");
59
+ if (typeof nativePackMeta.id !== "string" || !/^[a-z0-9-]+$/.test(nativePackMeta.id)) die("native_pack.id invalid");
60
+ if (typeof nativePackMeta.version !== "string" || !/^\d+\.\d+\.\d+$/.test(nativePackMeta.version)) die("native_pack.version invalid");
61
+ if (!Number.isInteger(nativePackMeta.protocol) || nativePackMeta.protocol < 1) die("native_pack.protocol invalid");
62
+ if (typeof nativePackMeta.core_source !== "string" || nativePackMeta.core_source.includes("..") || nativePackMeta.core_source.startsWith("/")) die("native_pack.core_source invalid");
63
+ if (!Number.isInteger(nativePackMeta.core_prompt_token_budget) || nativePackMeta.core_prompt_token_budget < 1) die("native_pack.core_prompt_token_budget invalid");
64
+ if (!Array.isArray(nativePackMeta.targets) || nativePackMeta.targets.length === 0 || nativePackMeta.targets.some((target) => !NATIVE_TARGETS.has(target))) die("native_pack.targets invalid");
65
+ if (new Set(nativePackMeta.targets).size !== nativePackMeta.targets.length) die("native_pack.targets contains duplicates");
66
+ const corePath = join(here, nativePackMeta.core_source);
67
+ if (!existsSync(corePath)) die(`native Core source missing: ${nativePackMeta.core_source}`);
68
+ const nativeCore = readFileSync(corePath, "utf8").trim();
69
+ const coreEstimatedTokens = Math.ceil(Buffer.byteLength(nativeCore) / 3);
70
+ if (coreEstimatedTokens > nativePackMeta.core_prompt_token_budget) {
71
+ die(`native Core exceeds conservative token estimate: ${coreEstimatedTokens} > ${nativePackMeta.core_prompt_token_budget}`);
72
+ }
73
+
74
+ const canonicalIDs = readdirSync(here, { withFileTypes: true })
75
+ .filter((entry) => entry.isDirectory() && existsSync(join(here, entry.name, "SKILL.md")))
76
+ .map((entry) => entry.name)
77
+ .sort();
78
+ const seen = new Set();
79
+ const skills = [];
80
+
81
+ for (const raw of registry.skills) {
82
+ const meta = object(raw, "skill entry");
83
+ exactKeys(meta, SKILL_KEYS, `skill ${JSON.stringify(meta.id)}`);
84
+ if (typeof meta.id !== "string" || !/^[a-z0-9-]+$/.test(meta.id)) die(`invalid skill id ${JSON.stringify(meta.id)}`);
85
+ if (seen.has(meta.id)) die(`duplicate skill id ${meta.id}`);
86
+ seen.add(meta.id);
87
+ if (typeof meta.summary !== "string" || meta.summary.trim() === "") die(`${meta.id}: summary required`);
88
+ if (!Array.isArray(meta.delivery) || meta.delivery.length === 0) die(`${meta.id}: delivery required`);
89
+ if (meta.delivery.some((value) => !DELIVERIES.has(value))) die(`${meta.id}: unknown delivery`);
90
+ if (!Array.isArray(meta.suites) || meta.suites.some((value) => typeof value !== "string")) die(`${meta.id}: suites must be strings`);
91
+
92
+ const native = meta.delivery.includes("native");
93
+ const nativeKeys = ["activation", "task_types", "evidence_status", "prompt_byte_budget", "conflicts", "precedence", "guardrails", "entry_condition", "stop_condition"];
94
+ if (native) {
95
+ if (meta.activation !== "classified") die(`${meta.id}: native activation must be classified`);
96
+ if (!Array.isArray(meta.task_types) || meta.task_types.length === 0 || meta.task_types.some((value) => typeof value !== "string" || !/^[a-z0-9-]+$/.test(value))) die(`${meta.id}: native task_types invalid`);
97
+ if (typeof meta.evidence_status !== "string" || meta.evidence_status.trim() === "") die(`${meta.id}: native evidence_status required`);
98
+ if (!Number.isInteger(meta.prompt_byte_budget) || meta.prompt_byte_budget < 1) die(`${meta.id}: native prompt_byte_budget invalid`);
99
+ if (!Array.isArray(meta.conflicts) || meta.conflicts.some((value) => typeof value !== "string")) die(`${meta.id}: native conflicts invalid`);
100
+ if (!Number.isInteger(meta.precedence) || meta.precedence < 0) die(`${meta.id}: native precedence invalid`);
101
+ if (!Array.isArray(meta.guardrails) || meta.guardrails.length === 0 || meta.guardrails.some((value) => typeof value !== "string")) die(`${meta.id}: native guardrails invalid`);
102
+ if (typeof meta.entry_condition !== "string" || typeof meta.stop_condition !== "string") die(`${meta.id}: native entry/stop condition required`);
103
+ } else if (nativeKeys.some((key) => Object.hasOwn(meta, key))) {
104
+ die(`${meta.id}: native metadata requires native delivery`);
105
+ }
106
+
107
+ const file = join(here, meta.id, "SKILL.md");
108
+ if (!existsSync(file)) die(`${meta.id}/SKILL.md missing`);
109
+ const body = readFileSync(file, "utf8");
110
+ if (!body.startsWith("---\n")) die(`${meta.id}: SKILL.md must open with YAML frontmatter`);
111
+ if (!body.includes(`name: ${meta.id}`)) die(`${meta.id}: frontmatter name must match directory`);
112
+ for (const marker of BANNED) {
113
+ if (body.includes(marker)) die(`${meta.id}: contains banned marker ${JSON.stringify(marker)}`);
114
+ }
115
+ const frontmatterEnd = body.indexOf("\n---\n", 4);
116
+ if (frontmatterEnd < 0) die(`${meta.id}: SKILL.md frontmatter is not closed`);
117
+ const instructions = body.slice(frontmatterEnd + 5).trim();
118
+ if (native && Buffer.byteLength(instructions) > meta.prompt_byte_budget) {
119
+ die(`${meta.id}: instruction bytes exceed budget (${Buffer.byteLength(instructions)} > ${meta.prompt_byte_budget})`);
120
+ }
121
+ skills.push({ ...meta, body, instructions });
122
+ }
123
+
124
+ skills.sort((left, right) => left.id.localeCompare(right.id));
125
+ const registryIDs = skills.map((skill) => skill.id);
126
+ const registered = new Set(registryIDs);
127
+ const missingRegistryIDs = registryIDs.filter((id) => !canonicalIDs.includes(id));
128
+ const unexpectedCanonicalIDs = canonicalIDs.filter((id) => !registered.has(id) && !preservedSkillIDs.has(id));
129
+ const overlappingPreservedIDs = registryIDs.filter((id) => preservedSkillIDs.has(id));
130
+ if (missingRegistryIDs.length > 0 || unexpectedCanonicalIDs.length > 0 || overlappingPreservedIDs.length > 0) {
131
+ die(`registry ids do not match canonical skill dirs (missing: ${missingRegistryIDs.join(", ") || "none"}; unexpected: ${unexpectedCanonicalIDs.join(", ") || "none"}; registered-and-preserved: ${overlappingPreservedIDs.join(", ") || "none"})`);
132
+ }
133
+
134
+ for (const [suite, ids] of Object.entries(suites)) {
135
+ if (!/^[a-z0-9-]+$/.test(suite) || !Array.isArray(ids) || ids.length === 0) die(`invalid suite ${JSON.stringify(suite)}`);
136
+ for (const id of ids) {
137
+ const skill = skills.find((entry) => entry.id === id);
138
+ if (!skill) die(`suite ${suite} references unknown skill ${JSON.stringify(id)}`);
139
+ if (!skill.suites.includes(suite)) die(`${id}: suite ${suite} missing from skill metadata`);
140
+ if (!skill.delivery.includes("cli")) die(`${id}: suite skills must be CLI-deliverable`);
141
+ }
142
+ }
143
+ for (const skill of skills) {
144
+ for (const suite of skill.suites) {
145
+ if (!Array.isArray(suites[suite]) || !suites[suite].includes(skill.id)) {
146
+ die(`${skill.id}: suite ${suite} does not include the skill`);
147
+ }
148
+ }
149
+ }
150
+
151
+ function generatedBody(selected, destination) {
152
+ const bodies = Object.fromEntries(selected.map((skill) => [skill.id, skill.body]));
153
+ const metadata = selected.map(({ id, summary, delivery, suites: skillSuites }) => ({
154
+ id,
155
+ summary,
156
+ delivery,
157
+ suites: skillSuites,
158
+ }));
159
+ const selectedIDs = new Set(selected.map((skill) => skill.id));
160
+ const selectedSuites = Object.fromEntries(
161
+ Object.entries(suites)
162
+ .map(([suite, ids]) => [suite, ids.filter((id) => selectedIDs.has(id))])
163
+ .filter(([, ids]) => ids.length > 0),
164
+ );
165
+ return `// GENERATED by skills/compile.mjs from skills/*/SKILL.md + registry.json — DO NOT EDIT.
166
+ // Destination: ${destination}.
167
+
168
+ export type AgentSkillMetadata = {
169
+ id: string;
170
+ summary: string;
171
+ delivery: string[];
172
+ suites: string[];
173
+ };
174
+
175
+ export const AGENT_SKILLS: Record<string, string> = ${JSON.stringify(bodies, null, 2)};
176
+ export const AGENT_SKILL_METADATA: AgentSkillMetadata[] = ${JSON.stringify(metadata, null, 2)};
177
+ export const AGENT_SKILL_SUITES: Record<string, string[]> = ${JSON.stringify(selectedSuites, null, 2)};
178
+ `;
179
+ }
180
+
181
+ const nativeSkills = skills.filter((skill) => skill.delivery.includes("native"));
182
+ const taskOwners = new Map();
183
+ for (const skill of nativeSkills) {
184
+ for (const taskType of skill.task_types) {
185
+ const owners = taskOwners.get(taskType) ?? [];
186
+ owners.push(skill);
187
+ taskOwners.set(taskType, owners);
188
+ }
189
+ for (const conflict of skill.conflicts) {
190
+ if (!nativeSkills.some((candidate) => candidate.id === conflict)) die(`${skill.id}: conflict references unknown native skill ${conflict}`);
191
+ }
192
+ }
193
+ for (const [taskType, owners] of taskOwners) {
194
+ for (let left = 0; left < owners.length; left++) {
195
+ for (let right = left + 1; right < owners.length; right++) {
196
+ const a = owners[left];
197
+ const b = owners[right];
198
+ if (!a.conflicts.includes(b.id) || !b.conflicts.includes(a.id)) die(`native task type ${taskType}: ${a.id} and ${b.id} must declare mutual conflict`);
199
+ if (a.precedence === b.precedence) die(`native task type ${taskType}: ${a.id} and ${b.id} need distinct precedence`);
200
+ }
201
+ }
202
+ }
203
+
204
+ const compiledNativePack = {
205
+ schema: "caveman.native-pack.v1",
206
+ id: nativePackMeta.id,
207
+ version: nativePackMeta.version,
208
+ protocol: nativePackMeta.protocol,
209
+ core: {
210
+ source: nativePackMeta.core_source,
211
+ mandatory: true,
212
+ prompt_token_budget: nativePackMeta.core_prompt_token_budget,
213
+ estimated_tokens: coreEstimatedTokens,
214
+ estimate_basis: "ceil_utf8_bytes_divided_by_3",
215
+ instructions: nativeCore,
216
+ },
217
+ targets: Object.fromEntries(nativePackMeta.targets.map((target) => [target, NATIVE_ACTIVATION[target]])),
218
+ skills: nativeSkills.map(({ id, summary, activation, task_types, evidence_status, prompt_byte_budget, conflicts, precedence, guardrails, entry_condition, stop_condition, instructions }) => ({
219
+ id, summary, activation, task_types, evidence_status, prompt_byte_budget, conflicts, precedence,
220
+ guardrails, entry_condition, stop_condition, instructions,
221
+ })),
222
+ };
223
+
224
+ function nativeTypeScript() {
225
+ const instructions = Object.fromEntries(compiledNativePack.skills.map((skill) => [skill.id, skill.instructions]));
226
+ return `// GENERATED by skills/compile.mjs from native-core.md + native SKILL.md files — DO NOT EDIT.
227
+ export const NATIVE_PACK = ${JSON.stringify(compiledNativePack, null, 2)} as const;
228
+ export const NATIVE_CORE = ${JSON.stringify(nativeCore)};
229
+ export const NATIVE_SKILL_INSTRUCTIONS: Record<string, string> = ${JSON.stringify(instructions, null, 2)};
230
+ `;
231
+ }
232
+
233
+ const cliCandidates = [
234
+ process.env.CAVEMAN_CLI_DIR ? resolve(process.env.CAVEMAN_CLI_DIR) : "",
235
+ join(here, "..", "cli"),
236
+ join(here, "..", "packages", "cli"),
237
+ ].filter(Boolean);
238
+ const cliDir = cliCandidates.find((candidate) => existsSync(join(candidate, "src")));
239
+ if (!cliDir) die("CLI source directory not found");
240
+
241
+ // skills-verbs gate: a skill can never document a CLI command, MCP tool, or SDK
242
+ // call the shipped surfaces do not expose. Runs before any generated write, so a
243
+ // drift fails the build closed rather than embedding a broken instruction.
244
+ const surfaces = loadSurfaces({ skillsDir: here, cliDir });
245
+ if (surfaces.errors.length > 0) {
246
+ die(`skills-verbs gate could not build the command surface (refusing to pass open): ${surfaces.errors.join("; ")}`);
247
+ }
248
+ const surfaceViolations = skills.flatMap((skill) => scanSkillBody(skill.id, skill.body, surfaces));
249
+ if (surfaceViolations.length > 0) {
250
+ die(`skill references a surface that does not exist:\n ${surfaceViolations.join("\n ")}`);
251
+ }
252
+
253
+ const cliSkills = skills.filter((skill) => skill.delivery.includes("cli"));
254
+ if (cliDir) {
255
+ writeFileSync(join(cliDir, "src", "agent-skills.generated.ts"), generatedBody(cliSkills, "CLI"));
256
+ writeFileSync(join(cliDir, "src", "native-pack.generated.ts"), nativeTypeScript());
257
+ console.error(`compiled ${cliSkills.length} agent skill(s) into ${join(cliDir, "src", "agent-skills.generated.ts")}`);
258
+ } else {
259
+ die("CLI source directory not found");
260
+ }
261
+
262
+ // Always-on activation rule, derived from the caveman skill so the IDE rule,
263
+ // the opencode AGENTS.md body and the caveman-init.js fallback cannot drift.
264
+ const repoRoot = join(here, "..");
265
+ if (existsSync(join(repoRoot, "src", "rules"))) {
266
+ const initPath = join(repoRoot, "src", "tools", "caveman-init.js");
267
+ let rule, init;
268
+ try {
269
+ rule = activationRule(readFileSync(join(here, "caveman", "SKILL.md"), "utf8"));
270
+ init = embedRuleBody(readFileSync(initPath, "utf8"), rule);
271
+ } catch (error) {
272
+ die(error.message);
273
+ }
274
+ writeFileSync(join(repoRoot, "src", "rules", "caveman-activate.md"), rule);
275
+ writeFileSync(initPath, init);
276
+ console.error("compiled the always-on activation rule into src/rules/caveman-activate.md and src/tools/caveman-init.js");
277
+ }
278
+
279
+ const nativePackJSON = JSON.stringify(compiledNativePack, null, 2) + "\n";
280
+ const nativeRuntimeDir = join(here, "..", "proxy", "internal", "nativepack");
281
+ mkdirSync(nativeRuntimeDir, { recursive: true });
282
+ writeFileSync(join(nativeRuntimeDir, "native-pack.generated.json"), nativePackJSON);
283
+ const generatedRoot = join(here, "generated");
284
+ for (const target of nativePackMeta.targets) {
285
+ const targetDir = join(generatedRoot, target);
286
+ mkdirSync(targetDir, { recursive: true });
287
+ writeFileSync(join(targetDir, "pack.json"), JSON.stringify({ ...compiledNativePack, target, activation: NATIVE_ACTIVATION[target] }, null, 2) + "\n");
288
+ }
289
+ console.error(`compiled ${nativeSkills.length} native skill(s) for ${nativePackMeta.targets.length} host target(s)`);
290
+
291
+ const webDir = join(here, "..", "..", "cloud", "web", "lib");
292
+ const webSkills = skills.filter((skill) => skill.delivery.includes("web"));
293
+ if (existsSync(webDir)) {
294
+ writeFileSync(join(webDir, "agent-skills.generated.ts"), generatedBody(webSkills, "web"));
295
+ console.error(`compiled ${webSkills.length} agent skill(s) into the web embed target`);
296
+ } else {
297
+ console.error(`web embed target not present — skipped (${webSkills.length} skill(s) validated)`);
298
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "schema_version": "1",
3
+ "tools": [
4
+ "caveman_compress",
5
+ "caveman_retrieve",
6
+ "caveman_stats",
7
+ "caveman_toon_decode",
8
+ "caveman_toon_encode"
9
+ ]
10
+ }