cc-hindsight 1.2.0 → 1.3.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/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ import { stripVTControlCharacters, styleText } from "node:util";
10
10
  import readline from "node:readline";
11
11
  import { spinner } from "@clack/prompts";
12
12
  //#region package.json
13
- var version = "1.2.0";
13
+ var version = "1.3.0";
14
14
  var 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.";
15
15
  //#endregion
16
16
  //#region src/commands/_shared.ts
@@ -317,10 +317,12 @@ const defaultSpawn$1 = (cmd, args, input) => new Promise((resolve) => {
317
317
  "ignore",
318
318
  "ignore"
319
319
  ] });
320
+ child.unref();
320
321
  let settled = false;
321
322
  const settle = (v) => {
322
323
  if (settled) return;
323
324
  settled = true;
325
+ child.stdin?.destroy();
324
326
  resolve(v);
325
327
  };
326
328
  child.on("error", (err) => settle({
@@ -330,6 +332,7 @@ const defaultSpawn$1 = (cmd, args, input) => new Promise((resolve) => {
330
332
  child.on("close", (code) => settle({ code }));
331
333
  child.on("exit", (code) => settle({ code }));
332
334
  child.stdin?.on("error", () => {});
335
+ child.stdin?.once("finish", () => child.stdin?.unref?.());
333
336
  child.stdin?.write(input);
334
337
  child.stdin?.end();
335
338
  });
@@ -1045,6 +1048,42 @@ function buildClusterPrompt(digests, origins) {
1045
1048
  "=== END SESSION DIGESTS ==="
1046
1049
  ].join("\n");
1047
1050
  }
1051
+ /**
1052
+ * Build the stage-2b merge prompt (windowed clustering only). When the corpus
1053
+ * exceeds the input budget, digests are clustered in windows; each window
1054
+ * produces tasks that cannot see the other windows' sessions, so the same
1055
+ * underlying goal can surface as two tasks. This prompt shows every task's
1056
+ * identity card and asks ONLY for cross-task unification, never re-grouping
1057
+ * of members.
1058
+ */
1059
+ function buildMergePrompt(tasks) {
1060
+ const blocks = tasks.map((t) => [
1061
+ `- slug: ${t.slug}`,
1062
+ ` title: ${t.title}`,
1063
+ ` rationale: ${t.rationale}`,
1064
+ ` sessions: ${t.members.length}`
1065
+ ].join("\n"));
1066
+ return [
1067
+ "You are unifying tasks that were produced by clustering a large corpus of",
1068
+ "coding-agent sessions in independent windows. Tasks from different windows",
1069
+ "may describe the SAME underlying goal. Below is every task's identity.",
1070
+ "",
1071
+ "Identify groups of two or more tasks that pursue the same underlying goal:",
1072
+ "- For each group output one entry in \"merges\" with:",
1073
+ " - \"slugs\": the existing slugs to unify (copied VERBATIM, two or more);",
1074
+ " - \"slug\": a unique kebab-case identifier of 2-5 words for the unified task;",
1075
+ " - \"title\": a short human-readable title;",
1076
+ " - \"rationale\": one or two sentences on why these are one task.",
1077
+ "- Use ONLY the slugs listed below; never invent slugs in \"slugs\".",
1078
+ "- List each existing slug in AT MOST one merge group.",
1079
+ "- Tasks you do not mention stay unchanged. If nothing overlaps, return",
1080
+ " { \"merges\": [] }.",
1081
+ "",
1082
+ `=== TASKS (${tasks.length}) ===`,
1083
+ ...blocks,
1084
+ "=== END TASKS ==="
1085
+ ].join("\n");
1086
+ }
1048
1087
  //#endregion
1049
1088
  //#region src/claude/prompts/digest.ts
1050
1089
  /** Human-facing name of a session's source backend. */
@@ -1103,6 +1142,19 @@ const ClusterSchema = z.object({
1103
1142
  /** Low-substance / trivia sessions that author no oneshot. */
1104
1143
  misc: z.array(z.string())
1105
1144
  });
1145
+ /**
1146
+ * Stage 2b, windowed clustering only: which window-local tasks are really the
1147
+ * same task. `merges` lists groups of existing slugs to unify; tasks not
1148
+ * mentioned stay as they are. Empty `merges` means nothing overlaps.
1149
+ */
1150
+ const ClusterMergeSchema = z.object({ merges: z.array(z.object({
1151
+ /** Slugs of the existing tasks to unify (two or more). */
1152
+ slugs: z.array(z.string()),
1153
+ /** Replacement identity for the unified task. */
1154
+ slug: z.string(),
1155
+ title: z.string(),
1156
+ rationale: z.string()
1157
+ })) });
1106
1158
  /** Stage 3 — author: one realistic oneshot + observed preferences per task. */
1107
1159
  const AuthorSchema = z.object({
1108
1160
  slug: z.string(),
@@ -1206,6 +1258,9 @@ function defaultSpawn(bin, args, opts) {
1206
1258
  if (settled) return;
1207
1259
  settled = true;
1208
1260
  clearTimers();
1261
+ child.stdout?.destroy();
1262
+ child.stderr?.destroy();
1263
+ child.stdin?.destroy();
1209
1264
  resolve({
1210
1265
  code,
1211
1266
  signal,
@@ -1218,6 +1273,9 @@ function defaultSpawn(bin, args, opts) {
1218
1273
  if (settled) return;
1219
1274
  settled = true;
1220
1275
  clearTimers();
1276
+ child.stdout?.destroy();
1277
+ child.stderr?.destroy();
1278
+ child.stdin?.destroy();
1221
1279
  reject(err);
1222
1280
  });
1223
1281
  child.on("close", (code, signal) => settle(code, signal));
@@ -1849,7 +1907,118 @@ function synthesizeNoGroupTasks(digests) {
1849
1907
  };
1850
1908
  }
1851
1909
  /**
1852
- * Stage 2 — cluster all digests into semantic tasks (one call total).
1910
+ * Split the corpus into clustering windows whose prompts each fit the input
1911
+ * budget. Returns one window (all ids, sorted) when the whole prompt fits or
1912
+ * no budget is known; otherwise greedily packs sorted ids so every window's
1913
+ * prompt stays within budget (a single oversized digest still gets its own
1914
+ * window rather than being dropped). Sorted, deterministic, order-preserving:
1915
+ * re-running the same corpus plans the same windows.
1916
+ */
1917
+ function planClusterWindows(digests, origins, budget) {
1918
+ const ids = Object.keys(digests).sort();
1919
+ if (budget === void 0 || buildClusterPrompt(digests, origins).length <= budget) return [ids];
1920
+ const overhead = buildClusterPrompt({}, origins).length;
1921
+ const cost = (id) => {
1922
+ const d = digests[id];
1923
+ return buildClusterPrompt(d ? { [id]: d } : {}, origins).length - overhead;
1924
+ };
1925
+ const windows = [];
1926
+ let current = [];
1927
+ let used = overhead;
1928
+ for (const id of ids) {
1929
+ const c = cost(id);
1930
+ if (current.length > 0 && used + c > budget) {
1931
+ windows.push(current);
1932
+ current = [];
1933
+ used = overhead;
1934
+ }
1935
+ current.push(id);
1936
+ used += c;
1937
+ }
1938
+ if (current.length > 0) windows.push(current);
1939
+ return windows;
1940
+ }
1941
+ /**
1942
+ * Suffix a slug for uniqueness WITHOUT breaking the 2-5 word slug rule.
1943
+ *
1944
+ * Appending to a 5-word slug would produce a 6-word slug, which
1945
+ * {@link validateCluster} rejects; since a slug is also a path component, the
1946
+ * task would be unwritable. So append only while there is room, and otherwise
1947
+ * replace the final word with the counter, keeping the word count fixed.
1948
+ */
1949
+ function suffixSlug(slug, n) {
1950
+ const words = slug.split("-");
1951
+ return words.length < 5 ? `${slug}-${n}` : [...words.slice(0, 4), String(n)].join("-");
1952
+ }
1953
+ /**
1954
+ * Apply a merge response to the combined window tasks. Deterministic and
1955
+ * defensive: an entry is applied only when every referenced slug exists, it
1956
+ * names at least two tasks, no slug was already consumed by an earlier entry,
1957
+ * and its replacement slug is well-formed; anything else is skipped with a note
1958
+ * (the unmerged union is still a fully valid grouping). Members of merged tasks
1959
+ * are unioned and deduped.
1960
+ *
1961
+ * The slug check is what keeps this path safe to write. Every other cluster
1962
+ * response passes {@link validateCluster} before anything is saved, but the
1963
+ * merge call runs AFTER per-window validation and `ClusterMergeSchema` types
1964
+ * the replacement slug as a bare string. A task slug is also a path component
1965
+ * (`library/<slug>/…`), so a response of `"Payments Work"` or `"../../escaped"`
1966
+ * would otherwise become a directory name.
1967
+ */
1968
+ function applyClusterMerges(tasks, merges) {
1969
+ const bySlug = new Map(tasks.map((t) => [t.slug, t]));
1970
+ const consumed = /* @__PURE__ */ new Set();
1971
+ const merged = [];
1972
+ const notes = [];
1973
+ for (const entry of merges) {
1974
+ const missing = entry.slugs.filter((s) => !bySlug.has(s));
1975
+ if (missing.length > 0) {
1976
+ notes.push(`merge skipped: unknown slug(s) ${missing.join(", ")}`);
1977
+ continue;
1978
+ }
1979
+ if (entry.slugs.length < 2) {
1980
+ notes.push(`merge skipped: fewer than two slugs (${entry.slugs.join(", ") || "none"})`);
1981
+ continue;
1982
+ }
1983
+ const doubly = entry.slugs.filter((s) => consumed.has(s));
1984
+ if (doubly.length > 0) {
1985
+ notes.push(`merge skipped: slug(s) already merged ${doubly.join(", ")}`);
1986
+ continue;
1987
+ }
1988
+ if (!SLUG_PATTERN.test(entry.slug)) {
1989
+ notes.push(`merge skipped: slug "${entry.slug}" is not 2-5 kebab-case words`);
1990
+ continue;
1991
+ }
1992
+ for (const s of entry.slugs) consumed.add(s);
1993
+ const members = [...new Set(entry.slugs.flatMap((s) => bySlug.get(s).members))];
1994
+ merged.push({
1995
+ slug: entry.slug,
1996
+ title: entry.title,
1997
+ rationale: entry.rationale,
1998
+ members
1999
+ });
2000
+ }
2001
+ const kept = tasks.filter((t) => !consumed.has(t.slug));
2002
+ const finalTasks = [...kept];
2003
+ const seen = new Set(kept.map((t) => t.slug));
2004
+ for (const m of merged) {
2005
+ let slug = m.slug;
2006
+ for (let n = 2; seen.has(slug); n++) slug = suffixSlug(m.slug, n);
2007
+ seen.add(slug);
2008
+ finalTasks.push(slug === m.slug ? m : {
2009
+ ...m,
2010
+ slug
2011
+ });
2012
+ }
2013
+ return {
2014
+ tasks: finalTasks,
2015
+ notes
2016
+ };
2017
+ }
2018
+ /**
2019
+ * Stage 2 — cluster all digests into semantic tasks. One call when the corpus
2020
+ * prompt fits the input budget; otherwise windowed: one call per window plus
2021
+ * one best-effort merge call that unifies cross-window duplicates.
1853
2022
  *
1854
2023
  * Resumable: a tasks.json from the same generation covering the same input set
1855
2024
  * is reused without a call. Semantic validation failures (duplicate slugs,
@@ -1858,7 +2027,6 @@ function synthesizeNoGroupTasks(digests) {
1858
2027
  * the command reports and exits non-zero, re-running resumes.
1859
2028
  */
1860
2029
  async function runClusterStage(opts) {
1861
- const runner = opts.runner ?? runClaude;
1862
2030
  const out = opts.output ?? process.stdout;
1863
2031
  const write = (s) => out.write(`${s}\n`);
1864
2032
  const inputIds = Object.keys(opts.digests).sort();
@@ -1882,27 +2050,29 @@ async function runClusterStage(opts) {
1882
2050
  cluster = synthesizeNoGroupTasks(opts.digests);
1883
2051
  write(` --no-group: synthesized ${cluster.tasks.length} task(s) deterministically (no claude call)`);
1884
2052
  } else {
1885
- write(` clustering ${inputIds.length} digest(s)…`);
1886
- const basePrompt = buildClusterPrompt(opts.digests, opts.origins);
1887
- if (opts.budget !== void 0 && basePrompt.length > opts.budget) write(` ⚠ clustering ${inputIds.length} digests is ${basePrompt.length} chars (> budget ${opts.budget}); this may hit a model/context limit. Consider --project to narrow scope.`);
1888
- cluster = canonicalizeClusterIds(await withSpinner(out, `clustering ${inputIds.length} digest(s)`, () => runner({
1889
- prompt: basePrompt,
1890
- schema: ClusterSchema,
1891
- model: opts.model,
1892
- timeoutMs: opts.timeoutMs
1893
- })), inputIds);
1894
- let problems = validateCluster(cluster, inputIds);
1895
- if (problems.length > 0) {
1896
- write(` response failed validation (${problems.length} problem(s)); retrying once…`);
1897
- const corrective = `${basePrompt}\n\nYour previous grouping had these problems:\n${problems.map((p) => `- ${p}`).join("\n")}\nProduce a corrected grouping that fixes every problem. Remember: every id in at least one task or misc, unique 2-5-word kebab-case slugs, only the listed ids.`;
1898
- cluster = canonicalizeClusterIds(await withSpinner(out, "retrying with corrections", () => runner({
1899
- prompt: corrective,
1900
- schema: ClusterSchema,
1901
- model: opts.model,
1902
- timeoutMs: opts.timeoutMs
1903
- })), inputIds);
1904
- problems = validateCluster(cluster, inputIds);
1905
- if (problems.length > 0) throw new Error(`clustering failed validation after one retry: ${problems.join("; ")}`);
2053
+ const windows = planClusterWindows(opts.digests, opts.origins, opts.budget);
2054
+ if (windows.length === 1) {
2055
+ write(` clustering ${inputIds.length} digest(s)…`);
2056
+ cluster = await clusterWindow(windows[0], opts, out, "");
2057
+ } else {
2058
+ write(` clustering ${inputIds.length} digest(s) in ${windows.length} windows (corpus exceeds the input budget of ${opts.budget} chars)…`);
2059
+ const combined = [];
2060
+ const misc = [];
2061
+ const usedSlugs = /* @__PURE__ */ new Set();
2062
+ for (const [i, windowIds] of windows.entries()) {
2063
+ const windowCluster = await clusterWindow(windowIds, opts, out, ` [window ${i + 1}/${windows.length}]`);
2064
+ for (const task of windowCluster.tasks) {
2065
+ let slug = task.slug;
2066
+ for (let n = 2; usedSlugs.has(slug); n++) slug = suffixSlug(task.slug, n);
2067
+ usedSlugs.add(slug);
2068
+ combined.push(slug === task.slug ? task : {
2069
+ ...task,
2070
+ slug
2071
+ });
2072
+ }
2073
+ misc.push(...windowCluster.misc);
2074
+ }
2075
+ cluster = await mergeWindowTasks(combined, misc, opts, out);
1906
2076
  }
1907
2077
  }
1908
2078
  const checkpoint = {
@@ -1920,6 +2090,81 @@ async function runClusterStage(opts) {
1920
2090
  resumed: false
1921
2091
  };
1922
2092
  }
2093
+ /**
2094
+ * Cluster one window of ids: one call plus one corrective retry when the
2095
+ * response fails semantic validation (against THIS window's ids). The default
2096
+ * timeout scales with the window's digest count; an explicit --timeout wins.
2097
+ */
2098
+ async function clusterWindow(windowIds, opts, out, label) {
2099
+ const runner = opts.runner ?? runClaude;
2100
+ const write = (s) => out.write(`${s}\n`);
2101
+ const digests = {};
2102
+ for (const id of windowIds) {
2103
+ const d = opts.digests[id];
2104
+ if (d) digests[id] = d;
2105
+ }
2106
+ const timeoutMs = opts.timeoutMs ?? 3e5 + 5e3 * windowIds.length;
2107
+ const basePrompt = buildClusterPrompt(digests, opts.origins);
2108
+ let cluster = canonicalizeClusterIds(await withSpinner(out, `clustering ${windowIds.length} digest(s)${label}`, () => runner({
2109
+ prompt: basePrompt,
2110
+ schema: ClusterSchema,
2111
+ model: opts.model,
2112
+ timeoutMs
2113
+ })), windowIds);
2114
+ let problems = validateCluster(cluster, windowIds);
2115
+ if (problems.length > 0) {
2116
+ write(` response failed validation (${problems.length} problem(s)); retrying once…`);
2117
+ const corrective = `${basePrompt}\n\nYour previous grouping had these problems:\n${problems.map((p) => `- ${p}`).join("\n")}\nProduce a corrected grouping that fixes every problem. Remember: every id in at least one task or misc, unique 2-5-word kebab-case slugs, only the listed ids.`;
2118
+ cluster = canonicalizeClusterIds(await withSpinner(out, `retrying with corrections${label}`, () => runner({
2119
+ prompt: corrective,
2120
+ schema: ClusterSchema,
2121
+ model: opts.model,
2122
+ timeoutMs
2123
+ })), windowIds);
2124
+ problems = validateCluster(cluster, windowIds);
2125
+ if (problems.length > 0) throw new Error(`clustering failed validation after one retry: ${problems.join("; ")}`);
2126
+ }
2127
+ return cluster;
2128
+ }
2129
+ /**
2130
+ * Unify cross-window duplicate tasks with one merge call over the combined
2131
+ * task identities. Best-effort by design: window clustering already produced
2132
+ * a fully valid grouping, so a failed or partially invalid merge response
2133
+ * degrades to (parts of) the unmerged union with a note instead of failing
2134
+ * the stage.
2135
+ */
2136
+ async function mergeWindowTasks(combined, misc, opts, out) {
2137
+ const runner = opts.runner ?? runClaude;
2138
+ const write = (s) => out.write(`${s}\n`);
2139
+ const uniqueMisc = [...new Set(misc)];
2140
+ if (combined.length < 2) return {
2141
+ tasks: combined,
2142
+ misc: uniqueMisc
2143
+ };
2144
+ const timeoutMs = opts.timeoutMs ?? 3e5 + 5e3 * combined.length;
2145
+ let merge;
2146
+ try {
2147
+ merge = await withSpinner(out, `merging ${combined.length} window task(s) into a unified grouping`, () => runner({
2148
+ prompt: buildMergePrompt(combined),
2149
+ schema: ClusterMergeSchema,
2150
+ model: opts.model,
2151
+ timeoutMs
2152
+ }));
2153
+ } catch (err) {
2154
+ write(` merge call failed (${err instanceof Error ? err.message : String(err)}); keeping the per-window tasks unmerged.`);
2155
+ return {
2156
+ tasks: combined,
2157
+ misc: uniqueMisc
2158
+ };
2159
+ }
2160
+ const { tasks, notes } = applyClusterMerges(combined, merge.merges);
2161
+ for (const note of notes) write(` ⚠ ${note}`);
2162
+ if (merge.merges.length - notes.length > 0) write(` merged ${combined.length} window task(s) → ${tasks.length}`);
2163
+ return {
2164
+ tasks,
2165
+ misc: uniqueMisc
2166
+ };
2167
+ }
1923
2168
  /** Read `exports/anaphora.json` ({export → records}); absent/invalid → {}. */
1924
2169
  function readAnaphora(home) {
1925
2170
  try {
@@ -4178,6 +4423,7 @@ async function runPreferences(args, deps = {}) {
4178
4423
  target,
4179
4424
  runner,
4180
4425
  model: args.model,
4426
+ timeoutMs: resolveTimeoutMs(args.timeout),
4181
4427
  output: out
4182
4428
  });
4183
4429
  if (merged !== null && block !== null) await offerCopyBlock({
@@ -4200,12 +4446,14 @@ async function runPreferences(args, deps = {}) {
4200
4446
  async function runConsolidation(opts) {
4201
4447
  const { prefs, taskCount, target, runner, model, output } = opts;
4202
4448
  const write = (s = "") => output.write(`${s}\n`);
4449
+ const timeoutMs = opts.timeoutMs ?? 3e5 + 5e3 * prefs.length;
4203
4450
  let consolidated;
4204
4451
  try {
4205
4452
  consolidated = await withSpinner(output, `consolidating ${prefs.length} preference(s)`, () => runner({
4206
4453
  prompt: buildConsolidatePrompt(prefs),
4207
4454
  schema: ConsolidateSchema,
4208
- model
4455
+ model,
4456
+ timeoutMs
4209
4457
  }));
4210
4458
  } catch (err) {
4211
4459
  write(`consolidation failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -4312,6 +4560,10 @@ var preferences_default = defineCommand({
4312
4560
  type: "string",
4313
4561
  description: "Model to pass through to the runner's --model for --consolidate"
4314
4562
  },
4563
+ timeout: {
4564
+ type: "string",
4565
+ description: "Consolidation call timeout in seconds (default scales with the preference count)"
4566
+ },
4315
4567
  yes: {
4316
4568
  type: "boolean",
4317
4569
  description: "Skip the consent prompt (for scripting)"
@@ -4655,6 +4907,7 @@ async function runDistill(args, deps = {}) {
4655
4907
  canPrompt,
4656
4908
  sourceMode,
4657
4909
  model: args.model,
4910
+ timeoutMs,
4658
4911
  deps,
4659
4912
  output: out
4660
4913
  });
@@ -4680,7 +4933,7 @@ async function runDistill(args, deps = {}) {
4680
4933
  * distill exit code is never affected by this cascade (best-effort tail).
4681
4934
  */
4682
4935
  async function offerPreferencesCascade(opts) {
4683
- const { home, runner, runnerName, yes, canPrompt, sourceMode, model, deps, output } = opts;
4936
+ const { home, runner, runnerName, yes, canPrompt, sourceMode, model, timeoutMs, deps, output } = opts;
4684
4937
  const write = (s = "") => output.write(`${s}\n`);
4685
4938
  const entries = readLibrary(home);
4686
4939
  const prefs = aggregatePreferences(entries);
@@ -4699,6 +4952,7 @@ async function offerPreferencesCascade(opts) {
4699
4952
  target,
4700
4953
  runner,
4701
4954
  model,
4955
+ timeoutMs,
4702
4956
  output
4703
4957
  });
4704
4958
  if (merged === null || block === null) return;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "cc-hindsight",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "cc-hindsight",
9
- "version": "1.2.0",
9
+ "version": "1.3.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@clack/prompts": "1.7.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-hindsight",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
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)",