cc-hindsight 1.0.1 → 1.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "cc-hindsight",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "cc-hindsight",
9
- "version": "1.0.1",
9
+ "version": "1.1.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@clack/prompts": "1.7.0",
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "cc-hindsight",
3
- "version": "1.0.1",
4
- "description": "Mine your Claude Code session history into a oneshot prompt library and CLAUDE.md preferences. The prompt you'd write if you knew then what you know now.",
3
+ "version": "1.1.0",
4
+ "description": "Mine your coding-agent session history (Claude Code, kiro-cli) into a oneshot prompt library and CLAUDE.md/AGENTS.md preferences. The prompt you'd write if you knew then what you know now.",
5
5
  "type": "module",
6
6
  "author": "Aditya Singhal (https://adityasinghal.com)",
7
7
  "license": "MIT",
8
8
  "keywords": [
9
9
  "claude",
10
10
  "claude-code",
11
+ "kiro",
12
+ "kiro-cli",
13
+ "agents",
11
14
  "prompt",
12
15
  "prompt-library",
13
16
  "prompt-engineering",
@@ -35,11 +38,12 @@
35
38
  },
36
39
  "scripts": {
37
40
  "build": "tsdown",
41
+ "prepare": "npm run build --silent 1>&2",
38
42
  "test": "vitest run",
39
43
  "lint": "biome check .",
40
44
  "format": "biome format --write .",
41
45
  "typecheck": "tsc --noEmit",
42
- "prepublishOnly": "npm run lint && npm run typecheck && npm test && npm run build && npm pack --dry-run --json > pack.json && node scripts/check-pack.mjs pack.json && rm pack.json"
46
+ "prepublishOnly": "npm run lint && npm run typecheck && npm test && npm run build && npm pack --dry-run --json --ignore-scripts > pack.json && node scripts/check-pack.mjs pack.json && rm pack.json"
43
47
  },
44
48
  "dependencies": {
45
49
  "@clack/prompts": "1.7.0",
@@ -1,2 +0,0 @@
1
- import { s as runClaude } from "./runner-_HierHih.js";
2
- export { runClaude };
@@ -1,313 +0,0 @@
1
- import path from "node:path";
2
- import fs from "node:fs";
3
- import { z } from "zod";
4
- import { spawn } from "node:child_process";
5
- //#region src/claude/schemas.ts
6
- /**
7
- * Distill-stage schemas — the single source of truth.
8
- *
9
- * Each stage's structured output is defined once here in zod; the JSON Schema
10
- * handed to `claude --json-schema` is derived from these via `toJsonSchema()`
11
- * (zod v4's built-in `z.toJSONSchema`), and every response is re-validated with
12
- * the same schema. One definition, three uses: derivation, validation, types.
13
- */
14
- /** Stage 1 — digest: one structured summary per session. */
15
- const DigestSchema = z.object({
16
- goal: z.string(),
17
- deliverable: z.string(),
18
- domain: z.string(),
19
- keywords: z.array(z.string()),
20
- outcome: z.enum([
21
- "completed",
22
- "partial",
23
- "abandoned",
24
- "unclear"
25
- ])
26
- });
27
- /** Stage 2 — cluster: sessions grouped into semantic tasks (many-to-one). */
28
- const ClusterSchema = z.object({
29
- tasks: z.array(z.object({
30
- slug: z.string(),
31
- title: z.string(),
32
- rationale: z.string(),
33
- members: z.array(z.string())
34
- })),
35
- /** Low-substance / trivia sessions that author no oneshot. */
36
- misc: z.array(z.string())
37
- });
38
- /** Stage 3 — author: one realistic oneshot + observed preferences per task. */
39
- const AuthorSchema = z.object({
40
- slug: z.string(),
41
- title: z.string(),
42
- oneshot_markdown: z.string().min(120, `oneshot_markdown must be the full realistic prompt (at least 120 characters), not a stub or placeholder`),
43
- confidence: z.enum([
44
- "high",
45
- "medium",
46
- "low"
47
- ]),
48
- preferences: z.array(z.object({
49
- text: z.string(),
50
- evidence: z.string()
51
- }))
52
- });
53
- /** `preferences --consolidate`: one call to merge semantic duplicates. */
54
- const ConsolidateSchema = z.object({ preferences: z.array(z.object({
55
- text: z.string(),
56
- /** How many of the original lines this merged item covers. */
57
- merged_from: z.number()
58
- })) });
59
- /**
60
- * Derive a JSON Schema from a zod schema, for passing to the
61
- * `claude --json-schema <schema>` flag.
62
- *
63
- * Real-CLI compatibility (verified against claude v2.1.207): the CLI's ajv
64
- * validator only ships the draft-07 meta-schema, so zod v4's default
65
- * draft-2020-12 output is rejected with `no schema with key or ref
66
- * "https://json-schema.org/draft/2020-12/schema"`. We target draft-7 and strip
67
- * the `$schema` key entirely so ajv applies its default dialect.
68
- */
69
- function toJsonSchema(schema) {
70
- const json = z.toJSONSchema(schema, { target: "draft-7" });
71
- delete json.$schema;
72
- return json;
73
- }
74
- //#endregion
75
- //#region src/claude/runner.ts
76
- /**
77
- * The safe bridge to the local `claude` CLI.
78
- *
79
- * All process interaction lives behind the injectable {@link RunnerIo}
80
- * interface so unit tests can mock spawning entirely and never invoke the real
81
- * binary. The default IO uses `node:child_process` + a PATH scan.
82
- *
83
- * Verified against Claude Code CLI 2.1.207 (macOS):
84
- * - `claude -p --output-format json` → single JSON envelope on stdout
85
- * ({ type, subtype, is_error, result, session_id, total_cost_usd, usage, ... });
86
- * `result` carries the model's text output.
87
- * - `--json-schema <json>` → server-side structured-output validation.
88
- * - `--tools ""` → disable all built-in tools.
89
- * - `--model <name>` → model pass-through.
90
- * Older CLIs may lack `--json-schema`; the capability probe detects it and we
91
- * fall back to embedding the schema in the prompt + zod validation.
92
- */
93
- /** Pointer shown when the `claude` binary cannot be found on PATH. */
94
- const CLAUDE_INSTALL_HINT = "`claude` CLI not found on PATH. Install it with `npm install -g @anthropic-ai/claude-code` (docs: https://docs.claude.com/en/docs/claude-code). Deterministic commands (scan/export) work without it — only distill needs claude.";
95
- /** Default per-invocation timeout: 5 minutes. */
96
- const DEFAULT_TIMEOUT_MS = 3e5;
97
- /** A typed error carrying enough context (stderr / output snippet) to report. */
98
- var ClaudeRunnerError = class extends Error {
99
- kind;
100
- stderr;
101
- output;
102
- constructor(kind, message, extra) {
103
- super(message);
104
- this.name = "ClaudeRunnerError";
105
- this.kind = kind;
106
- this.stderr = extra?.stderr;
107
- this.output = extra?.output;
108
- }
109
- };
110
- function defaultWhich(bin) {
111
- const envPath = process.env.PATH ?? "";
112
- const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
113
- for (const dir of envPath.split(path.delimiter)) {
114
- if (!dir) continue;
115
- for (const ext of exts) {
116
- const full = path.join(dir, bin + ext);
117
- try {
118
- fs.accessSync(full, fs.constants.X_OK);
119
- return full;
120
- } catch {}
121
- }
122
- }
123
- return null;
124
- }
125
- /** Grace period between SIGTERM and SIGKILL on timeout. */
126
- const KILL_GRACE_MS = 2e3;
127
- function defaultSpawn(bin, args, opts) {
128
- return new Promise((resolve, reject) => {
129
- const child = spawn(bin, args, { stdio: [
130
- "pipe",
131
- "pipe",
132
- "pipe"
133
- ] });
134
- let stdout = "";
135
- let stderr = "";
136
- let timedOut = false;
137
- let killTimer;
138
- const timer = setTimeout(() => {
139
- timedOut = true;
140
- child.kill("SIGTERM");
141
- killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
142
- killTimer.unref?.();
143
- }, opts.timeoutMs);
144
- const clearTimers = () => {
145
- clearTimeout(timer);
146
- if (killTimer) clearTimeout(killTimer);
147
- };
148
- child.stdout?.on("data", (d) => {
149
- stdout += d.toString();
150
- });
151
- child.stderr?.on("data", (d) => {
152
- stderr += d.toString();
153
- });
154
- child.on("error", (err) => {
155
- clearTimers();
156
- reject(err);
157
- });
158
- child.on("close", (code, signal) => {
159
- clearTimers();
160
- resolve({
161
- code,
162
- signal,
163
- stdout,
164
- stderr,
165
- timedOut
166
- });
167
- });
168
- child.stdin?.on("error", () => {});
169
- child.stdin?.write(opts.input);
170
- child.stdin?.end();
171
- });
172
- }
173
- /** The default IO, used when none is injected. */
174
- const defaultIo = {
175
- which: defaultWhich,
176
- spawn: defaultSpawn
177
- };
178
- let capabilitiesCache = null;
179
- /**
180
- * Probe the installed CLI's `--help` once and cache the result. `--help` is a
181
- * local, deterministic, no-API invocation, so this never costs anything.
182
- */
183
- async function probeCapabilities(bin, io) {
184
- if (capabilitiesCache) return capabilitiesCache;
185
- const help = await io.spawn(bin, ["--help"], {
186
- input: "",
187
- timeoutMs: 15e3
188
- });
189
- const text = `${help.stdout}\n${help.stderr}`;
190
- const disableTools = text.includes("--tools") ? "tools-empty" : /--disallowed-?[tT]ools/.test(text) ? "disallowed" : "none";
191
- const caps = {
192
- jsonSchema: text.includes("--json-schema"),
193
- disableTools
194
- };
195
- capabilitiesCache = caps;
196
- return caps;
197
- }
198
- /** Internal sentinel: a parse/validation problem that warrants one retry. */
199
- var RetryableError = class extends Error {};
200
- function snippet(s, max = 500) {
201
- const t = s.trim();
202
- return t.length > max ? `${t.slice(0, max)}…` : t;
203
- }
204
- /** Strip a Markdown code fence if the model wrapped its JSON in one. */
205
- function stripFence(text) {
206
- const trimmed = text.trim();
207
- const fence = trimmed.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/);
208
- return fence?.[1] ? fence[1].trim() : trimmed;
209
- }
210
- /**
211
- * Parse the CLI envelope and pull out the structured result. Throws
212
- * {@link ClaudeRunnerError} for fatal CLI errors (no point retrying) and
213
- * {@link RetryableError} for parse/validation problems (retry may help).
214
- */
215
- function extractResult(result) {
216
- let envelope;
217
- try {
218
- envelope = JSON.parse(result.stdout);
219
- } catch {
220
- const detail = snippet(result.stdout || result.stderr) || "no output";
221
- if (result.code !== 0) throw new ClaudeRunnerError("cli-error", `claude exited ${result.code}: ${detail}`, {
222
- stderr: result.stderr,
223
- output: result.stdout
224
- });
225
- throw new RetryableError(`could not parse claude JSON envelope: ${detail}`);
226
- }
227
- if (envelope.is_error) throw new ClaudeRunnerError("cli-error", `claude reported an error: ${typeof envelope.result === "string" ? envelope.result : "unknown error"}`, {
228
- stderr: result.stderr,
229
- output: result.stdout
230
- });
231
- const r = envelope.result;
232
- if (r === null || r === void 0) throw new RetryableError("claude envelope missing a 'result' field");
233
- if (typeof r === "object") return r;
234
- if (typeof r === "string") {
235
- const jsonText = stripFence(r);
236
- try {
237
- return JSON.parse(jsonText);
238
- } catch {
239
- throw new RetryableError(`claude result was not valid JSON: ${snippet(r)}`);
240
- }
241
- }
242
- throw new RetryableError(`unexpected claude result type: ${typeof r}`);
243
- }
244
- function buildArgs(caps, opts) {
245
- const args = [
246
- "-p",
247
- "--output-format",
248
- "json"
249
- ];
250
- if (caps.jsonSchema) args.push("--json-schema", JSON.stringify(toJsonSchema(opts.schema)));
251
- if ((opts.disableTools ?? true) && caps.disableTools === "tools-empty") args.push("--tools", "");
252
- if (opts.model) args.push("--model", opts.model);
253
- return args;
254
- }
255
- function buildPrompt(caps, opts) {
256
- let prompt = opts.prompt;
257
- if (!caps.jsonSchema) {
258
- const json = JSON.stringify(toJsonSchema(opts.schema));
259
- prompt += `\n\nRespond ONLY with JSON matching this schema:\n${json}`;
260
- }
261
- if ((opts.disableTools ?? true) && caps.disableTools !== "tools-empty") prompt += "\n\nDo not use any tools; answer directly from the content provided.";
262
- return prompt;
263
- }
264
- async function resolveBinary(io) {
265
- const resolved = await io.which("claude");
266
- if (!resolved) throw new ClaudeRunnerError("missing-binary", CLAUDE_INSTALL_HINT);
267
- return resolved;
268
- }
269
- /**
270
- * Invoke `claude -p` for one stage: resolve the binary, probe capabilities
271
- * (cached), spawn with the schema flag (or embed it in the prompt), parse the
272
- * envelope, validate against the zod schema, and retry exactly once on a
273
- * parse/validation failure with a corrective note. Throws a typed
274
- * {@link ClaudeRunnerError} on missing binary, timeout, CLI error, or a second
275
- * validation failure.
276
- */
277
- async function runClaude(opts, io = defaultIo) {
278
- const bin = await resolveBinary(io);
279
- const caps = opts.capabilities ?? await probeCapabilities(bin, io);
280
- const timeoutMs = opts.timeoutMs ?? 3e5;
281
- const args = buildArgs(caps, opts);
282
- const basePrompt = buildPrompt(caps, opts);
283
- let lastDetail = "";
284
- let lastOutput = "";
285
- let lastStderr = "";
286
- for (let attempt = 0; attempt < 2; attempt++) {
287
- let input = basePrompt;
288
- if (attempt === 1) input += `\n\nYour previous response could not be used (${lastDetail}). Respond ONLY with valid JSON matching the required schema — no prose, no code fences.`;
289
- const result = await io.spawn(bin, args, {
290
- input,
291
- timeoutMs
292
- });
293
- if (result.timedOut) throw new ClaudeRunnerError("timeout", `claude invocation timed out after ${timeoutMs}ms`, {
294
- stderr: result.stderr,
295
- output: result.stdout
296
- });
297
- lastOutput = result.stdout;
298
- lastStderr = result.stderr;
299
- try {
300
- const raw = extractResult(result);
301
- return opts.schema.parse(raw);
302
- } catch (err) {
303
- if (err instanceof ClaudeRunnerError) throw err;
304
- lastDetail = err instanceof Error ? err.message : String(err);
305
- }
306
- }
307
- throw new ClaudeRunnerError("validation", `claude response failed schema validation after one retry: ${lastDetail}`, {
308
- stderr: lastStderr,
309
- output: lastOutput
310
- });
311
- }
312
- //#endregion
313
- export { defaultIo as a, AuthorSchema as c, DigestSchema as d, KILL_GRACE_MS as i, ClusterSchema as l, ClaudeRunnerError as n, probeCapabilities as o, DEFAULT_TIMEOUT_MS as r, runClaude as s, CLAUDE_INSTALL_HINT as t, ConsolidateSchema as u };