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/macapp.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // `chompyy app`: download the Mac app from this version's GitHub Release into ~/Applications and open it.
2
- // The app is a thin window over this CLI, so the two versions are kept in step.
2
+ // The app is a thin window over this CLI, so the two versions are kept in step. The download is checked against
3
+ // the SHA-256 published next to it, and the app's code signature is checked, before anything is opened (#24).
3
4
  import { execFileSync } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
4
6
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
7
  import { homedir, tmpdir } from 'node:os';
6
8
  import { dirname, join } from 'node:path';
@@ -14,6 +16,13 @@ export function cliVersion() {
14
16
  export function appZipUrl(version) {
15
17
  return `https://github.com/${REPO}/releases/download/v${version}/Chompyy-${version}.zip`;
16
18
  }
19
+ /** The release's checksum file: `<sha256> Chompyy-<version>.zip`, written by mac/Scripts/build-app.sh --release. */
20
+ export const checksumUrl = (version) => `${appZipUrl(version)}.sha256`;
21
+ /** The hash in a `shasum -a 256` line, or null when the text isn't one. */
22
+ export function parseChecksum(text) {
23
+ const m = text.trim().match(/^([0-9a-f]{64})\b/i);
24
+ return m ? m[1].toLowerCase() : null;
25
+ }
17
26
  const defaultDeps = () => ({
18
27
  fetch: (url) => fetch(url),
19
28
  exec: (cmd, args) => {
@@ -31,14 +40,28 @@ export async function installApp(opts = {}, deps = defaultDeps()) {
31
40
  const res = await deps.fetch(url);
32
41
  if (!res.ok)
33
42
  throw new Error(`Couldn't download the app (HTTP ${res.status}) from ${url}`);
43
+ const sumRes = await deps.fetch(checksumUrl(version));
44
+ const want = sumRes.ok ? parseChecksum(Buffer.from(await sumRes.arrayBuffer()).toString('utf8')) : null;
45
+ if (!want)
46
+ throw new Error(`The release has no checksum (${checksumUrl(version)}), so Chompyy won't open its download. Nothing was installed.`);
47
+ const bytes = Buffer.from(await res.arrayBuffer());
48
+ const got = createHash('sha256').update(bytes).digest('hex');
49
+ if (got !== want)
50
+ throw new Error(`The download doesn't match the release's checksum (got ${got.slice(0, 12)}…, expected ${want.slice(0, 12)}…). Nothing was installed.`);
34
51
  const tmp = mkdtempSync(join(tmpdir(), 'chompyy-app-'));
35
52
  try {
36
53
  const zip = join(tmp, 'Chompyy.zip');
37
- writeFileSync(zip, Buffer.from(await res.arrayBuffer()));
54
+ writeFileSync(zip, bytes);
38
55
  deps.exec('ditto', ['-x', '-k', zip, tmp]);
39
56
  const unpacked = join(tmp, 'Chompyy.app');
40
57
  if (!existsSync(unpacked))
41
58
  throw new Error('The download had no Chompyy.app in it.');
59
+ try {
60
+ deps.exec('codesign', ['--verify', '--deep', '--strict', unpacked]);
61
+ }
62
+ catch {
63
+ throw new Error("The app's code signature doesn't check out (codesign --verify), so it wasn't installed.");
64
+ }
42
65
  mkdirSync(deps.appsDir, { recursive: true });
43
66
  const target = join(deps.appsDir, 'Chompyy.app');
44
67
  try {
package/dist/pacing.js ADDED
@@ -0,0 +1,189 @@
1
+ // Pacing (FEATURES §2): how you're spending your windows, at a glance.
2
+ //
3
+ // - Signed pace delta (claude-pace): used % minus the % of the window that has passed. ⇣15% = headroom,
4
+ // ⇡15% = burning faster than an even pace.
5
+ // - Forecast unused at reset (Claude-Code-Usage-Monitor forecasts run-out; we flip it): "~40% resets unused at
6
+ // 18:20" is the moment to offer cards. Frozen once a limit is hit: no projections past 100%.
7
+ // - Rolling daily allowance: today = what's left of the week ÷ days left, where your day ends at bedtime.
8
+ //
9
+ // The burn rate comes from a small history of quota readings (quota-history.json), saved whenever the snapshot
10
+ // changes, so no extra calls are made.
11
+ import { homePath, readJson, writeJson } from './home.js';
12
+ import { windowView } from './quota.js';
13
+ export const FIVE_HOURS = 5 * 3600_000;
14
+ export const WEEK = 7 * 24 * 3600_000;
15
+ const DAY = 24 * 3600_000;
16
+ const historyPath = () => homePath('quota-history.json');
17
+ /** Keep 8 days: enough for a weekly window and the day before it. */
18
+ const KEEP_MS = 8 * DAY;
19
+ /** Save a reading at most this often unless the numbers changed. */
20
+ const MIN_GAP_MS = 5 * 60_000;
21
+ export function loadSamples() {
22
+ return readJson(historyPath(), { samples: [] }).samples;
23
+ }
24
+ const same = (a, b) => a?.usedPct === b?.usedPct && a?.resetsAt === b?.resetsAt;
25
+ /** Add a reading when it says something new. Returns true when saved. */
26
+ export function recordSample(snap, nowMs = Date.parse(snap.capturedAt)) {
27
+ if (!snap.fiveHour && !snap.sevenDay)
28
+ return false;
29
+ const samples = loadSamples();
30
+ const last = samples.at(-1);
31
+ if (last && same(last.five, snap.fiveHour) && same(last.week, snap.sevenDay) && nowMs - last.at < MIN_GAP_MS)
32
+ return false;
33
+ if (last && nowMs < last.at)
34
+ return false; // out of order
35
+ samples.push({ at: nowMs, ...(snap.fiveHour ? { five: snap.fiveHour } : {}), ...(snap.sevenDay ? { week: snap.sevenDay } : {}) });
36
+ writeJson(historyPath(), { samples: samples.filter((s) => s.at > nowMs - KEEP_MS) });
37
+ return true;
38
+ }
39
+ // ---------- pace delta ----------
40
+ /** Used % minus elapsed % of the window. Negative = headroom. Null when the window is unknown or reset. */
41
+ export function paceDelta(w, lengthMs, now) {
42
+ const v = windowView(w, now);
43
+ if (!v.known)
44
+ return null;
45
+ const elapsedPct = Math.min(100, Math.max(0, (1 - v.msLeft / lengthMs) * 100));
46
+ return v.usedPct - elapsedPct;
47
+ }
48
+ const GREEN = '\u001b[32m';
49
+ const RED = '\u001b[31m';
50
+ const RESET = '\u001b[0m';
51
+ /** "⇣15%" (headroom, green) or "⇡15%" (burning fast, red); "±0%" when within a point. */
52
+ export function formatDelta(delta, color = false) {
53
+ if (delta === null)
54
+ return '';
55
+ const n = Math.round(Math.abs(delta));
56
+ if (n < 1)
57
+ return '±0%';
58
+ const text = delta < 0 ? `⇣${n}%` : `⇡${n}%`;
59
+ return color ? `${delta < 0 ? GREEN : RED}${text}${RESET}` : text;
60
+ }
61
+ const RECENT_MS = 60 * 60_000;
62
+ const MIN_SPAN_MS = 10 * 60_000;
63
+ /** % per ms over the last hour of readings in this same window, or null if there aren't enough. */
64
+ export function recentRate(samples, pick, resetsAt, nowMs) {
65
+ const pts = samples.filter((s) => pick(s)?.resetsAt === resetsAt && s.at >= nowMs - RECENT_MS && s.at <= nowMs);
66
+ if (pts.length < 2)
67
+ return null;
68
+ const first = pts[0];
69
+ const last = pts.at(-1);
70
+ if (last.at - first.at < MIN_SPAN_MS)
71
+ return null;
72
+ return Math.max(0, (pick(last).usedPct - pick(first).usedPct) / (last.at - first.at));
73
+ }
74
+ export function forecastWindow(w, lengthMs, samples, pick, now) {
75
+ const v = windowView(w, now);
76
+ if (!v.known)
77
+ return { kind: 'unknown' };
78
+ if (v.usedPct >= 100)
79
+ return { kind: 'limit', resetsAt: v.resetsAt };
80
+ const nowMs = now.getTime();
81
+ let rate = recentRate(samples, pick, v.resetsAt, nowMs);
82
+ let basis = 'recent';
83
+ if (rate === null) {
84
+ const elapsed = lengthMs - v.msLeft;
85
+ if (elapsed < 15 * 60_000)
86
+ return { kind: 'unknown' };
87
+ rate = v.usedPct / elapsed;
88
+ basis = 'average';
89
+ }
90
+ const projected = v.usedPct + rate * v.msLeft;
91
+ if (projected >= 100 && rate > 0)
92
+ return { kind: 'limit-ahead', atMs: nowMs + (100 - v.usedPct) / rate, resetsAt: v.resetsAt };
93
+ return { kind: 'unused', unusedPct: Math.max(0, 100 - projected), resetsAt: v.resetsAt, basis };
94
+ }
95
+ const clock = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
96
+ /** Short, for the status line: "~40% unused at 18:20" · "limit ~17:05" · "limit hit, resets 18:20". */
97
+ export function formatForecastShort(f) {
98
+ switch (f.kind) {
99
+ case 'unused':
100
+ return `~${Math.round(f.unusedPct)}% unused at ${clock(f.resetsAt * 1000)}`;
101
+ case 'limit-ahead':
102
+ return `limit ~${clock(f.atMs)}`;
103
+ case 'limit':
104
+ return `limit hit, resets ${clock(f.resetsAt * 1000)}`;
105
+ default:
106
+ return '';
107
+ }
108
+ }
109
+ export function formatForecast(f) {
110
+ switch (f.kind) {
111
+ case 'unused':
112
+ return `at ${f.basis === 'recent' ? 'your pace over the last hour' : 'your average pace this window'}, ~${Math.round(f.unusedPct)}% of this window resets unused at ${clock(f.resetsAt * 1000)}${f.unusedPct >= 20 ? ' (room for an away card: chompyy eat-tokens)' : ''}`;
113
+ case 'limit-ahead':
114
+ return `at this pace you hit the limit at ~${clock(f.atMs)}, before the reset at ${clock(f.resetsAt * 1000)}`;
115
+ case 'limit':
116
+ return `limit hit; no forecast until it resets at ${clock(f.resetsAt * 1000)}`;
117
+ default:
118
+ return 'not enough readings yet to forecast';
119
+ }
120
+ }
121
+ // ---------- rolling daily allowance ----------
122
+ /** The day you're in: from your last bedtime (or midnight) to the next. */
123
+ export function dayBounds(now, bedtime) {
124
+ const [h, m] = bedtime ? bedtime.split(':').map(Number) : [0, 0];
125
+ const start = new Date(now);
126
+ start.setHours(h, m, 0, 0);
127
+ if (start.getTime() > now.getTime())
128
+ start.setDate(start.getDate() - 1);
129
+ const end = new Date(start);
130
+ end.setDate(end.getDate() + 1); // calendar day, so DST shifts don't move bedtime
131
+ return { start: start.getTime(), end: end.getTime() };
132
+ }
133
+ export function dailyAllowance(w, samples, now, bedtime) {
134
+ const v = windowView(w, now);
135
+ if (!v.known)
136
+ return null;
137
+ const { start, end } = dayBounds(now, bedtime);
138
+ const weekEnd = v.resetsAt * 1000;
139
+ // The weekly window may have started today: then today starts there.
140
+ const dayStart = Math.max(start, weekEnd - WEEK);
141
+ const inWindow = samples.filter((s) => s.week?.resetsAt === v.resetsAt);
142
+ const before = inWindow.filter((s) => s.at <= dayStart).at(-1);
143
+ const after = inWindow.find((s) => s.at > dayStart);
144
+ const approx = !before && !(dayStart > start); // a window that began today started at 0
145
+ const usedAtStart = dayStart > start ? 0 : (before ?? after)?.week?.usedPct ?? v.usedPct;
146
+ const daysLeft = Math.max(1, Math.ceil((weekEnd - dayStart) / DAY - 0.01));
147
+ const allowance = Math.max(0, 100 - usedAtStart) / daysLeft;
148
+ const usedToday = Math.max(0, v.usedPct - usedAtStart);
149
+ const dayEnds = Math.min(end, weekEnd);
150
+ const frac = Math.min(1, Math.max(0, (now.getTime() - dayStart) / Math.max(1, dayEnds - dayStart)));
151
+ const expectedByNow = allowance * frac;
152
+ const slack = Math.max(1, allowance * 0.1);
153
+ const status = usedToday > allowance ? 'over' : usedToday > expectedByNow + slack ? 'ahead' : usedToday < expectedByNow - slack ? 'behind' : 'on pace';
154
+ const since = approx ? (after?.at ?? now.getTime()) : dayStart;
155
+ const tooEarly = approx && now.getTime() - since < 2 * 3600_000;
156
+ return { allowance, usedToday, expectedByNow, status, daysLeft, dayEnds, approx, since, tooEarly };
157
+ }
158
+ const r1 = (n) => (n < 10 ? (Math.round(n * 10) / 10).toString() : Math.round(n).toString());
159
+ /** "today 4% of 12% ▓▓▓░░░░░░░ behind: 3% unspent so far, it funds the night · day ends 23:30". */
160
+ export function formatAllowance(a) {
161
+ if (!a)
162
+ return 'today unknown (weekly window not known)';
163
+ if (a.tooEarly)
164
+ return `today ${r1(a.allowance)}% a day for the ${a.daysLeft} day${a.daysLeft === 1 ? '' : 's'} left · tracking today since ${clock(a.since)}, so no verdict yet · day ends ${clock(a.dayEnds)}`;
165
+ const filled = Math.min(10, Math.round((a.usedToday / Math.max(a.allowance, 0.01)) * 10));
166
+ const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);
167
+ const say = {
168
+ 'on pace': 'on pace',
169
+ ahead: `ahead: ${r1(a.usedToday - a.expectedByNow)}% more than an even day by now`,
170
+ behind: `behind: ${r1(a.expectedByNow - a.usedToday)}% unspent so far, it funds the night`,
171
+ over: `over today's share by ${r1(a.usedToday - a.allowance)}%`,
172
+ };
173
+ return `today ${r1(a.usedToday)}% of ${r1(a.allowance)}% ${bar} ${say[a.status]} · day ends ${clock(a.dayEnds)}${a.approx ? ' (counted from the first reading today)' : ''}`;
174
+ }
175
+ export function pacing(snap, samples, now, bedtime) {
176
+ const models = {};
177
+ for (const [name, w] of Object.entries(snap?.models ?? {})) {
178
+ const v = windowView(w, now);
179
+ if (v.known)
180
+ models[name] = { usedPct: v.usedPct, delta: paceDelta(w, WEEK, now), resetsAt: v.resetsAt };
181
+ }
182
+ return {
183
+ fiveHourDelta: paceDelta(snap?.fiveHour, FIVE_HOURS, now),
184
+ weekDelta: paceDelta(snap?.sevenDay, WEEK, now),
185
+ fiveHourForecast: forecastWindow(snap?.fiveHour, FIVE_HOURS, samples, (s) => s.five, now),
186
+ today: dailyAllowance(snap?.sevenDay, samples, now, bedtime),
187
+ models,
188
+ };
189
+ }
@@ -0,0 +1,106 @@
1
+ // The permission plan (research/away-readiness.md, step 3): an away run can't ask for approval at 3 AM, so the
2
+ // approval stage asks instead. A card's plan lists what its run may need beyond the box's defaults, from three
3
+ // sources: what earlier runs in this repo were blocked on, what preflight found, and what the blueprint itself
4
+ // says it needs. You tick what to allow when you approve; nothing is allowed by default, and allowed commands
5
+ // still run inside the box.
6
+ export const permissionId = (kind, value) => `${kind}:${value}`;
7
+ export function parsePermission(id) {
8
+ const m = id.match(/^(network|command):(.+)$/);
9
+ if (!m)
10
+ return null;
11
+ const value = m[2].trim();
12
+ if (m[1] === 'network' && !/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(value))
13
+ return null; // a plain domain, nothing else
14
+ if (m[1] === 'command' && (!value || /[;&|`$<>]/.test(value)))
15
+ return null; // one command, no shell tricks
16
+ return { kind: m[1], value };
17
+ }
18
+ /** A blocked command as a pattern to allow: its program name plus anything after ("swiftc *"). */
19
+ export function commandPattern(command) {
20
+ const first = command.trim().split(/\s+/)[0]?.replace(/^.*\//, '');
21
+ if (!first || /[;&|`$<>()]/.test(first))
22
+ return null;
23
+ return `${first} *`;
24
+ }
25
+ /** Hosts named in network errors ("ENOTFOUND registry.npmjs.org", "request to https://x/…"). */
26
+ export function hostsInErrors(text) {
27
+ if (!/ENOTFOUND|EAI_AGAIN|getaddrinfo|Could not resolve host|ECONNREFUSED|network request|unable to access/i.test(text))
28
+ return [];
29
+ const hosts = new Set();
30
+ for (const m of text.matchAll(/(?:ENOTFOUND|EAI_AGAIN|getaddrinfo \w+|Could not resolve host:?)\s+([a-z0-9.-]+\.[a-z]{2,})/gi))
31
+ hosts.add(m[1].toLowerCase());
32
+ for (const m of text.matchAll(/https?:\/\/([a-z0-9.-]+\.[a-z]{2,})/gi))
33
+ hosts.add(m[1].toLowerCase());
34
+ return [...hosts].filter((h) => h !== 'localhost').slice(0, 10);
35
+ }
36
+ /** The "## Needs" section a blueprint may carry: "- network: docs.swift.org: why" or "- command: swiftc: why". */
37
+ export function blueprintNeeds(blueprint) {
38
+ if (!blueprint)
39
+ return [];
40
+ const section = blueprint.split(/^## /m).find((s) => /^Needs\b/i.test(s));
41
+ if (!section)
42
+ return [];
43
+ const needs = [];
44
+ for (const line of section.split('\n').slice(1)) {
45
+ const m = line.match(/^\s*[-*]\s*(network|command)\s*:\s*`?([^`:]+?)`?\s*(?::|—|-)\s*(.+)$/i);
46
+ if (!m)
47
+ continue;
48
+ const kind = m[1].toLowerCase();
49
+ const raw = m[2].trim();
50
+ const value = kind === 'command' ? (raw.endsWith('*') ? raw : `${raw.split(/\s+/)[0]} *`) : raw.toLowerCase();
51
+ if (parsePermission(permissionId(kind, value)))
52
+ needs.push({ kind, value, why: m[3].trim() });
53
+ }
54
+ return needs;
55
+ }
56
+ /** Merge one run's blocked needs into the repo's record. */
57
+ export function recordNeeds(existing, run, cardId, at) {
58
+ const out = existing.map((n) => ({ ...n }));
59
+ const add = (kind, value) => {
60
+ const id = permissionId(kind, value);
61
+ if (!parsePermission(id))
62
+ return;
63
+ const hit = out.find((n) => n.id === id);
64
+ if (hit)
65
+ Object.assign(hit, { runs: hit.runs + 1, lastCard: cardId, lastAt: at });
66
+ else
67
+ out.push({ id, kind, value, runs: 1, lastCard: cardId, lastAt: at });
68
+ };
69
+ for (const c of new Set(run.commands))
70
+ add('command', c);
71
+ for (const h of new Set(run.hosts))
72
+ add('network', h);
73
+ return out;
74
+ }
75
+ /** The plan for a card: earlier runs' blocks, preflight's network needs, and the blueprint's own Needs. */
76
+ export function planFor(blueprint, recorded, preflightHosts = []) {
77
+ const plan = [];
78
+ const push = (p) => {
79
+ if (!plan.some((q) => q.id === p.id))
80
+ plan.push(p);
81
+ };
82
+ for (const n of blueprintNeeds(blueprint))
83
+ push({ id: permissionId(n.kind, n.value), kind: n.kind, value: n.value, why: n.why, source: 'blueprint' });
84
+ for (const n of recorded) {
85
+ const what = n.kind === 'network' ? `reaching ${n.value}` : `running ${n.value.replace(/ \*$/, '')}`;
86
+ push({ id: n.id, kind: n.kind, value: n.value, why: `an earlier run here was blocked ${what} (${n.runs}×, last on #${n.lastCard})`, source: 'earlier runs' });
87
+ }
88
+ for (const h of preflightHosts)
89
+ push({ id: permissionId('network', h), kind: 'network', value: h, why: "the repo's checks reach it", source: 'preflight' });
90
+ return plan;
91
+ }
92
+ /** What a run gets from the permissions you allowed: extra tool rules and sandbox domains. */
93
+ export function applyPermissions(allowed) {
94
+ const tools = [];
95
+ const domains = [];
96
+ for (const id of allowed ?? []) {
97
+ const p = parsePermission(id);
98
+ if (!p)
99
+ continue;
100
+ if (p.kind === 'network')
101
+ domains.push(p.value);
102
+ else
103
+ tools.push(`Bash(${p.value})`);
104
+ }
105
+ return { allowedTools: tools, domains };
106
+ }
@@ -0,0 +1,124 @@
1
+ // Picture first: every card opens with a diagram of what the task will do, drawn by an agent following
2
+ // the diagram-design skill (vendored in cli/vendor/diagram-design, MIT). One HTML + SVG file per card,
3
+ // in Chompyy's skin; the dark copy is made by swapping tokens (the skill's inversion rule), no second call.
4
+ import { createHash } from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { existsSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { homePath } from './home.js';
10
+ import { chosenType, suggestTypes, typeHint } from './picturetype.js';
11
+ export function skillDir() {
12
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'vendor', 'diagram-design');
13
+ }
14
+ export const blueprintHash = (text) => createHash('sha256').update(text ?? '').digest('hex').slice(0, 16);
15
+ export function picturePrompt(card, suggestions = suggestTypes(card)) {
16
+ return `You are drawing the picture for a task card in Chompyy, unattended. Nobody can answer questions,
17
+ so don't ask any: decide and draw.
18
+
19
+ Use the diagram-design skill in this folder. Read SKILL.md first. The style guide
20
+ (references/style-guide.md) is already customized for Chompyy, so skip the first-time style gate and
21
+ onboarding, and take every color from it (never the colors in the example files). Then pick ONE visual
22
+ type and read only that type's reference, plus references/primitives-core.md or
23
+ references/layout-budget.md if you need exact markup. Start from assets/template.html.
24
+
25
+ Which type: the card's text was checked for signals (below). They are hints, not orders.
26
+ ${typeHint(suggestions)}
27
+
28
+ Who looks at it: the person deciding in ten seconds whether to approve this task. The picture must show
29
+ what the task will DO and WHY it helps: the thing it produces or changes and how it fits, not the
30
+ blueprint's headings. Don't draw four boxes called Goal / Changes / Won't touch / Done when. Put the accent on the 1 or 2 things this task actually creates or changes. Keep it small:
31
+ at most 7 nodes. Title (h1): the task in plain words. Eyebrow: "<Type> · Card #${card.id}".
32
+
33
+ Rendering rules for Chompyy:
34
+ - Remove the Google Fonts <link>; keep the font stacks (Chompyy renders offline).
35
+ - Static only: no <script>, no motion.
36
+ - Use viewBox width 960 and the matching min-width, as the template does.
37
+ - Follow the taste gate (SKILL.md §9) before you answer.
38
+
39
+ Reply with ONLY the complete HTML document, from <!DOCTYPE html> to </html>. No commentary.
40
+
41
+ The task:
42
+ Title: ${card.title}
43
+ Idea: ${card.idea}
44
+
45
+ Blueprint (agreed scope):
46
+ ${card.blueprint ?? '(none yet)'}`;
47
+ }
48
+ /** The HTML document in the model's reply. */
49
+ export function extractHtml(output) {
50
+ const start = output.search(/<!DOCTYPE html>|<html[\s>]/i);
51
+ const end = output.toLowerCase().lastIndexOf('</html>');
52
+ if (start < 0 || end < start)
53
+ throw new Error('The picture model did not reply with an HTML document.');
54
+ return output.slice(start, end + '</html>'.length);
55
+ }
56
+ // Colors from the skill's default skin (examples) → Chompyy light, then Chompyy light → dark.
57
+ const TO_CHOMPYY = [
58
+ [/#f5f5f5\b/gi, '#faf3e8'],
59
+ [/#ececec\b/gi, '#f2e8d9'],
60
+ [/#2d3142\b/gi, '#3a2a1f'],
61
+ [/#4f5d75\b/gi, '#6b5141'],
62
+ [/#5a6580\b/gi, '#735a48'],
63
+ [/#bfc0c0\b/gi, '#ddd0bd'],
64
+ [/#bf4520\b/gi, '#a8481c'],
65
+ [/rgba\(\s*45\s*,\s*49\s*,\s*66\s*,/gi, 'rgba(58,42,31,'],
66
+ [/rgba\(\s*191\s*,\s*69\s*,\s*32\s*,/gi, 'rgba(168,72,28,'],
67
+ ];
68
+ const TO_DARK = [
69
+ [/#faf3e8\b/gi, '#1e1915'],
70
+ [/#f2e8d9\b/gi, '#2a231d'],
71
+ [/#ffffff\b|#fff\b(?![0-9a-f])/gi, '#26201b'],
72
+ [/(fill|background(?:-color)?)(=|:\s*)"?white\b/gi, '$1$2"#26201b'],
73
+ [/#3a2a1f\b/gi, '#f6eee3'],
74
+ [/#6b5141\b/gi, '#d0c1af'],
75
+ [/#735a48\b/gi, '#b5a28f'],
76
+ [/#ddd0bd\b/gi, 'rgba(208,193,175,0.25)'],
77
+ [/#a8481c\b/gi, '#f0a066'],
78
+ [/#2e5aa8\b/gi, '#86aee6'],
79
+ [/rgba\(\s*58\s*,\s*42\s*,\s*31\s*,/gi, 'rgba(246,238,227,'],
80
+ [/rgba\(\s*168\s*,\s*72\s*,\s*28\s*,/gi, 'rgba(240,160,102,'],
81
+ ];
82
+ const apply = (html, map) => map.reduce((s, [re, to]) => s.replace(re, to), html);
83
+ /** Make it safe and offline: no scripts, no remote fonts or images; Chompyy colors. */
84
+ export function cleanPicture(html) {
85
+ const out = html
86
+ .replace(/<link[^>]+fonts\.(googleapis|gstatic)\.com[^>]*>/gi, '')
87
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
88
+ .replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*')/gi, '');
89
+ if (!/<svg[\s>]/i.test(out))
90
+ throw new Error('The picture has no diagram (<svg>) in it.');
91
+ if (/(src|href)\s*=\s*["']https?:/i.test(out.replace(/xmlns(:\w+)?="[^"]*"/g, '')))
92
+ throw new Error('The picture loads something from the internet.');
93
+ return apply(out, TO_CHOMPYY);
94
+ }
95
+ export const darkPicture = (html) => apply(html, TO_DARK);
96
+ /** The skill's own self-check (accessibility contract, single-file safety, content inside the viewBox). */
97
+ function selfCheck(file) {
98
+ const r = spawnSync('python3', [join(skillDir(), 'scripts', 'self_check.py'), file], { encoding: 'utf8', timeout: 20_000 });
99
+ if (r.error)
100
+ return null;
101
+ return (r.stdout + r.stderr).trim().split('\n').slice(0, 12).join('\n') || (r.status === 0 ? 'OK' : `exit ${r.status}`);
102
+ }
103
+ export async function drawPicture(card, runner, opts) {
104
+ if (!card.blueprint)
105
+ throw new Error(`Card #${card.id} has no blueprint to draw yet.`);
106
+ if (!existsSync(join(skillDir(), 'SKILL.md')))
107
+ throw new Error('The diagram-design skill is missing from this install.');
108
+ const suggested = suggestTypes(card);
109
+ const result = await runner.run({ prompt: picturePrompt(card, suggested), cwd: skillDir(), model: opts.model, tools: 'Read,Glob,Grep', timeoutMs: opts.timeoutMs ?? 300_000 });
110
+ if (result.timedOut)
111
+ throw new Error('Drawing the picture timed out.');
112
+ if (result.exitCode !== 0)
113
+ throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
114
+ const html = cleanPicture(extractHtml(result.output));
115
+ const chose = chosenType(html);
116
+ const path = homePath('pictures', `${card.id}.html`);
117
+ const darkPath = homePath('pictures', `${card.id}-dark.html`);
118
+ writeFileSync(path, html);
119
+ writeFileSync(darkPath, darkPicture(html));
120
+ return {
121
+ path, darkPath, at: opts.now.toISOString(), blueprintHash: blueprintHash(card.blueprint), check: selfCheck(path),
122
+ type: chose?.type ?? null, why: chose?.why ?? null, suggested,
123
+ };
124
+ }