chompyy 0.1.0 → 0.4.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 (184) hide show
  1. package/README.md +82 -8
  2. package/THIRD_PARTY_NOTICES.md +29 -1
  3. package/dist/appstate.js +121 -4
  4. package/dist/away.js +191 -25
  5. package/dist/blueprint.js +102 -7
  6. package/dist/board.js +143 -15
  7. package/dist/catalog.js +81 -0
  8. package/dist/claudesettings.js +23 -0
  9. package/dist/cli.js +804 -55
  10. package/dist/coldstart.js +208 -0
  11. package/dist/config.js +43 -8
  12. package/dist/costs.js +162 -0
  13. package/dist/deps.js +124 -0
  14. package/dist/dream.js +422 -0
  15. package/dist/duration.js +3 -3
  16. package/dist/gate.js +40 -5
  17. package/dist/history.js +308 -0
  18. package/dist/live.js +255 -0
  19. package/dist/livequota.js +42 -5
  20. package/dist/macapp.js +25 -2
  21. package/dist/pacing.js +189 -0
  22. package/dist/permissions.js +106 -0
  23. package/dist/picture.js +124 -0
  24. package/dist/picturetype.js +208 -0
  25. package/dist/preflight.js +168 -0
  26. package/dist/projects.js +5 -4
  27. package/dist/quota.js +31 -5
  28. package/dist/refresh.js +290 -0
  29. package/dist/report.js +41 -21
  30. package/dist/review.js +111 -11
  31. package/dist/runner.js +318 -10
  32. package/dist/taste.js +528 -0
  33. package/dist/tokens.js +75 -0
  34. package/dist/tokenstore.js +61 -0
  35. package/dist/trace.js +284 -0
  36. package/dist/triggers.js +193 -0
  37. package/dist/usage.js +467 -0
  38. package/dist/vendor/codeburn/prices.js +45 -0
  39. package/dist/verify.js +150 -0
  40. package/dist/verifycard.js +146 -0
  41. package/dist/workspace.js +132 -18
  42. package/package.json +4 -2
  43. package/skills/taste/SKILL.md +4 -1
  44. package/vendor/diagram-design/LICENSE +21 -0
  45. package/vendor/diagram-design/SKILL.md +399 -0
  46. package/vendor/diagram-design/UPSTREAM.md +18 -0
  47. package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
  48. package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
  49. package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
  50. package/vendor/diagram-design/assets/example-architecture.html +183 -0
  51. package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
  52. package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
  53. package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
  54. package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
  55. package/vendor/diagram-design/assets/example-bar.html +129 -0
  56. package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
  57. package/vendor/diagram-design/assets/example-box-plot.html +127 -0
  58. package/vendor/diagram-design/assets/example-bubble.html +147 -0
  59. package/vendor/diagram-design/assets/example-bump.html +142 -0
  60. package/vendor/diagram-design/assets/example-data-flow.html +143 -0
  61. package/vendor/diagram-design/assets/example-datalake.html +269 -0
  62. package/vendor/diagram-design/assets/example-db-schema.html +302 -0
  63. package/vendor/diagram-design/assets/example-dependency.html +224 -0
  64. package/vendor/diagram-design/assets/example-deployment.html +190 -0
  65. package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
  66. package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
  67. package/vendor/diagram-design/assets/example-er.html +202 -0
  68. package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
  69. package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
  70. package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
  71. package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
  72. package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
  73. package/vendor/diagram-design/assets/example-exploded.html +83 -0
  74. package/vendor/diagram-design/assets/example-fishbone.html +152 -0
  75. package/vendor/diagram-design/assets/example-flowchart.html +163 -0
  76. package/vendor/diagram-design/assets/example-gantt.html +137 -0
  77. package/vendor/diagram-design/assets/example-heatmap.html +224 -0
  78. package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
  79. package/vendor/diagram-design/assets/example-high-level.html +301 -0
  80. package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
  81. package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
  82. package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
  83. package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
  84. package/vendor/diagram-design/assets/example-it-state.html +128 -0
  85. package/vendor/diagram-design/assets/example-journey.html +148 -0
  86. package/vendor/diagram-design/assets/example-kanban.html +174 -0
  87. package/vendor/diagram-design/assets/example-layers.html +123 -0
  88. package/vendor/diagram-design/assets/example-line.html +111 -0
  89. package/vendor/diagram-design/assets/example-loop.html +100 -0
  90. package/vendor/diagram-design/assets/example-marimekko.html +148 -0
  91. package/vendor/diagram-design/assets/example-medallion.html +159 -0
  92. package/vendor/diagram-design/assets/example-nested.html +136 -0
  93. package/vendor/diagram-design/assets/example-org-chart.html +45 -0
  94. package/vendor/diagram-design/assets/example-polar.html +116 -0
  95. package/vendor/diagram-design/assets/example-process.html +64 -0
  96. package/vendor/diagram-design/assets/example-pyramid.html +119 -0
  97. package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
  98. package/vendor/diagram-design/assets/example-quadrant.html +135 -0
  99. package/vendor/diagram-design/assets/example-radar.html +139 -0
  100. package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
  101. package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
  102. package/vendor/diagram-design/assets/example-sankey.html +150 -0
  103. package/vendor/diagram-design/assets/example-sbgn.html +213 -0
  104. package/vendor/diagram-design/assets/example-scatter.html +141 -0
  105. package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
  106. package/vendor/diagram-design/assets/example-sequence.html +222 -0
  107. package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
  108. package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
  109. package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
  110. package/vendor/diagram-design/assets/example-state.html +147 -0
  111. package/vendor/diagram-design/assets/example-steps.html +78 -0
  112. package/vendor/diagram-design/assets/example-story-map.html +184 -0
  113. package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
  114. package/vendor/diagram-design/assets/example-swimlane.html +172 -0
  115. package/vendor/diagram-design/assets/example-timeline.html +135 -0
  116. package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
  117. package/vendor/diagram-design/assets/example-tree.html +173 -0
  118. package/vendor/diagram-design/assets/example-treemap.html +107 -0
  119. package/vendor/diagram-design/assets/example-uml-class.html +188 -0
  120. package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
  121. package/vendor/diagram-design/assets/example-venn.html +110 -0
  122. package/vendor/diagram-design/assets/example-wardley.html +153 -0
  123. package/vendor/diagram-design/assets/example-waterfall.html +129 -0
  124. package/vendor/diagram-design/assets/template-dark.html +99 -0
  125. package/vendor/diagram-design/assets/template.html +100 -0
  126. package/vendor/diagram-design/references/layout-budget.md +103 -0
  127. package/vendor/diagram-design/references/output-spec.md +277 -0
  128. package/vendor/diagram-design/references/primitive-annotation.md +36 -0
  129. package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
  130. package/vendor/diagram-design/references/primitives-core.md +146 -0
  131. package/vendor/diagram-design/references/semantic-patterns.md +154 -0
  132. package/vendor/diagram-design/references/style-guide.md +234 -0
  133. package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
  134. package/vendor/diagram-design/references/type-architecture.md +117 -0
  135. package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
  136. package/vendor/diagram-design/references/type-bar.md +108 -0
  137. package/vendor/diagram-design/references/type-data-flow.md +371 -0
  138. package/vendor/diagram-design/references/type-db-schema.md +48 -0
  139. package/vendor/diagram-design/references/type-dependency.md +113 -0
  140. package/vendor/diagram-design/references/type-deployment.md +45 -0
  141. package/vendor/diagram-design/references/type-dp-integration.md +407 -0
  142. package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
  143. package/vendor/diagram-design/references/type-er.md +25 -0
  144. package/vendor/diagram-design/references/type-event-modeling.md +36 -0
  145. package/vendor/diagram-design/references/type-exploded.md +115 -0
  146. package/vendor/diagram-design/references/type-fishbone.md +75 -0
  147. package/vendor/diagram-design/references/type-flowchart.md +23 -0
  148. package/vendor/diagram-design/references/type-gantt.md +45 -0
  149. package/vendor/diagram-design/references/type-heatmap.md +80 -0
  150. package/vendor/diagram-design/references/type-high-level.md +470 -0
  151. package/vendor/diagram-design/references/type-it-state.md +468 -0
  152. package/vendor/diagram-design/references/type-journey.md +55 -0
  153. package/vendor/diagram-design/references/type-kanban.md +49 -0
  154. package/vendor/diagram-design/references/type-layers.md +26 -0
  155. package/vendor/diagram-design/references/type-line.md +337 -0
  156. package/vendor/diagram-design/references/type-loop.md +223 -0
  157. package/vendor/diagram-design/references/type-medallion.md +356 -0
  158. package/vendor/diagram-design/references/type-nested.md +22 -0
  159. package/vendor/diagram-design/references/type-org-chart.md +44 -0
  160. package/vendor/diagram-design/references/type-polar.md +136 -0
  161. package/vendor/diagram-design/references/type-process.md +490 -0
  162. package/vendor/diagram-design/references/type-pyramid.md +33 -0
  163. package/vendor/diagram-design/references/type-quadrant.md +81 -0
  164. package/vendor/diagram-design/references/type-radar.md +82 -0
  165. package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
  166. package/vendor/diagram-design/references/type-sankey.md +75 -0
  167. package/vendor/diagram-design/references/type-sbgn.md +80 -0
  168. package/vendor/diagram-design/references/type-scatter.md +276 -0
  169. package/vendor/diagram-design/references/type-sequence.md +130 -0
  170. package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
  171. package/vendor/diagram-design/references/type-state.md +30 -0
  172. package/vendor/diagram-design/references/type-steps.md +180 -0
  173. package/vendor/diagram-design/references/type-story-map.md +46 -0
  174. package/vendor/diagram-design/references/type-swimlane.md +22 -0
  175. package/vendor/diagram-design/references/type-timeline.md +20 -0
  176. package/vendor/diagram-design/references/type-tree.md +24 -0
  177. package/vendor/diagram-design/references/type-treemap.md +137 -0
  178. package/vendor/diagram-design/references/type-uml-class.md +65 -0
  179. package/vendor/diagram-design/references/type-unit-grid.md +63 -0
  180. package/vendor/diagram-design/references/type-venn.md +26 -0
  181. package/vendor/diagram-design/references/type-wardley.md +39 -0
  182. package/vendor/diagram-design/references/type-waterfall.md +75 -0
  183. package/vendor/diagram-design/scripts/self_check.py +1177 -0
  184. package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
package/dist/cli.js CHANGED
@@ -1,30 +1,50 @@
1
1
  #!/usr/bin/env node
2
2
  // chompyy: park ideas, blueprint them, run approved cards while you're away.
3
- import { spawn } from 'node:child_process';
4
- import { existsSync, readFileSync } from 'node:fs';
3
+ import { execFileSync, spawn } from 'node:child_process';
4
+ import { backfillTokens, median } from './tokenstore.js';
5
+ import { compact, formatTokens, totalTokens } from './tokens.js';
6
+ import { closeSync, existsSync, openSync, readFileSync } from 'node:fs';
5
7
  import { parseArgs } from 'node:util';
6
- import { away } from './away.js';
7
- import { draftBlueprint, draftFiveStarOptions, GENERIC_FIVE_STAR } from './blueprint.js';
8
- import { addCard, COLUMNS, dropCard, formatBoard, formatCard, getCard, loadBoard, moveCard, updateBoard } from './board.js';
9
- import { loadConfig } from './config.js';
8
+ import { away, runCard } from './away.js';
9
+ import { formatPreflight, loadProfile, preflight, saveProfile } from './preflight.js';
10
+ import { verifyCard } from './verifycard.js';
11
+ import { parsePermission, recordNeeds } from './permissions.js';
12
+ import { draftAllPlan, draftBlueprint, draftFiveStarOptions, draftTitle, GENERIC_FIVE_STAR, isUsageLimit, writeBlueprintFile } from './blueprint.js';
13
+ import { addCard, awayQueue, claimDrafts, COLUMNS, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, noteDraftFailure, quotaWaitReason, recoverRunning, titleFrom, updateBoard } from './board.js';
14
+ import { loadConfig, setConfig } from './config.js';
10
15
  import { formatDuration, parseDuration } from './duration.js';
11
16
  import { budgetGate } from './gate.js';
12
17
  import { chompyyHome, homePath } from './home.js';
13
- import { loadSnapshot, mergeSnapshot, parseStatusline, saveSnapshot, statusLineText, statusText, windowView } from './quota.js';
14
- import { cardsSince, formatReport, lastReportAt, markReported, rateCard, readTaste } from './report.js';
15
- import { changedFiles, diffCard, keepCard, questionsOf, undoCard } from './review.js';
16
- import { ClaudeRunner, claudeAvailable } from './runner.js';
17
- import { commitLeftovers, planWorkspace, prepareWorkspace } from './workspace.js';
18
- import { answerCard, appState, cardView, editBlueprint, recordCliLocation } from './appstate.js';
19
- import { refreshLiveQuota } from './livequota.js';
18
+ import { loadSnapshot, mergeSnapshot, parseStatusline, saveSnapshot, statusLineText, statusText as baseStatusText, windowView } from './quota.js';
19
+ import { loadSamples } from './pacing.js';
20
+ import { cardsSince, formatReport, lastReportAt, markReported, morningLine, rateCard, readTaste } from './report.js';
21
+ import { changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } from './review.js';
22
+ import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
23
+ import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
24
+ import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, recordCliLocation } from './appstate.js';
25
+ import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
20
26
  import { recentProjects } from './projects.js';
21
27
  import { cliVersion, installApp } from './macapp.js';
28
+ import { buildDigest, historyRetention, scanHistory } from './history.js';
29
+ import { acceptColdStart, forgetColdStart, formatColdStart, loadColdStart, runColdStart } from './coldstart.js';
30
+ import { keepHistory } from './claudesettings.js';
31
+ import { blueprintHash, drawPicture } from './picture.js';
32
+ import { costRange, formatCostRange, readRuns, trendLines } from './costs.js';
33
+ import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, loadStore, nextQuestion, readSignals, recordOutcome, retirePreference, syncTasteFile, tasteChangesSince, } from './taste.js';
34
+ import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, readLogPath, setTicked } from './dream.js';
35
+ import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
36
+ import { formatTrace, traceSession } from './trace.js';
37
+ import { homedir } from 'node:os';
38
+ import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
39
+ import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
40
+ import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
22
41
  const HELP = `chompyy: use the 5-hour window capacity that would reset unused
23
42
 
24
43
  Quota
25
44
  chompyy statusline Claude Code statusLine command: reads JSON on stdin, saves a snapshot
26
45
  chompyy status % left, time to reset, pace, weekly used, staleness
27
46
  chompyy quota [--refresh] read live quota from Anthropic now (uses Claude Code's saved login; sends no message)
47
+ chompyy quota --allow-keychain | --no-keychain allow (or stop) reading that login from the macOS Keychain
28
48
  chompyy eat-tokens show leftover quota and cards you could choose to run (read-only)
29
49
 
30
50
  Board
@@ -33,8 +53,11 @@ Board
33
53
  chompyy board [--column c] cards by column (suggested later approved running review done)
34
54
  chompyy show <id> one card: blueprint, last run, what the agent said
35
55
  chompyy blueprint <id> (re)draft the blueprint with a cheap model [--model haiku]
56
+ --all-later draft every later card that has no blueprint yet, one at a time
57
+ chompyy picture <id> (re)draw the card's picture: a diagram of what it will do (diagram-design skill)
36
58
  chompyy approve <id> later → approved (needs a blueprint)
37
59
  chompyy edit-blueprint <id> replace the blueprint with text from stdin
60
+ chompyy edit-idea <id> replace a later card's idea with text from stdin
38
61
  chompyy drop <id> remove a card (kept in archive.jsonl)
39
62
 
40
63
  Away
@@ -45,22 +68,59 @@ Away
45
68
  Back
46
69
  chompyy report [--all] what ran, and the one thing to do about each
47
70
  chompyy diff <id> the change it made
48
- chompyy keep <id> merge its branch into your current branch
71
+ chompyy keep <id> merge its branch into the branch it started from (and update the live app, if set)
72
+ chompyy refresh [<id>] bring cards in review up to date with main (Chompyy does this by itself after each Keep)
49
73
  chompyy undo <id> throw it away (removes its branch; yours are untouched)
50
74
  chompyy answer <id> answer the run's questions (stdin); the card goes back to approved
51
75
  chompyy redo <id> throw this attempt away and run it again from your latest code
52
76
  chompyy rate <id> <1-5> ["why"] [--to-five "change" ...] rate a result; --to-five = what would have made it a 5
53
77
  chompyy five-star <id> options for "what would have made it a 5?" (JSON)
54
- chompyy taste show taste.md
55
78
  chompyy signals [--json] everything Chompyy has recorded from you: ratings, edits, answers
79
+ chompyy tokens [--json] exact tokens and API-value cost of each run
80
+ chompyy trends last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits
81
+
82
+ Taste (learned from what you keep, undo, edit and rate)
83
+ chompyy trace <id> one conversation turn by turn: cost per turn, context size, what ate the tokens
84
+ chompyy plan-price <usd|auto> what your plan costs a month, for "your plan did N× its price"
85
+ chompyy usage [--period today|7d|30d|month] tokens and API-value cost of every Claude Code conversation on this Mac
86
+ chompyy dream the nightly read: learn how you like to work from your coding sessions
87
+ (--dry-run shows exactly what it would read; --since 3d to re-read)
88
+ chompyy dream workspaces the folders and apps it can read, ticked or not
89
+ chompyy dream tick|untick <folder> choose what it learns from (coding folders start ticked)
90
+ chompyy taste show taste.md
91
+ chompyy taste list every preference: to ask, in taste.md, candidates, declined, retired
92
+ chompyy taste why <id> the cards, edits and quotes behind a preference
93
+ chompyy taste yes|not-now|never <id> answer a question (yes writes it to taste.md)
94
+ chompyy taste retire <id> stop using a preference (kept, with the reason)
95
+ chompyy distill [--force] read new signals and update preferences now (one model call; runs after away too)
96
+
97
+ Triggers (start away runs on their own; the budget gate still decides every card)
98
+ chompyy triggers on|off install or remove the macOS LaunchAgent that runs \`chompyy tick\` every 5 minutes
99
+ chompyy triggers what is set, and what the last tick decided
100
+ chompyy bedtime <23:30|off> run approved cards at bedtime (with the window that is left)
101
+ chompyy last-hour <on|off> run approved cards in the last hour before a 5-hour reset
102
+ chompyy missed-reset <on|off> run approved cards on the first tick after a reset nothing used (default off)
103
+ chompyy tick check the triggers once (what the LaunchAgent runs)
104
+
105
+ Get to know you (cold start)
106
+ chompyy history [--digest] what Chompyy would read from your Claude Code history (local; --digest = the exact text it would send)
107
+ chompyy coldstart [--force] read your history once and propose taste lines and suggested cards (one model call)
108
+ chompyy coldstart show the proposals accept --taste t1,t2 --cards c1 forget
109
+ chompyy keep-history <days> keep Claude Code transcripts longer (cleanupPeriodDays; default 30)
56
110
 
57
111
  App
58
112
  chompyy app install (or update) the Mac app in ~/Applications and open it
113
+ chompyy live [set <repo>|update|off] for Chompyy's own developers: the app runs from ~/.chompyy/live, which follows
114
+ main and rebuilds (CLI, and the app if its code changed) after every Keep on main
59
115
  chompyy version this CLI's version
60
116
  chompyy projects [--json] recent project folders (from Claude Code history and past cards)
61
117
  chompyy state --json everything the Mac app shows, in one JSON (board, show, status also take --json)
62
118
 
63
119
  State lives in ${chompyyHome()} (override with CHOMPYY_HOME).`;
120
+ /** `chompyy status` text with pacing: burn-rate history and your bedtime. */
121
+ function statusText(snap, now) {
122
+ return baseStatusText(snap, now, { samples: loadSamples(), bedtime: loadConfig().bedtime });
123
+ }
64
124
  async function readStdin() {
65
125
  if (process.stdin.isTTY)
66
126
  return '';
@@ -78,26 +138,65 @@ async function blueprintCard(id, model) {
78
138
  const config = loadConfig();
79
139
  const card = getCard(loadBoard(), id);
80
140
  try {
81
- const text = await draftBlueprint(card, new ClaudeRunner(config.claudeBin), {
141
+ const runner = new ClaudeRunner(config.claudeBin);
142
+ const opts = {
82
143
  model: model ?? config.blueprintModel,
83
144
  // Run in the card's folder so the model can read the repo (read-only tools only).
84
145
  cwd: existsSync(card.cwd) ? card.cwd : chompyyHome(),
85
- });
146
+ };
147
+ const text = await draftBlueprint(card, runner, opts);
148
+ // Retitle only cards still named by the first words of the prompt: a title the model already wrote
149
+ // (cold start, or an earlier draft) is kept, so redrafting a blueprint costs no extra call.
150
+ const title = card.title === titleFrom(card.idea) ? await draftTitle(card, runner, opts) : card.title;
86
151
  updateBoard((b) => {
87
152
  const c = getCard(b, id);
88
153
  c.blueprint = text;
154
+ c.title = title;
89
155
  delete c.blueprintError;
156
+ delete c.blueprintWaiting;
157
+ delete c.blueprintWaitUntil;
90
158
  delete c.draftingAt;
159
+ writeBlueprintFile(c, text);
91
160
  c.updatedAt = new Date().toISOString();
92
161
  });
162
+ if (config.pictures && windowActive(new Date()))
163
+ await pictureCard(id).catch(() => { });
93
164
  return text;
94
165
  }
95
166
  catch (err) {
96
167
  const message = err instanceof Error ? err.message : String(err);
168
+ updateBoard((b) => noteDraftFailure(b, id, message, isUsageLimit(message), retryAfterLimit(new Date())));
169
+ throw err;
170
+ }
171
+ }
172
+ /** When to retry a draft that hit the usage limit: at the 5-hour reset if known, else in 30 minutes. */
173
+ function retryAfterLimit(now) {
174
+ const five = windowView(loadSnapshot()?.fiveHour, now);
175
+ return five.known ? new Date(five.resetsAt * 1000) : new Date(now.getTime() + 30 * 60_000);
176
+ }
177
+ /** Draw (or redraw) a card's picture with the diagram-design skill. Errors are kept on the card. */
178
+ async function pictureCard(id, model) {
179
+ const config = loadConfig();
180
+ const card = getCard(loadBoard(), id);
181
+ updateBoard((b) => {
182
+ getCard(b, id).drawingAt = new Date().toISOString();
183
+ });
184
+ try {
185
+ const info = await drawPicture(card, new ClaudeRunner(config.claudeBin), { model: model ?? config.pictureModel, now: new Date() });
97
186
  updateBoard((b) => {
98
187
  const c = getCard(b, id);
99
- c.blueprintError = message;
100
- delete c.draftingAt;
188
+ c.picture = info;
189
+ delete c.pictureError;
190
+ delete c.drawingAt;
191
+ });
192
+ return info.path;
193
+ }
194
+ catch (err) {
195
+ const message = err instanceof Error ? err.message : String(err);
196
+ updateBoard((b) => {
197
+ const c = getCard(b, id);
198
+ c.pictureError = message;
199
+ delete c.drawingAt;
101
200
  });
102
201
  throw err;
103
202
  }
@@ -113,22 +212,43 @@ function fullOutput(card) {
113
212
  function windowActive(now) {
114
213
  return windowView(loadSnapshot()?.fiveHour, now).known;
115
214
  }
215
+ /** Why a draft must wait (the running window has 0% left), or null. A draft then would only hit the limit. */
216
+ function quotaEmpty(now) {
217
+ return quotaWaitReason(windowView(loadSnapshot()?.fiveHour, now));
218
+ }
116
219
  /**
117
220
  * Draft blueprints that are waiting, but only while a window is active: drafting is a model call, and
118
221
  * with no active window it would start a new 5-hour window. Called whenever quota is fresh.
119
222
  */
120
223
  function draftPending(now) {
224
+ const days = loadConfig().suggestedExpiryDays;
225
+ if (days > 0 && loadBoard().cards.some((c) => c.column === 'suggested'))
226
+ updateBoard((b) => expireSuggested(b, now, days));
121
227
  if (!windowActive(now) || !claudeAvailable(loadConfig().claudeBin))
122
228
  return;
123
- const stale = now.getTime() - 3 * 60_000;
124
- const ids = updateBoard((b) => {
125
- const due = b.cards.filter((c) => (c.column === 'later' || c.column === 'suggested') && !c.blueprint && !c.blueprintError && !c.noAutoDraft && (!c.draftingAt || Date.parse(c.draftingAt) < stale));
229
+ // With 0% left the cards wait (and say so) instead of failing; they stay due and draft after the reset.
230
+ const waiting = quotaEmpty(now);
231
+ const ids = updateBoard((b) => claimDrafts(b, now, waiting));
232
+ for (const id of ids)
233
+ blueprintInBackground(id);
234
+ // Pictures for cards whose blueprint is ready but not drawn yet, or changed since (an edit or a redraw).
235
+ if (!loadConfig().pictures || waiting)
236
+ return;
237
+ const toDraw = updateBoard((b) => {
238
+ const due = b.cards.filter((c) => ['suggested', 'later', 'approved'].includes(c.column) &&
239
+ c.blueprint && !c.draftingAt && !c.pictureError &&
240
+ (!c.picture || c.picture.blueprintHash !== blueprintHash(c.blueprint)) &&
241
+ (!c.drawingAt || Date.parse(c.drawingAt) < now.getTime() - 6 * 60_000));
126
242
  for (const c of due)
127
- c.draftingAt = now.toISOString();
243
+ c.drawingAt = now.toISOString();
128
244
  return due.map((c) => c.id);
129
245
  });
130
- for (const id of ids)
131
- blueprintInBackground(id);
246
+ for (const id of toDraw)
247
+ inBackground(['picture', id, '--quiet']);
248
+ }
249
+ function inBackground(args) {
250
+ const child = spawn(process.execPath, [process.argv[1], ...args], { detached: true, stdio: 'ignore', env: process.env });
251
+ child.unref();
132
252
  }
133
253
  /** Draft the blueprint in a detached child so `later` returns at once. */
134
254
  function blueprintInBackground(id) {
@@ -139,12 +259,189 @@ function blueprintInBackground(id) {
139
259
  });
140
260
  child.unref();
141
261
  }
262
+ /** The nightly read, then distil: inside an active window only (a model call would otherwise start one). */
263
+ async function dreamNow(now, opts = {}) {
264
+ const config = loadConfig();
265
+ if (opts.dryRun) {
266
+ const r = await dream(new ClaudeRunner(config.claudeBin), { model: config.dreamModel, now, dryRun: true, sinceMs: opts.sinceMs });
267
+ return `Would read ${r.sessions} session${r.sessions === 1 ? '' : 's'} (~${Math.round(r.readTokens / 1000)}k tokens) in ${r.chunks} call${r.chunks === 1 ? '' : 's'} with ${config.dreamModel}. Exactly what it would read: ${readLogPath(now)}`;
268
+ }
269
+ if (!opts.force && !windowActive(now))
270
+ return 'No active 5-hour window: reading now would start one. It runs after your next away, or add --force.';
271
+ if (!claudeAvailable(config.claudeBin))
272
+ return `Can't find Claude Code (\`${config.claudeBin}\`).`;
273
+ const r = await dream(new ClaudeRunner(config.claudeBin), { model: config.dreamModel, now, sinceMs: opts.sinceMs });
274
+ const lines = [formatDream(r, config.dreamModel)];
275
+ if (r.signals)
276
+ lines.push(`Taste: ${await distillNow(new Date(), true)}`);
277
+ lines.push(`What it read: ${readLogPath(now)}`);
278
+ return lines.join('\n');
279
+ }
280
+ /** Distil taste from new signals, but only inside an active window (a model call would otherwise start one). */
281
+ async function distillNow(now, force = false) {
282
+ const config = loadConfig();
283
+ if (!force && !windowActive(now))
284
+ return 'No active 5-hour window: distilling now would start one. It runs after your next away, or add --force.';
285
+ if (!claudeAvailable(config.claudeBin))
286
+ return `Can't find Claude Code (\`${config.claudeBin}\`).`;
287
+ const r = await distill(loadBoard(), new ClaudeRunner(config.claudeBin), { model: config.distillModel, cwd: chompyyHome(), now });
288
+ if (!r.read)
289
+ return 'No new signals to learn from.';
290
+ const c = r.changes;
291
+ const parts = [`${c.added.length} new`, `${c.extended.length} with more evidence`, `${c.ready.length} ready to ask`, `${c.retired.length} retired`];
292
+ return `Read ${r.read} new signal(s): ${parts.join(', ')}${c.dropped ? ` (${c.dropped} thrown out for weak evidence)` : ''}. See \`chompyy taste list\`.`;
293
+ }
294
+ /** Keep a card: merge it, record it, update the live app, and bring the other cards in review up to date. */
295
+ function keepNow(id, now) {
296
+ const kept = getCard(loadBoard(), id);
297
+ console.log(keepCard(kept));
298
+ updateBoard((b) => {
299
+ const card = getCard(b, id);
300
+ card.outcome = 'kept';
301
+ card.column = 'done';
302
+ delete card.keepWhenRefreshed;
303
+ card.updatedAt = now.toISOString();
304
+ recordOutcome(card, 'kept', now);
305
+ return card;
306
+ });
307
+ // If this landed on what the app runs from, bring the app up to date by itself (live.ts).
308
+ const landedOn = kept.run?.base?.branch ?? currentBranch(kept.cwd);
309
+ if (keepAffectsLive(loadLive(), kept.cwd, landedOn)) {
310
+ startLiveUpdate();
311
+ console.log('Updating the app with it in the background: the CLI in seconds, the Mac app in 1–2 minutes if its code changed (`chompyy live` shows progress).');
312
+ }
313
+ // Main moved: cards still in review may clash with it now. Checking each one costs git time per card, so
314
+ // that happens in the background job that also brings them up to date (refresh.ts); Keep returns at once.
315
+ const waiting = loadBoard().cards.filter((c) => c.id !== id && c.column === 'review' && c.run?.branch);
316
+ if (waiting.length) {
317
+ startBackground(['refresh', '--clashing'], 'refresh.log');
318
+ console.log(`Checking ${waiting.map((c) => '#' + c.id).join(', ')} against it in the background; any that clash get brought up to date.`);
319
+ }
320
+ }
321
+ /** Run a chompyy command in the background, detached, so it outlives this process (and an app restart). */
322
+ function startBackground(args, logName) {
323
+ const out = openSync(homePath(logName), 'a');
324
+ spawn(process.execPath, [process.argv[1], ...args], { detached: true, stdio: ['ignore', out, out] }).unref();
325
+ closeSync(out);
326
+ }
327
+ function refreshDeps(config, freshQuota) {
328
+ const a = awayDeps(config, freshQuota);
329
+ return {
330
+ runner: a.runner,
331
+ config,
332
+ now: () => new Date(),
333
+ snapshot: loadSnapshot,
334
+ out: (line) => console.log(`${new Date().toISOString().slice(0, 16)} ${line}`),
335
+ ...(a.verify ? { verify: a.verify } : {}),
336
+ ...(a.repoChecks ? { repoChecks: a.repoChecks } : {}),
337
+ keep: (id) => keepNow(id, new Date()),
338
+ };
339
+ }
340
+ /** An away run: one at a time (lock), then distil what the run taught, if anything. */
341
+ /** What an away run (and each card's worker) needs from the real world. */
342
+ function awayDeps(config, freshQuota) {
343
+ return {
344
+ runner: new ClaudeRunner(config.claudeBin),
345
+ config,
346
+ now: () => Date.now(),
347
+ snapshot: loadSnapshot,
348
+ plan: planWorkspace,
349
+ prepare: prepareWorkspace,
350
+ commitLeftovers,
351
+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms))),
352
+ recordNeeds: (card, needs) => {
353
+ const root = gitRoot(card.cwd);
354
+ if (!root)
355
+ return;
356
+ const p = loadProfile(root) ?? { root, checks: [], updatedAt: new Date().toISOString() };
357
+ saveProfile({ ...p, needs: recordNeeds(p.needs ?? [], needs, card.id, new Date().toISOString()) });
358
+ },
359
+ repoChecks: (card) => {
360
+ const root = gitRoot(card.cwd);
361
+ const p = root ? loadProfile(root) : null;
362
+ return (p?.preflight?.results ?? []).filter((r) => r.verdict === 'ready').map((r) => ({ dir: r.check.dir, label: r.check.label }));
363
+ },
364
+ refreshQuota: async () => {
365
+ await freshQuota(true);
366
+ },
367
+ ...(config.independentCheck
368
+ ? {
369
+ verify: async (ws, card) => {
370
+ // Chompyy's own measurement: the repo's checks on the card and on the main it started from.
371
+ const root = gitRoot(card.cwd);
372
+ const cacheDir = homePath('cache', 'tools');
373
+ if (!root || ws.kind !== 'worktree')
374
+ return undefined;
375
+ const baseCommit = ws.base?.commit ?? execFileSync('git', ['-C', root, 'merge-base', 'HEAD', ws.branch], { encoding: 'utf8' }).trim();
376
+ return verifyCard({ root, dir: ws.dir, baseCommit, cacheDir, denyRead: config.denyReadPaths, timeoutMs: config.checkTimeoutMin * 60_000, now: () => new Date() });
377
+ },
378
+ }
379
+ : {}),
380
+ out: (line) => console.log(line),
381
+ };
382
+ }
383
+ /** The supervisor's side of a worker: run `chompyy run-card` and wait, killing it if it outlives its card. */
384
+ function isolateCard(config) {
385
+ return (id, timeoutMs, trigger) => new Promise((resolve) => {
386
+ const args = [process.argv[1], 'run-card', id, '--timeout', String(timeoutMs), ...(trigger ? ['--trigger', trigger] : [])];
387
+ const child = spawn(process.execPath, args, { stdio: ['ignore', 'inherit', 'pipe'], env: process.env });
388
+ const stderr = new CappedText(64 * 1024);
389
+ child.stderr.setEncoding('utf8');
390
+ child.stderr.on('data', (d) => {
391
+ stderr.push(d);
392
+ process.stderr.write(d);
393
+ });
394
+ // Watchdog: the card's cap, plus time for the independent check and committing, plus a margin.
395
+ const limit = timeoutMs + (config.independentCheck ? config.checkTimeoutMin * 60_000 : 0) + 5 * 60_000;
396
+ const dog = setTimeout(() => {
397
+ child.kill('SIGTERM'); // the worker stops its agent's process group on SIGTERM
398
+ setTimeout(() => child.kill('SIGKILL'), 10_000).unref();
399
+ }, limit);
400
+ child.on('close', (code, signal) => {
401
+ clearTimeout(dog);
402
+ resolve({ exitCode: code, signal, stderr: stderr.toString() });
403
+ });
404
+ child.on('error', (err) => {
405
+ clearTimeout(dog);
406
+ resolve({ exitCode: null, signal: null, stderr: String(err) });
407
+ });
408
+ });
409
+ }
410
+ async function runAway(ms, opts, now, freshQuota) {
411
+ const config = loadConfig();
412
+ const release = opts.dryRun ? () => { } : takeAwayLock(now, opts.trigger ?? 'away');
413
+ try {
414
+ await away(ms, { ...awayDeps(config, freshQuota), isolate: isolateCard(config) }, opts);
415
+ }
416
+ finally {
417
+ release();
418
+ }
419
+ // After the cards (they come first): the nightly read of your everyday sessions, once a day.
420
+ if (!opts.dryRun && config.dream && dreamDue(new Date())) {
421
+ try {
422
+ console.log(`Nightly read: ${await dreamNow(new Date())}`);
423
+ }
424
+ catch (err) {
425
+ console.log(`Nightly read: couldn't run (${err instanceof Error ? err.message : err})`);
426
+ }
427
+ }
428
+ if (!opts.dryRun && config.distillAfterAway && distillDue(loadBoard(), new Date(), 0)) {
429
+ try {
430
+ console.log(`Taste: ${await distillNow(new Date())}`);
431
+ }
432
+ catch (err) {
433
+ console.log(`Taste: couldn't distil (${err instanceof Error ? err.message : err})`);
434
+ }
435
+ }
436
+ }
142
437
  async function main(argv) {
143
438
  const { values, positionals } = parseArgs({
144
439
  args: argv,
145
440
  allowPositionals: true,
146
441
  options: {
147
442
  'no-blueprint': { type: 'boolean' },
443
+ 'all-later': { type: 'boolean' },
444
+ clashing: { type: 'boolean' },
148
445
  wait: { type: 'boolean' },
149
446
  'dry-run': { type: 'boolean' },
150
447
  force: { type: 'boolean' },
@@ -155,7 +452,20 @@ async function main(argv) {
155
452
  help: { type: 'boolean', short: 'h' },
156
453
  json: { type: 'boolean' },
157
454
  refresh: { type: 'boolean' },
455
+ 'allow-keychain': { type: 'boolean' },
456
+ 'no-keychain': { type: 'boolean' },
158
457
  'to-five': { type: 'string', multiple: true },
458
+ digest: { type: 'boolean' },
459
+ taste: { type: 'string' },
460
+ cards: { type: 'string' },
461
+ ref: { type: 'string' },
462
+ allow: { type: 'string', multiple: true },
463
+ timeout: { type: 'string' },
464
+ trigger: { type: 'string' },
465
+ since: { type: 'string' },
466
+ days: { type: 'string' },
467
+ app: { type: 'boolean' },
468
+ period: { type: 'string' },
159
469
  },
160
470
  });
161
471
  const [command, ...args] = values.help ? ["help"] : positionals;
@@ -168,7 +478,8 @@ async function main(argv) {
168
478
  if (loadConfig().quotaSource !== 'api')
169
479
  return null;
170
480
  try {
171
- return await refreshLiveQuota({ force });
481
+ const config = loadConfig();
482
+ return await refreshLiveQuota({ force, allowKeychain: keychainAllowed(config), keychainOff: config.allowKeychain === false });
172
483
  }
173
484
  catch {
174
485
  return null;
@@ -181,7 +492,7 @@ async function main(argv) {
181
492
  const parsed = parseStatusline(await readStdin(), now);
182
493
  const snap = mergeSnapshot(loadSnapshot(), { ...parsed, ...(parsed.fiveHour || parsed.sevenDay ? { source: 'statusline' } : {}) });
183
494
  saveSnapshot(snap);
184
- console.log(statusLineText(snap, now));
495
+ console.log(statusLineText(snap, now, { samples: loadSamples(), color: true }));
185
496
  }
186
497
  catch {
187
498
  console.log('🍪');
@@ -197,7 +508,11 @@ async function main(argv) {
197
508
  return;
198
509
  }
199
510
  case 'quota': {
200
- const r = await freshQuota(Boolean(values.refresh));
511
+ if (values['allow-keychain'])
512
+ setConfig('allowKeychain', true);
513
+ if (values['no-keychain'])
514
+ setConfig('allowKeychain', false);
515
+ const r = await freshQuota(Boolean(values.refresh || values['allow-keychain']));
201
516
  if (r)
202
517
  console.log(r.message);
203
518
  else if (loadConfig().quotaSource !== 'api')
@@ -206,9 +521,36 @@ async function main(argv) {
206
521
  return;
207
522
  }
208
523
  case 'state': {
209
- await freshQuota(Boolean(values.refresh));
524
+ const refreshed = await freshQuota(Boolean(values.refresh));
210
525
  draftPending(now);
211
- return json(appState(loadBoard(), loadSnapshot(), loadConfig(), now));
526
+ // A card left in running by an away run that died shouldn't look like it's still working.
527
+ if (!awayRunning() && loadBoard().cards.some((c) => c.column === 'running'))
528
+ updateBoard((b) => recoverRunning(b, now, planWorkspace));
529
+ // What the quota check just did, so the app's Refresh button can say it instead of looking dead.
530
+ const quotaRefresh = values.refresh ? (refreshed ? { ok: refreshed.ok, message: refreshed.message } : { ok: false, message: 'Live quota reading is off (quotaSource in config.json).' }) : null;
531
+ return json({ ...appState(loadBoard(), loadSnapshot(), loadConfig(), now), quotaRefresh });
532
+ }
533
+ case 'live': {
534
+ const sub = args[0] ?? 'status';
535
+ if (sub === 'set') {
536
+ const live = liveSet(need(args[1], 'chompyy live set <your Chompyy checkout> [branch]'), args[2] ?? 'main');
537
+ console.log(`Live copy at ${live.dir}, following ${live.branch}. Building it now…`);
538
+ liveUpdateLocked();
539
+ return console.log(formatLive(loadLive()));
540
+ }
541
+ if (sub === 'off') {
542
+ liveOff();
543
+ return console.log('The app no longer follows the live copy; it uses whichever chompyy CLI runs next.');
544
+ }
545
+ if (sub === 'update') {
546
+ const state = liveUpdateLocked();
547
+ if (!state)
548
+ console.log('An update is already running; it will pick up the newest main when it finishes.');
549
+ if (state?.error)
550
+ process.exitCode = 1;
551
+ return;
552
+ }
553
+ return console.log(formatLive(loadLive()));
212
554
  }
213
555
  case 'app': {
214
556
  console.log(`Downloading Chompyy ${cliVersion()} for Mac…`);
@@ -216,6 +558,72 @@ async function main(argv) {
216
558
  console.log(`Installed ${at} and opened it. Look for the cookie in your menu bar.`);
217
559
  return;
218
560
  }
561
+ case 'history': {
562
+ const scan = scanHistory();
563
+ if (values.digest)
564
+ return console.log(buildDigest(scan.sessions).text || '(nothing to read)');
565
+ const { included, text } = buildDigest(scan.sessions);
566
+ const retention = historyRetention();
567
+ const projects = [...new Set(scan.sessions.map((s) => s.project))];
568
+ const info = {
569
+ sessions: scan.sessions.length,
570
+ projects: projects.length,
571
+ projectNames: projects.map((p) => p.split('/').pop()),
572
+ from: scan.from,
573
+ to: scan.to,
574
+ skipped: scan.skipped,
575
+ digest: { sessions: included.length, chars: text.length },
576
+ retention,
577
+ };
578
+ if (values.json)
579
+ return json(info);
580
+ console.log(`${info.sessions} interactive sessions in ${info.projects} projects, ${(scan.from ?? '').slice(0, 10)} to ${(scan.to ?? '').slice(0, 10)}`);
581
+ console.log(`Skipped: ${scan.skipped.headless} headless runs, ${scan.skipped.temp} in temp folders, ${scan.skipped.empty} empty`);
582
+ console.log(`Would send: the newest ${included.length} sessions, ${text.length} characters (see it: chompyy history --digest)`);
583
+ console.log(`Claude Code keeps transcripts ${retention.days} days${retention.isDefault ? ' (default; raise it with chompyy keep-history 365)' : ''}`);
584
+ return;
585
+ }
586
+ case 'coldstart': {
587
+ const sub = args[0];
588
+ if (sub === 'show') {
589
+ const cs = loadColdStart();
590
+ if (values.json)
591
+ return json(cs);
592
+ return console.log(cs ? formatColdStart(cs) : 'No cold start yet. Run `chompyy coldstart`.');
593
+ }
594
+ if (sub === 'accept') {
595
+ const list = (v) => (v ?? '').split(',').map((x) => x.trim()).filter(Boolean);
596
+ const r = acceptColdStart({ taste: list(values.taste), cards: list(values.cards) }, now);
597
+ if (values.json)
598
+ return json(r);
599
+ console.log(`Added ${r.taste.length} taste line(s) to taste.md and ${r.cards.length} card(s) to suggested${r.cards.length ? ` (${r.cards.map((c) => `#${c.id}`).join(', ')})` : ''}.`);
600
+ draftPending(now);
601
+ return;
602
+ }
603
+ if (sub === 'forget')
604
+ return console.log(forgetColdStart() ? 'Forgot the cold start proposals. Accepted taste lines stay in taste.md.' : 'Nothing to forget.');
605
+ if (sub)
606
+ throw new Error('Usage: chompyy coldstart [show|accept|forget]');
607
+ await freshQuota();
608
+ if (!values.force && !windowActive(now))
609
+ throw new Error('No active 5-hour window: reading your history would start one. Try again while you are using Claude Code, or add --force.');
610
+ const config = loadConfig();
611
+ if (!claudeAvailable(config.claudeBin))
612
+ throw new Error(`Can't find Claude Code (\`${config.claudeBin}\`).`);
613
+ const cs = await runColdStart(scanHistory(), new ClaudeRunner(config.claudeBin), { model: config.coldStartModel, cwd: chompyyHome(), now, existing: loadBoard().cards.map((c) => c.title) });
614
+ if (values.json)
615
+ return json(cs);
616
+ console.log(formatColdStart(cs));
617
+ return;
618
+ }
619
+ case 'keep-history': {
620
+ const days = Number(need(args[0], 'chompyy keep-history <days>'));
621
+ if (!Number.isInteger(days) || days < 1)
622
+ throw new Error('Days must be a whole number, e.g. 365.');
623
+ const r = keepHistory(days);
624
+ console.log(`Claude Code now keeps transcripts for ${days} days (was ${r.before ?? '30, the default'}). Changed ${r.path}.`);
625
+ return;
626
+ }
219
627
  case 'version':
220
628
  console.log(cliVersion());
221
629
  return;
@@ -262,8 +670,13 @@ async function main(argv) {
262
670
  });
263
671
  if (values.json)
264
672
  return json(items.reverse());
265
- for (const s of items)
673
+ for (const s of items) {
674
+ if (s.kind === 'coldstart') {
675
+ console.log(`${s.at.slice(0, 16)} coldstart kept: ${[...s.accepted.taste, ...s.accepted.cards].join('; ') || '-'} left out: ${[...s.declined.taste, ...s.declined.cards].join('; ') || '-'}`);
676
+ continue;
677
+ }
266
678
  console.log(`${s.at.slice(0, 16)} #${s.card} ${s.kind ?? 'rating'} ${s.rating ? `${s.rating}/5 ` : ''}${s.reason ?? s.text ?? ''}${s.toFive ? ` → to make it a 5: ${s.toFive.join('; ')}` : ''}`);
679
+ }
267
680
  return;
268
681
  }
269
682
  case 'edit-blueprint': {
@@ -273,6 +686,15 @@ async function main(argv) {
273
686
  console.log(`✏️ #${card.id} blueprint updated.`);
274
687
  return;
275
688
  }
689
+ case 'edit-idea': {
690
+ const id = need(args[0], 'chompyy edit-idea <id> (new idea on stdin)');
691
+ const text = await readStdin();
692
+ const card = updateBoard((b) => editIdea(b, id, text, now));
693
+ console.log(`✏️ #${card.id} idea updated: ${card.title}`);
694
+ if (card.blueprint)
695
+ console.log(` Its blueprint was drafted from the old idea; redraft with: chompyy blueprint ${card.id}`);
696
+ return;
697
+ }
276
698
  case 'answer': {
277
699
  const id = need(args[0], 'chompyy answer <id> (answers on stdin)');
278
700
  const text = args.slice(1).join(' ').trim() || (await readStdin());
@@ -290,6 +712,7 @@ async function main(argv) {
290
712
  return;
291
713
  }
292
714
  const eligible = loadBoard().cards.filter((card) => card.column === 'approved' || card.column === 'later');
715
+ const runs = readRuns();
293
716
  if (!eligible.length) {
294
717
  console.log('\nNo cards to consider. Park an idea with `chompyy later "<idea>"`.');
295
718
  return;
@@ -300,13 +723,14 @@ async function main(argv) {
300
723
  console.log(` #${card.id} ${card.title} [${state}]`);
301
724
  if (card.column === 'later' && !card.blueprint?.trim())
302
725
  console.log(' blueprint needed before approval');
726
+ console.log(` ${formatCostRange(costRange(card, runs))}`);
303
727
  }
304
728
  console.log('\nThis is a read-only list. Start selected work with `chompyy away <duration>`.');
305
729
  return;
306
730
  }
307
731
  case 'later': {
308
732
  const idea = need(args.join(' ').trim(), 'chompyy later "<idea>"');
309
- const card = updateBoard((b) => addCard(b, idea, process.cwd(), now));
733
+ const card = updateBoard((b) => addCard(b, idea, process.cwd(), now, 'later', branchOf(process.cwd())));
310
734
  console.log(`📥 #${card.id} parked in later: ${card.title}`);
311
735
  if (values['no-blueprint']) {
312
736
  updateBoard((b) => {
@@ -332,6 +756,14 @@ async function main(argv) {
332
756
  console.log(' the blueprint waits until your 5-hour window is active (drafting now would start a new window)');
333
757
  return;
334
758
  }
759
+ const waiting = quotaEmpty(now);
760
+ if (waiting) {
761
+ updateBoard((b) => {
762
+ getCard(b, card.id).blueprintWaiting = waiting;
763
+ });
764
+ console.log(` ${waiting}`);
765
+ return;
766
+ }
335
767
  updateBoard((b) => {
336
768
  getCard(b, card.id).draftingAt = now.toISOString();
337
769
  });
@@ -354,9 +786,93 @@ async function main(argv) {
354
786
  if (values.json)
355
787
  return json(cardView(card));
356
788
  console.log(formatCard(card));
789
+ if (!card.run)
790
+ console.log(`\n${formatCostRange(costRange(card, readRuns()))}`);
791
+ else if (card.run.cost?.fiveHourPct != null)
792
+ console.log(`used ${card.run.cost.fiveHourPct}% of the 5h window${card.run.trigger ? ` · started by the ${card.run.trigger} trigger` : ''}`);
793
+ return;
794
+ }
795
+ case 'tokens': {
796
+ // Exact tokens per run (tokens.ts). Runs from before 2026-11-19 are filled in from their saved stream logs.
797
+ const filled = backfillTokens();
798
+ const rows = readRuns().filter((r) => r.tokens);
799
+ if (values.json)
800
+ return json(rows.map((r) => ({ at: r.at, card: r.card, title: r.title, status: r.status, ...r.tokens })));
801
+ if (filled)
802
+ console.log(`Filled in exact tokens for ${filled} earlier run(s) from their logs.\n`);
803
+ if (!rows.length)
804
+ return console.log('No runs with exact token counts yet: they are recorded from the next away run on.');
805
+ for (const r of rows.slice(-20))
806
+ console.log(`${r.at.slice(0, 16).replace('T', ' ')} #${r.card.padEnd(4)} ${formatTokens(r.tokens)}\n ${r.title}`);
807
+ const sum = rows.reduce((a, r) => a + r.tokens.costUsd, 0);
808
+ const all = rows.reduce((a, r) => a + totalTokens(r.tokens), 0);
809
+ console.log(`\n${rows.length} run(s): ${compact(all)} tokens, $${sum.toFixed(2)} at API prices (median $${median(rows.map((r) => r.tokens.costUsd)).toFixed(2)} per run)`);
810
+ return;
811
+ }
812
+ case 'picture': {
813
+ const id = need(args[0], 'chompyy picture <id> [--model sonnet]');
814
+ await freshQuota();
815
+ if (!values.force && !windowActive(now))
816
+ throw new Error('No active 5-hour window: drawing would start one. Add --force to draw anyway.');
817
+ const path = await pictureCard(id, values.model);
818
+ if (!values.quiet)
819
+ console.log(`Drew the picture for #${id}: ${path}`);
357
820
  return;
358
821
  }
359
822
  case 'blueprint': {
823
+ if (values['all-later']) {
824
+ await freshQuota();
825
+ if (!claudeAvailable(loadConfig().claudeBin))
826
+ throw new Error('claude CLI not found: drafting needs it.');
827
+ // Same rule as background drafting (card #20): with 0% left, every draft would only hit the limit.
828
+ const waiting = quotaEmpty(now);
829
+ if (waiting) {
830
+ updateBoard((b) => claimDrafts(b, now, waiting)); // marks the later cards "waiting for quota"
831
+ console.log(`Nothing drafted: ${waiting}. They draft on their own once quota is back.`);
832
+ return;
833
+ }
834
+ const plan = draftAllPlan(loadBoard(), windowActive(now), now);
835
+ if (!plan.ids.length) {
836
+ console.log(plan.message);
837
+ return;
838
+ }
839
+ // Mark them all first so background drafting and the app don't start a second draft of the same card.
840
+ updateBoard((b) => {
841
+ for (const id of plan.ids)
842
+ getCard(b, id).draftingAt = new Date().toISOString();
843
+ });
844
+ const failed = [];
845
+ for (const [i, id] of plan.ids.entries()) {
846
+ updateBoard((b) => {
847
+ getCard(b, id).draftingAt = new Date().toISOString(); // fresh, so a long queue doesn't look stale
848
+ });
849
+ if (!values.quiet)
850
+ console.log(`Drafting #${id} (${i + 1} of ${plan.ids.length})…`);
851
+ try {
852
+ await blueprintCard(id, values.model); // a failure is kept on the card as blueprintError
853
+ }
854
+ catch (err) {
855
+ const message = err instanceof Error ? err.message : String(err);
856
+ if (isUsageLimit(message)) {
857
+ // Out of quota mid-way: the rest would fail the same way. They wait for the reset instead (card #20).
858
+ const left = plan.ids.slice(i + 1);
859
+ updateBoard((b) => { for (const l of left)
860
+ delete getCard(b, l).draftingAt; claimDrafts(b, new Date(), quotaEmpty(new Date()) ?? 'waiting for quota: the usage limit was hit'); });
861
+ console.log(`Drafted ${i} of ${plan.ids.length}: the usage limit was hit at #${id}. The rest draft on their own once quota is back.`);
862
+ process.exitCode = i === 0 ? 1 : 0;
863
+ return;
864
+ }
865
+ failed.push(id);
866
+ if (!values.quiet)
867
+ console.log(` #${id} failed: ${message}`);
868
+ }
869
+ }
870
+ const done = plan.ids.length - failed.length;
871
+ console.log(`Drafted ${done} of ${plan.ids.length} blueprint${plan.ids.length === 1 ? '' : 's'}${failed.length ? `; failed: ${failed.map((f) => '#' + f).join(', ')} (see each card)` : ''}.`);
872
+ if (done === 0)
873
+ process.exitCode = 1;
874
+ return;
875
+ }
360
876
  const id = need(args[0], 'chompyy blueprint <id> [--model haiku]');
361
877
  const text = await blueprintCard(id, values.model);
362
878
  if (!values.quiet)
@@ -364,8 +880,24 @@ async function main(argv) {
364
880
  return;
365
881
  }
366
882
  case 'approve': {
367
- const card = updateBoard((b) => moveCard(b, need(args[0], 'chompyy approve <id>'), 'approved', now));
368
- console.log(`✅ #${card.id} approved: ${card.title}`);
883
+ const id = need(args[0], 'chompyy approve <id> [--allow network:host] [--allow "command:swiftc *"]');
884
+ // The permission plan: what you allow here is all the run gets beyond the box's defaults (none by default).
885
+ const allow = values.allow ?? [];
886
+ const bad = allow.filter((a) => !parsePermission(a));
887
+ if (bad.length)
888
+ throw new Error(`Not a permission: ${bad.join(', ')}. Use network:<domain> or "command:<program> *".`);
889
+ const card = updateBoard((b) => {
890
+ const c = moveCard(b, id, 'approved', now);
891
+ if (allow.length)
892
+ c.permissions = [...new Set(allow)];
893
+ else
894
+ delete c.permissions;
895
+ return c;
896
+ });
897
+ console.log(`✅ #${card.id} approved: ${card.title}${card.permissions?.length ? `\n allowed: ${card.permissions.join(', ')}` : ''}`);
898
+ for (const o of overlaps(card, loadBoard().cards)) {
899
+ console.log(` ⚠️ #${o.id} "${o.title}" may touch the same files (${o.files.slice(0, 3).join(', ')}). Keeping both can conflict; Run again fixes that.`);
900
+ }
369
901
  return;
370
902
  }
371
903
  case 'drop': {
@@ -373,6 +905,28 @@ async function main(argv) {
373
905
  console.log(`🗑 #${card.id} dropped: ${card.title}`);
374
906
  return;
375
907
  }
908
+ case 'preflight': {
909
+ // Run the repo's checks on clean latest main, in the away box and outside it (research/away-readiness.md).
910
+ const root = gitRoot(args[0] ?? process.cwd());
911
+ if (!root)
912
+ throw new Error('Not in a git repo. Usage: chompyy preflight [path-to-repo]');
913
+ const config = loadConfig();
914
+ console.log(`Checking ${root} on its latest main, in the away box and outside it…`);
915
+ const result = await preflight(root, { cacheDir: homePath('cache', 'tools'), denyRead: config.denyReadPaths, timeoutMs: config.checkTimeoutMin * 60_000, ...(values.ref ? { ref: values.ref } : {}) });
916
+ const before = loadProfile(root);
917
+ saveProfile({ root, checks: result.results.map((r) => r.check), updatedAt: result.at, preflight: result, ...(before?.needs ? { needs: before.needs } : {}) });
918
+ if (values.json)
919
+ return json(result);
920
+ console.log(formatPreflight(result));
921
+ return;
922
+ }
923
+ case 'run-card': {
924
+ // A worker started by an away run: one card in its own process, so a crash ends only this card.
925
+ const id = need(args[0], 'chompyy run-card <id> --timeout <ms>');
926
+ const config = loadConfig();
927
+ await runCard(id, Number(values.timeout) || config.cardTimeoutMin * 60_000, awayDeps(config, freshQuota), values.trigger);
928
+ return;
929
+ }
376
930
  case 'away': {
377
931
  const ms = parseDuration(need(args[0], 'chompyy away <1h|30m> [--dry-run] [--force]'));
378
932
  const config = loadConfig();
@@ -380,24 +934,178 @@ async function main(argv) {
380
934
  const gate = budgetGate(loadSnapshot(), config, now);
381
935
  console.log(statusText(loadSnapshot(), now));
382
936
  console.log(`gate ${gate.ok ? 'open' : values.force ? 'closed, forced open' : 'closed'}${[...gate.reasons, ...gate.notes].map((r) => `\n · ${r}`).join('')}\n`);
383
- await away(ms, {
384
- runner: new ClaudeRunner(config.claudeBin),
385
- config,
386
- now: () => Date.now(),
387
- snapshot: loadSnapshot,
388
- plan: planWorkspace,
389
- prepare: prepareWorkspace,
390
- commitLeftovers,
391
- refreshQuota: async () => {
392
- await freshQuota(true);
393
- },
394
- out: (line) => console.log(line),
395
- }, { dryRun: values['dry-run'], force: values.force });
937
+ await runAway(ms, { dryRun: values['dry-run'], force: values.force }, now, freshQuota);
938
+ return;
939
+ }
940
+ case 'tick': {
941
+ // Run by the LaunchAgent every 5 minutes. Prints one line per tick to tick.log.
942
+ await freshQuota();
943
+ const config = loadConfig();
944
+ const board = loadBoard();
945
+ // Refreshes that waited for quota (refresh.ts) go as soon as there is some again.
946
+ if (board.cards.some((c) => c.column === 'review' && c.refresh?.state === 'waiting') && !refreshGate(loadSnapshot(), now)) {
947
+ await withRefreshLock(() => refreshClashing(refreshDeps(config, freshQuota)));
948
+ }
949
+ const d = decideTrigger(now, loadSnapshot(), config, loadTriggerState().fired, awayQueue(board).length, Boolean(awayRunning()));
950
+ const stamp = now.toISOString().slice(0, 16);
951
+ if (!d.fire) {
952
+ noteTick(now, d.why);
953
+ // Nightly consolidation: at bedtime, distil taste even when no card runs.
954
+ if (config.bedtime && config.dream && bedtimeKey(now, config.bedtime, config.bedtimeWindowMin) && !awayRunning() && windowActive(now) && dreamDue(now)) {
955
+ console.log(`${stamp} bedtime · nightly read: ${await dreamNow(now).catch((e) => String(e))}`);
956
+ }
957
+ else if (config.bedtime && bedtimeKey(now, config.bedtime, config.bedtimeWindowMin) && !awayRunning() && windowActive(now) && distillDue(board, now, 12 * 3600_000)) {
958
+ console.log(`${stamp} bedtime · taste: ${await distillNow(now).catch((e) => String(e))}`);
959
+ }
960
+ else if (values.json || process.stdout.isTTY)
961
+ console.log(`${stamp} ${d.why}`);
962
+ return;
963
+ }
964
+ markFired(d.key, now, d.why);
965
+ console.log(`${stamp} ▶ ${d.why}: away for ${formatDuration(d.durationMs)}`);
966
+ await runAway(d.durationMs, { trigger: d.kind }, now, freshQuota);
967
+ return;
968
+ }
969
+ case 'triggers': {
970
+ const sub = args[0];
971
+ if (sub === 'on') {
972
+ const path = installAgent();
973
+ const c = loadConfig();
974
+ console.log(`Triggers on: ${path} runs \`chompyy tick\` every 5 minutes.`);
975
+ console.log(` last hour before a reset: ${c.lastHourTrigger ? `on (with ≥${c.lastHourMinLeftPct}% left)` : 'off'} · bedtime: ${c.bedtime ?? 'not set (chompyy bedtime 23:30)'} · missed reset: ${c.missedReset ? 'on' : 'off'}`);
976
+ return;
977
+ }
978
+ if (sub === 'off')
979
+ return console.log(uninstallAgent() ? 'Triggers off: removed the LaunchAgent.' : 'Triggers were already off.');
980
+ if (sub)
981
+ throw new Error('Usage: chompyy triggers [on|off]');
982
+ const c = loadConfig();
983
+ const st = loadTriggerState();
984
+ if (values.json)
985
+ return json({ installed: agentInstalled(), lastHour: c.lastHourTrigger, lastHourMinLeftPct: c.lastHourMinLeftPct, bedtime: c.bedtime, missedReset: c.missedReset, ...st });
986
+ console.log(`LaunchAgent ${agentInstalled() ? 'on (every 5 minutes)' : 'off (turn on: chompyy triggers on)'}`);
987
+ console.log(`last hour ${c.lastHourTrigger ? `on, with ≥${c.lastHourMinLeftPct}% of the window left` : 'off'}`);
988
+ console.log(`bedtime ${c.bedtime ?? 'not set'}`);
989
+ console.log(`missed reset ${c.missedReset ? 'on, approved cards run on the first tick after an unused reset' : 'off'}`);
990
+ if (st.lastTickAt)
991
+ console.log(`last tick ${st.lastTickAt.slice(0, 16).replace('T', ' ')}: ${st.lastDecision ?? ''}`);
992
+ return;
993
+ }
994
+ case 'bedtime': {
995
+ const v = need(args[0], 'chompyy bedtime <23:30|off>');
996
+ if (v === 'off') {
997
+ setConfig('bedtime', null);
998
+ return console.log('Bedtime trigger off.');
999
+ }
1000
+ parseClock(v);
1001
+ setConfig('bedtime', v);
1002
+ console.log(`Bedtime set to ${v}: approved cards run then, with the window that is left.${agentInstalled() ? '' : ' Turn triggers on with `chompyy triggers on`.'}`);
1003
+ return;
1004
+ }
1005
+ case 'plan-price': {
1006
+ const v = need(args[0], 'chompyy plan-price <dollars per month | auto>');
1007
+ const n = Number(v);
1008
+ if (v !== 'auto' && !(Number.isFinite(n) && n > 0))
1009
+ throw new Error('Usage: chompyy plan-price <dollars per month | auto>');
1010
+ setConfig('planPriceUsd', v === 'auto' ? null : n);
1011
+ console.log(v === 'auto' ? 'Plan price: the list price for the plan Chompyy sees.' : `Plan price: $${n} a month.`);
1012
+ return;
1013
+ }
1014
+ case 'last-hour': {
1015
+ const v = need(args[0], 'chompyy last-hour <on|off>');
1016
+ if (v !== 'on' && v !== 'off')
1017
+ throw new Error('Usage: chompyy last-hour <on|off>');
1018
+ setConfig('lastHourTrigger', v === 'on');
1019
+ console.log(`Last-hour trigger ${v}.${v === 'on' && !agentInstalled() ? ' Turn triggers on with `chompyy triggers on`.' : ''}`);
1020
+ return;
1021
+ }
1022
+ case 'missed-reset': {
1023
+ const v = need(args[0], 'chompyy missed-reset <on|off>');
1024
+ if (v !== 'on' && v !== 'off')
1025
+ throw new Error('Usage: chompyy missed-reset <on|off>');
1026
+ setConfig('missedReset', v === 'on');
1027
+ console.log(`Missed-reset trigger ${v}.${v === 'on' ? ` Only cards already approved (chompyy approve) run; the budget gate still decides.${agentInstalled() ? '' : ' Turn triggers on with `chompyy triggers on`.'}` : ''}`);
1028
+ return;
1029
+ }
1030
+ case 'trace': {
1031
+ const q = need(args[0], 'chompyy trace <conversation id> [--json] (ids: chompyy usage --json)');
1032
+ const ticked = new Set(cachedWorkspaces(now).filter((w) => w.ticked).map((w) => w.path));
1033
+ const t = traceSession(q, { showPrompts: (ws) => ticked.has(ws) });
1034
+ if (!t)
1035
+ throw new Error(q.startsWith('chompyy-card-') ? 'Away runs keep no transcript (only their recorded totals, in chompyy usage).' : `No conversation "${q}" on this Mac.`);
1036
+ if (values.json)
1037
+ return json(t);
1038
+ console.log(formatTrace(t));
1039
+ return;
1040
+ }
1041
+ case 'usage': {
1042
+ const period = (values.period ?? '');
1043
+ if (values.period && !PERIODS.includes(period))
1044
+ throw new Error(`Usage: chompyy usage [--period ${PERIODS.join('|')}] [--days 7] [--json]`);
1045
+ const days = period ? periodDays(period, now) : values.days ? Number(values.days) : 7;
1046
+ if (!Number.isInteger(days) || days < 1 || days > 400)
1047
+ throw new Error('Usage: chompyy usage [--period today|7d|30d|month] [--days 7] [--json]');
1048
+ // Titles only for workspaces the nightly read may see (your ticks); numbers count everywhere.
1049
+ const ticked = new Set(cachedWorkspaces(now).filter((w) => w.ticked).map((w) => w.path));
1050
+ const canShow = (ws) => ticked.has(ws);
1051
+ const ledger = loadLedger();
1052
+ const view = usageView(ledger, now, days, 25, canShow);
1053
+ const to = now.toISOString();
1054
+ const cmp = compare(ledger, now, { label: loadLiveState().plan ?? null, priceUsd: loadConfig().planPriceUsd });
1055
+ const kinds = byKind(ledger, view.from, to);
1056
+ const prs = prCosts(ledger, view.from, to, canShow);
1057
+ // For the app: 12 weeks of days (the calendar), this week (the menu bar), the chosen period with kinds of
1058
+ // work and pull requests, and the comparisons, in one call.
1059
+ if (values.json && values.app) {
1060
+ const long = usageView(ledger, now, 84, 0, canShow);
1061
+ const week = usageView(ledger, now, 7, 10, canShow);
1062
+ return json({ generatedAt: to, period: period || `${days}d`, days: long.days, today: long.today, week, view: { ...view, byKind: kinds, prs }, compare: cmp, unpriced: long.unpriced });
1063
+ }
1064
+ if (values.json)
1065
+ return json({ ...view, byKind: kinds, prs, compare: cmp });
1066
+ console.log(formatUsage(view, homedir()));
1067
+ console.log(formatExtras(kinds, prs, cmp));
1068
+ return;
1069
+ }
1070
+ case 'dream': {
1071
+ const sub = args[0];
1072
+ if (sub === 'workspaces') {
1073
+ if (values.json)
1074
+ return json(cachedWorkspaces(now, 0));
1075
+ return console.log(formatWorkspaces(cachedWorkspaces(now, 0)));
1076
+ }
1077
+ if (sub === 'tick' || sub === 'untick') {
1078
+ const w = setTicked(need(args.slice(1).join(' ') || undefined, `chompyy dream ${sub} <folder>`), sub === 'tick', now);
1079
+ return console.log(`${w.ticked ? 'Ticked' : 'Unticked'} ${w.path}: the nightly read ${w.ticked ? 'will learn from' : "won't read"} its sessions.`);
1080
+ }
1081
+ if (sub === 'on' || sub === 'off') {
1082
+ setConfig('dream', sub === 'on');
1083
+ return console.log(`Nightly read ${sub}.`);
1084
+ }
1085
+ if (sub)
1086
+ throw new Error('Usage: chompyy dream [workspaces | tick <folder> | untick <folder> | on | off] [--dry-run] [--force] [--since 7d]');
1087
+ console.log(await dreamNow(now, { force: Boolean(values.force), dryRun: Boolean(values['dry-run']), sinceMs: values.since ? parseDuration(values.since) : undefined }));
1088
+ return;
1089
+ }
1090
+ case 'distill': {
1091
+ console.log(await distillNow(now, Boolean(values.force)));
1092
+ return;
1093
+ }
1094
+ case 'trends': {
1095
+ const lines = trendLines(readRuns(), readSignals(), now);
1096
+ console.log(lines.length ? lines.join('\n') : 'Not enough runs yet for trends (needs 3).');
396
1097
  return;
397
1098
  }
398
1099
  case 'report': {
399
1100
  const since = values.all ? null : lastReportAt();
400
- console.log(formatReport(cardsSince(loadBoard(), since), since, (c) => ({ files: changedFiles(c), questions: questionsOf(c) })));
1101
+ syncTasteFile(now);
1102
+ const cards = cardsSince(loadBoard(), since);
1103
+ const store = loadStore();
1104
+ const signals = readSignals();
1105
+ const morning = morningLine(cards, tasteChangesSince(store, since));
1106
+ const question = nextQuestion(store, signals);
1107
+ const footer = [...(question ? formatQuestion(question, signals) : []), ...trendLines(readRuns(), signals, now)];
1108
+ console.log(formatReport(cards, since, (c) => ({ files: changedFiles(c), questions: questionsOf(c) }), { header: morning ? [morning] : [], footer }));
401
1109
  markReported(now);
402
1110
  return;
403
1111
  }
@@ -407,14 +1115,32 @@ async function main(argv) {
407
1115
  }
408
1116
  case 'keep': {
409
1117
  const id = need(args[0], 'chompyy keep <id>');
410
- console.log(keepCard(getCard(loadBoard(), id)));
411
- updateBoard((b) => {
412
- const card = getCard(b, id);
413
- card.outcome = 'kept';
414
- card.column = 'done';
415
- card.updatedAt = now.toISOString();
416
- return card;
1118
+ const card = getCard(loadBoard(), id);
1119
+ const clash = clashOf(card);
1120
+ if (clash) {
1121
+ // Don't hand the clash to you: Chompyy brings the card onto the new main, checks it, then keeps it (refresh.ts).
1122
+ updateBoard((b) => {
1123
+ getCard(b, id).keepWhenRefreshed = true;
1124
+ });
1125
+ startBackground(['refresh', '--clashing'], 'refresh.log');
1126
+ console.log(`#${id} clashes with ${clash.branch} (${clash.files.join(', ')}): other cards were kept since it ran. Chompyy is bringing it up to date and will keep it once its checks pass.`);
1127
+ return;
1128
+ }
1129
+ keepNow(id, now);
1130
+ return;
1131
+ }
1132
+ case 'refresh': {
1133
+ const config = loadConfig();
1134
+ const deps = refreshDeps(config, freshQuota);
1135
+ await freshQuota();
1136
+ const ran = await withRefreshLock(async () => {
1137
+ if (args[0])
1138
+ await refreshCard(args[0], deps);
1139
+ else
1140
+ await refreshClashing(deps);
417
1141
  });
1142
+ if (!ran)
1143
+ console.log('A refresh is already running; it will go round again to include this.');
418
1144
  return;
419
1145
  }
420
1146
  case 'undo': {
@@ -425,6 +1151,7 @@ async function main(argv) {
425
1151
  card.outcome = 'undone';
426
1152
  card.column = 'done';
427
1153
  card.updatedAt = now.toISOString();
1154
+ recordOutcome(card, 'undone', now);
428
1155
  return card;
429
1156
  });
430
1157
  return;
@@ -459,6 +1186,28 @@ async function main(argv) {
459
1186
  return;
460
1187
  }
461
1188
  case 'taste': {
1189
+ const sub = args[0];
1190
+ const removed = syncTasteFile(now);
1191
+ if (removed.length)
1192
+ console.log(`Retired ${removed.join(', ')}: you removed ${removed.length === 1 ? 'it' : 'them'} from taste.md.\n`);
1193
+ if (sub === 'list') {
1194
+ if (values.json)
1195
+ return json(loadStore());
1196
+ return console.log(formatPrefs(loadStore(), readSignals()));
1197
+ }
1198
+ if (sub === 'why')
1199
+ return console.log(formatWhy(getPref(loadStore(), need(args[1], 'chompyy taste why <id>')), readSignals()));
1200
+ if (sub === 'yes' || sub === 'not-now' || sub === 'never') {
1201
+ const p = answerPreference(need(args[1], `chompyy taste ${sub} <id>`), sub, now);
1202
+ const said = { yes: `✓ Added to taste.md: "${p.text}". Agents follow it from now on.`, 'not-now': `Okay, not now. Chompyy asks again only when there's more evidence.`, never: `🔕 Won't ask about "${p.text}" again.` };
1203
+ return console.log(said[sub]);
1204
+ }
1205
+ if (sub === 'retire') {
1206
+ const p = retirePreference(need(args[1], 'chompyy taste retire <id>'), now);
1207
+ return console.log(`Retired ${p.id}: "${p.text}". It's kept in \`chompyy taste list\` with the reason.`);
1208
+ }
1209
+ if (sub)
1210
+ throw new Error('Usage: chompyy taste [list | why <id> | yes|not-now|never <id> | retire <id>]');
462
1211
  const { path, text, created } = readTaste();
463
1212
  if (created)
464
1213
  console.log(`(created ${path})\n`);