chompyy 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +252 -2
- package/THIRD_PARTY_NOTICES.md +59 -0
- package/dist/appstate.js +116 -0
- package/dist/away.js +314 -0
- package/dist/blueprint.js +91 -0
- package/dist/board.js +186 -0
- package/dist/claudesettings.js +23 -0
- package/dist/cli.js +861 -0
- package/dist/coldstart.js +207 -0
- package/dist/config.js +89 -0
- package/dist/costs.js +162 -0
- package/dist/duration.js +36 -0
- package/dist/gate.js +69 -0
- package/dist/history.js +308 -0
- package/dist/home.js +34 -0
- package/dist/livequota.js +92 -0
- package/dist/macapp.js +57 -0
- package/dist/pacing.js +189 -0
- package/dist/picture.js +117 -0
- package/dist/projects.js +114 -0
- package/dist/quota.js +153 -0
- package/dist/report.js +136 -0
- package/dist/review.js +173 -0
- package/dist/runner.js +357 -0
- package/dist/taste.js +507 -0
- package/dist/triggers.js +182 -0
- package/dist/vendor/codeburn/claude.js +255 -0
- package/dist/vendor/codeburn/security.js +260 -0
- package/dist/vendor/codeburn/types.js +1 -0
- package/dist/verify.js +131 -0
- package/dist/workspace.js +80 -0
- package/package.json +48 -4
- package/skills/away/SKILL.md +26 -0
- package/skills/eat-tokens/SKILL.md +18 -0
- package/skills/later/SKILL.md +20 -0
- package/skills/taste/SKILL.md +19 -0
- package/vendor/diagram-design/LICENSE +21 -0
- package/vendor/diagram-design/SKILL.md +399 -0
- package/vendor/diagram-design/UPSTREAM.md +18 -0
- package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
- package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
- package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
- package/vendor/diagram-design/assets/example-architecture.html +183 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
- package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
- package/vendor/diagram-design/assets/example-bar.html +129 -0
- package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
- package/vendor/diagram-design/assets/example-box-plot.html +127 -0
- package/vendor/diagram-design/assets/example-bubble.html +147 -0
- package/vendor/diagram-design/assets/example-bump.html +142 -0
- package/vendor/diagram-design/assets/example-data-flow.html +143 -0
- package/vendor/diagram-design/assets/example-datalake.html +269 -0
- package/vendor/diagram-design/assets/example-db-schema.html +302 -0
- package/vendor/diagram-design/assets/example-dependency.html +224 -0
- package/vendor/diagram-design/assets/example-deployment.html +190 -0
- package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
- package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
- package/vendor/diagram-design/assets/example-er.html +202 -0
- package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
- package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
- package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
- package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
- package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
- package/vendor/diagram-design/assets/example-exploded.html +83 -0
- package/vendor/diagram-design/assets/example-fishbone.html +152 -0
- package/vendor/diagram-design/assets/example-flowchart.html +163 -0
- package/vendor/diagram-design/assets/example-gantt.html +137 -0
- package/vendor/diagram-design/assets/example-heatmap.html +224 -0
- package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
- package/vendor/diagram-design/assets/example-high-level.html +301 -0
- package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
- package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
- package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
- package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
- package/vendor/diagram-design/assets/example-it-state.html +128 -0
- package/vendor/diagram-design/assets/example-journey.html +148 -0
- package/vendor/diagram-design/assets/example-kanban.html +174 -0
- package/vendor/diagram-design/assets/example-layers.html +123 -0
- package/vendor/diagram-design/assets/example-line.html +111 -0
- package/vendor/diagram-design/assets/example-loop.html +100 -0
- package/vendor/diagram-design/assets/example-marimekko.html +148 -0
- package/vendor/diagram-design/assets/example-medallion.html +159 -0
- package/vendor/diagram-design/assets/example-nested.html +136 -0
- package/vendor/diagram-design/assets/example-org-chart.html +45 -0
- package/vendor/diagram-design/assets/example-polar.html +116 -0
- package/vendor/diagram-design/assets/example-process.html +64 -0
- package/vendor/diagram-design/assets/example-pyramid.html +119 -0
- package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
- package/vendor/diagram-design/assets/example-quadrant.html +135 -0
- package/vendor/diagram-design/assets/example-radar.html +139 -0
- package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
- package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
- package/vendor/diagram-design/assets/example-sankey.html +150 -0
- package/vendor/diagram-design/assets/example-sbgn.html +213 -0
- package/vendor/diagram-design/assets/example-scatter.html +141 -0
- package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
- package/vendor/diagram-design/assets/example-sequence.html +222 -0
- package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
- package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
- package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
- package/vendor/diagram-design/assets/example-state.html +147 -0
- package/vendor/diagram-design/assets/example-steps.html +78 -0
- package/vendor/diagram-design/assets/example-story-map.html +184 -0
- package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
- package/vendor/diagram-design/assets/example-swimlane.html +172 -0
- package/vendor/diagram-design/assets/example-timeline.html +135 -0
- package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
- package/vendor/diagram-design/assets/example-tree.html +173 -0
- package/vendor/diagram-design/assets/example-treemap.html +107 -0
- package/vendor/diagram-design/assets/example-uml-class.html +188 -0
- package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
- package/vendor/diagram-design/assets/example-venn.html +110 -0
- package/vendor/diagram-design/assets/example-wardley.html +153 -0
- package/vendor/diagram-design/assets/example-waterfall.html +129 -0
- package/vendor/diagram-design/assets/template-dark.html +99 -0
- package/vendor/diagram-design/assets/template.html +100 -0
- package/vendor/diagram-design/references/layout-budget.md +103 -0
- package/vendor/diagram-design/references/output-spec.md +277 -0
- package/vendor/diagram-design/references/primitive-annotation.md +36 -0
- package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
- package/vendor/diagram-design/references/primitives-core.md +146 -0
- package/vendor/diagram-design/references/semantic-patterns.md +154 -0
- package/vendor/diagram-design/references/style-guide.md +234 -0
- package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
- package/vendor/diagram-design/references/type-architecture.md +117 -0
- package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
- package/vendor/diagram-design/references/type-bar.md +108 -0
- package/vendor/diagram-design/references/type-data-flow.md +371 -0
- package/vendor/diagram-design/references/type-db-schema.md +48 -0
- package/vendor/diagram-design/references/type-dependency.md +113 -0
- package/vendor/diagram-design/references/type-deployment.md +45 -0
- package/vendor/diagram-design/references/type-dp-integration.md +407 -0
- package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
- package/vendor/diagram-design/references/type-er.md +25 -0
- package/vendor/diagram-design/references/type-event-modeling.md +36 -0
- package/vendor/diagram-design/references/type-exploded.md +115 -0
- package/vendor/diagram-design/references/type-fishbone.md +75 -0
- package/vendor/diagram-design/references/type-flowchart.md +23 -0
- package/vendor/diagram-design/references/type-gantt.md +45 -0
- package/vendor/diagram-design/references/type-heatmap.md +80 -0
- package/vendor/diagram-design/references/type-high-level.md +470 -0
- package/vendor/diagram-design/references/type-it-state.md +468 -0
- package/vendor/diagram-design/references/type-journey.md +55 -0
- package/vendor/diagram-design/references/type-kanban.md +49 -0
- package/vendor/diagram-design/references/type-layers.md +26 -0
- package/vendor/diagram-design/references/type-line.md +337 -0
- package/vendor/diagram-design/references/type-loop.md +223 -0
- package/vendor/diagram-design/references/type-medallion.md +356 -0
- package/vendor/diagram-design/references/type-nested.md +22 -0
- package/vendor/diagram-design/references/type-org-chart.md +44 -0
- package/vendor/diagram-design/references/type-polar.md +136 -0
- package/vendor/diagram-design/references/type-process.md +490 -0
- package/vendor/diagram-design/references/type-pyramid.md +33 -0
- package/vendor/diagram-design/references/type-quadrant.md +81 -0
- package/vendor/diagram-design/references/type-radar.md +82 -0
- package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
- package/vendor/diagram-design/references/type-sankey.md +75 -0
- package/vendor/diagram-design/references/type-sbgn.md +80 -0
- package/vendor/diagram-design/references/type-scatter.md +276 -0
- package/vendor/diagram-design/references/type-sequence.md +130 -0
- package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
- package/vendor/diagram-design/references/type-state.md +30 -0
- package/vendor/diagram-design/references/type-steps.md +180 -0
- package/vendor/diagram-design/references/type-story-map.md +46 -0
- package/vendor/diagram-design/references/type-swimlane.md +22 -0
- package/vendor/diagram-design/references/type-timeline.md +20 -0
- package/vendor/diagram-design/references/type-tree.md +24 -0
- package/vendor/diagram-design/references/type-treemap.md +137 -0
- package/vendor/diagram-design/references/type-uml-class.md +65 -0
- package/vendor/diagram-design/references/type-unit-grid.md +63 -0
- package/vendor/diagram-design/references/type-venn.md +26 -0
- package/vendor/diagram-design/references/type-wardley.md +39 -0
- package/vendor/diagram-design/references/type-waterfall.md +75 -0
- package/vendor/diagram-design/scripts/self_check.py +1177 -0
- package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
package/dist/report.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// "While you were away" report and rating (spec §5.7).
|
|
2
|
+
import { getCard } from './board.js';
|
|
3
|
+
import { formatDuration } from './duration.js';
|
|
4
|
+
import { wrap } from './review.js';
|
|
5
|
+
import { appendJsonl, homePath, readJson, writeJson } from './home.js';
|
|
6
|
+
const statePath = () => homePath('state.json');
|
|
7
|
+
export function lastReportAt() {
|
|
8
|
+
return readJson(statePath(), {}).lastReportAt ?? null;
|
|
9
|
+
}
|
|
10
|
+
export function markReported(now) {
|
|
11
|
+
writeJson(statePath(), { ...readJson(statePath(), {}), lastReportAt: now.toISOString() });
|
|
12
|
+
}
|
|
13
|
+
/** Cards whose last run finished after `since` (all runs when null), oldest first. */
|
|
14
|
+
export function cardsSince(board, since) {
|
|
15
|
+
return board.cards
|
|
16
|
+
.filter((c) => c.run && (!since || c.run.finishedAt > since))
|
|
17
|
+
.sort((a, b) => a.run.finishedAt.localeCompare(b.run.finishedAt));
|
|
18
|
+
}
|
|
19
|
+
/** The one thing to do about each run, most urgent first. */
|
|
20
|
+
const ACTION = {
|
|
21
|
+
questions: { icon: '❓', rank: 0, text: 'Answer its question, then keep or undo' },
|
|
22
|
+
failed: { icon: '❌', rank: 1, text: "It didn't finish. Look at what happened, then undo or run it again" },
|
|
23
|
+
error: { icon: '⚠️', rank: 1, text: "It couldn't start. Look at what happened" },
|
|
24
|
+
timeout: { icon: '⏱', rank: 2, text: 'It ran out of time. Check what it got done, then keep or undo' },
|
|
25
|
+
stuck: { icon: '⛔', rank: 1, text: 'Chompyy stopped it: it was going in circles. Look at what happened, then undo or run it again' },
|
|
26
|
+
ok: { icon: '✅', rank: 3, text: 'Check the change, then keep or undo' },
|
|
27
|
+
};
|
|
28
|
+
/** Finished, but its own checks didn't pass: say so instead of a plain ✅. */
|
|
29
|
+
const UNCHECKED = {
|
|
30
|
+
failed: { icon: '⚠️', rank: 1, text: 'It finished, but its checks fail. See why before you keep it' },
|
|
31
|
+
failedIndependently: { icon: '⚠️', rank: 1, text: "It says it's done, but the tests fail when Chompyy runs them. See why before you keep it" },
|
|
32
|
+
notRun: { icon: '🔍', rank: 2, text: "It finished but couldn't check its work. Check it yourself, then keep or undo" },
|
|
33
|
+
};
|
|
34
|
+
/** Once you've kept or undone a card, the only thing left is the rating. */
|
|
35
|
+
const DECIDED = {
|
|
36
|
+
kept: { icon: '📥', rank: 4, text: 'Kept. Rate it so Chompyy learns your taste' },
|
|
37
|
+
undone: { icon: '↩️', rank: 4, text: 'Undone. Rate it so Chompyy learns what missed' },
|
|
38
|
+
};
|
|
39
|
+
function filesLine(files) {
|
|
40
|
+
if (!files.length)
|
|
41
|
+
return 'no files changed';
|
|
42
|
+
const shown = files.slice(0, 3).join(', ');
|
|
43
|
+
return files.length > 3 ? `${shown} +${files.length - 3} more` : shown;
|
|
44
|
+
}
|
|
45
|
+
/** "Last night: 3 cards ran, 1 kept · taste: 1 learned, 1 retired, 1 question". Shows the system evolving. */
|
|
46
|
+
export function morningLine(cards, taste) {
|
|
47
|
+
const bits = [];
|
|
48
|
+
if (cards.length) {
|
|
49
|
+
const kept = cards.filter((c) => c.outcome === 'kept').length;
|
|
50
|
+
const used = cards.map((c) => c.run?.cost?.fiveHourPct).filter((n) => typeof n === 'number');
|
|
51
|
+
const total = Math.round(used.reduce((a, b) => a + b, 0));
|
|
52
|
+
bits.push(`${cards.length} card${cards.length === 1 ? '' : 's'} ran${kept ? `, ${kept} kept` : ''}${used.length ? `, using ${total}% of 5h windows` : ''}`);
|
|
53
|
+
}
|
|
54
|
+
const t = [];
|
|
55
|
+
if (taste.learned)
|
|
56
|
+
t.push(`${taste.learned} learned`);
|
|
57
|
+
if (taste.retired)
|
|
58
|
+
t.push(`${taste.retired} retired`);
|
|
59
|
+
if (t.length)
|
|
60
|
+
bits.push(`taste: ${t.join(', ')}`);
|
|
61
|
+
return bits.length ? `Since last time: ${bits.join(' · ')}` : null;
|
|
62
|
+
}
|
|
63
|
+
export function formatReport(cards, since, facts, extras = {}) {
|
|
64
|
+
const footer = extras.footer?.length ? ['', ...extras.footer] : [];
|
|
65
|
+
if (cards.length === 0)
|
|
66
|
+
return [since ? 'Nothing new since your last report.' : 'Nothing has run yet.', ...footer].join('\n');
|
|
67
|
+
const actionOf = (c) => {
|
|
68
|
+
if (c.outcome)
|
|
69
|
+
return DECIDED[c.outcome];
|
|
70
|
+
// Chompyy's own test run outranks what the agent says about itself.
|
|
71
|
+
if (c.run.status === 'ok' && c.run.verified?.result === 'failed' && !c.run.verified.sandboxBlocked)
|
|
72
|
+
return UNCHECKED.failedIndependently;
|
|
73
|
+
if (c.run.status === 'ok' && c.run.verified?.sandboxBlocked)
|
|
74
|
+
return UNCHECKED.notRun;
|
|
75
|
+
if (c.run.status === 'ok' && c.run.verified?.result === 'passed')
|
|
76
|
+
return ACTION.ok;
|
|
77
|
+
if (c.run.status === 'ok' && c.run.checks && c.run.checks.result !== 'passed') {
|
|
78
|
+
return c.run.checks.result === 'failed' ? UNCHECKED.failed : UNCHECKED.notRun;
|
|
79
|
+
}
|
|
80
|
+
return ACTION[c.run.status];
|
|
81
|
+
};
|
|
82
|
+
const rank = (c) => actionOf(c)?.rank ?? 9;
|
|
83
|
+
const sorted = [...cards].sort((a, b) => rank(a) - rank(b));
|
|
84
|
+
const out = [`🍪 While you were away · ${cards.length} card${cards.length === 1 ? '' : 's'}`, ...(extras.header ?? []), ''];
|
|
85
|
+
for (const c of sorted) {
|
|
86
|
+
const decided = c.outcome ? DECIDED[c.outcome] : undefined;
|
|
87
|
+
const action = actionOf(c) ?? { icon: '•', text: 'Take a look' };
|
|
88
|
+
const { files, questions } = decided ? { files: [], questions: [] } : facts(c);
|
|
89
|
+
out.push(`${action.icon} #${c.id} ${c.title}`);
|
|
90
|
+
out.push(` → ${action.text}`);
|
|
91
|
+
const v = c.run.verified;
|
|
92
|
+
if (!decided && v && v.result !== 'not run')
|
|
93
|
+
wrap(`${v.result === 'passed' ? '✓' : '✗'} ${v.why} (run by Chompyy, not the agent)`, 70).forEach((part, i) => out.push(` ${i === 0 ? '·' : ' '} ${part}`));
|
|
94
|
+
else if (!decided && action !== ACTION[c.run.status] && c.run.checks?.why)
|
|
95
|
+
wrap(c.run.checks.why, 70).forEach((part, i) => out.push(` ${i === 0 ? '·' : ' '} ${part}`));
|
|
96
|
+
for (const q of questions)
|
|
97
|
+
wrap(q, 70).forEach((part, i) => out.push(` ${i === 0 ? '·' : ' '} ${part}`));
|
|
98
|
+
if (!decided)
|
|
99
|
+
out.push(` changed: ${filesLine(files)} · took ${formatDuration(c.run.durationMs)}`);
|
|
100
|
+
out.push('');
|
|
101
|
+
}
|
|
102
|
+
const top = sorted[0];
|
|
103
|
+
const id = top.id;
|
|
104
|
+
out.push(top.outcome
|
|
105
|
+
? `More on a card: chompyy show ${id} · rate ${id} <1-5>`
|
|
106
|
+
: `More on a card: chompyy show ${id} · diff ${id} · keep ${id} · undo ${id} · rate ${id} <1-5>`);
|
|
107
|
+
out.push(...footer);
|
|
108
|
+
return out.join('\n');
|
|
109
|
+
}
|
|
110
|
+
export function rateCard(board, id, score, reason, now, toFive = []) {
|
|
111
|
+
if (!Number.isInteger(score) || score < 1 || score > 5)
|
|
112
|
+
throw new Error('Rating must be a whole number from 1 to 5.');
|
|
113
|
+
const card = getCard(board, id);
|
|
114
|
+
if (card.column !== 'review' && card.column !== 'done') {
|
|
115
|
+
throw new Error(`Card #${card.id} is in ${card.column}; only cards that ran (review or done) can be rated.`);
|
|
116
|
+
}
|
|
117
|
+
const at = now.toISOString();
|
|
118
|
+
card.rating = { score, ...(reason ? { reason } : {}), ...(toFive.length ? { toFive } : {}), at };
|
|
119
|
+
// A card is done once you've kept or undone it. Rating first keeps it in review, so Keep/Undo stay available.
|
|
120
|
+
if (card.outcome)
|
|
121
|
+
card.column = 'done';
|
|
122
|
+
card.updatedAt = at;
|
|
123
|
+
// Raw material for taste distillation (spec §5.8, taste.ts).
|
|
124
|
+
appendJsonl(homePath('signals.jsonl'), {
|
|
125
|
+
at,
|
|
126
|
+
card: card.id,
|
|
127
|
+
title: card.title,
|
|
128
|
+
rating: score,
|
|
129
|
+
reason: reason ?? null,
|
|
130
|
+
toFive: toFive.length ? toFive : null,
|
|
131
|
+
blueprint: card.blueprint,
|
|
132
|
+
status: card.run?.status ?? null,
|
|
133
|
+
});
|
|
134
|
+
return card;
|
|
135
|
+
}
|
|
136
|
+
export { readTaste, TASTE_STUB } from './taste.js';
|
package/dist/review.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// After a run: what changed, what the agent asks, and keep / undo (spec §5.7).
|
|
2
|
+
// Every git card works on its own branch, so undo is just removing that branch.
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { commitLeftovers, gitRoot, uncommittedWork } from './workspace.js';
|
|
7
|
+
function git(cwd, args) {
|
|
8
|
+
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
9
|
+
}
|
|
10
|
+
function ran(card) {
|
|
11
|
+
if (!card.run)
|
|
12
|
+
throw new Error(`Card #${card.id} hasn't run yet.`);
|
|
13
|
+
return card.run;
|
|
14
|
+
}
|
|
15
|
+
/** The question itself: up to the first "?", else the first sentence. Never cut mid-sentence. */
|
|
16
|
+
function questionPart(text) {
|
|
17
|
+
const q = text.indexOf('?');
|
|
18
|
+
if (q !== -1)
|
|
19
|
+
return text.slice(0, q + 1);
|
|
20
|
+
const dot = text.search(/[.!](\s|$)/);
|
|
21
|
+
return dot !== -1 ? text.slice(0, dot + 1) : text;
|
|
22
|
+
}
|
|
23
|
+
/** Top-level items from QUESTIONS.md, as whole questions, at most `max`. */
|
|
24
|
+
export function firstQuestions(markdown, max = 2) {
|
|
25
|
+
return markdown
|
|
26
|
+
.split('\n')
|
|
27
|
+
.filter((line) => /^(\d+\.|[-*])\s+/.test(line)) // top level only, not indented sub-points
|
|
28
|
+
.map((line) => questionPart(line.replace(/^(\d+\.|[-*])\s+/, '').replace(/\*\*|__|`/g, '').trim()))
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.slice(0, max);
|
|
31
|
+
}
|
|
32
|
+
/** Wrap text at word boundaries so long questions fold onto the next line instead of being cut. */
|
|
33
|
+
export function wrap(text, width) {
|
|
34
|
+
const lines = [];
|
|
35
|
+
let line = '';
|
|
36
|
+
for (const word of text.split(/\s+/)) {
|
|
37
|
+
if (line && line.length + 1 + word.length > width) {
|
|
38
|
+
lines.push(line);
|
|
39
|
+
line = word;
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
line = line ? `${line} ${word}` : word;
|
|
43
|
+
}
|
|
44
|
+
if (line)
|
|
45
|
+
lines.push(line);
|
|
46
|
+
return lines;
|
|
47
|
+
}
|
|
48
|
+
export function questionsOf(card) {
|
|
49
|
+
const path = card.run ? join(card.run.workdir, 'QUESTIONS.md') : '';
|
|
50
|
+
return path && existsSync(path) ? firstQuestions(readFileSync(path, 'utf8')) : [];
|
|
51
|
+
}
|
|
52
|
+
/** Files the run changed: from the branch for git cards, from the folder for draft cards. */
|
|
53
|
+
export function changedFiles(card) {
|
|
54
|
+
const run = card.run;
|
|
55
|
+
if (!run || !existsSync(run.workdir))
|
|
56
|
+
return [];
|
|
57
|
+
try {
|
|
58
|
+
if (run.branch) {
|
|
59
|
+
const root = gitRoot(card.cwd);
|
|
60
|
+
if (!root)
|
|
61
|
+
return [];
|
|
62
|
+
return git(root, ['diff', '--name-only', `HEAD...${run.branch}`]).split('\n').filter(Boolean);
|
|
63
|
+
}
|
|
64
|
+
return readdirSync(run.workdir, { recursive: true, withFileTypes: true })
|
|
65
|
+
.filter((d) => d.isFile())
|
|
66
|
+
.map((d) => join(d.parentPath ?? run.workdir, d.name).slice(run.workdir.length + 1));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** File paths a blueprint names: `src/x.ts`, docs/README.md, … (a guess at what a card will touch). */
|
|
73
|
+
export function blueprintFiles(blueprint) {
|
|
74
|
+
if (!blueprint)
|
|
75
|
+
return [];
|
|
76
|
+
const found = new Set();
|
|
77
|
+
for (const m of blueprint.matchAll(/`([^`\s]+)`|(?:^|[\s(])((?:[\w.-]+\/)*[\w-]+\.[a-z]{1,6})(?=[\s),.:;]|$)/gim)) {
|
|
78
|
+
const p = (m[1] ?? m[2] ?? '').replace(/^\.\//, '');
|
|
79
|
+
if (/\.[a-z]{1,6}$/i.test(p) && !/^https?:/.test(p) && !/^\d+(\.\d+)+$/.test(p) && !/^(e\.g|i\.e|etc)\.?$/i.test(p))
|
|
80
|
+
found.add(p);
|
|
81
|
+
}
|
|
82
|
+
return [...found];
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Cards already queued, running or waiting for review that look like they touch the same files as `card`:
|
|
86
|
+
* from what a run really changed, else the files its blueprint names. A warning, not a block: overlaps only
|
|
87
|
+
* conflict at keep time, and Run again recovers.
|
|
88
|
+
*/
|
|
89
|
+
export function overlaps(card, others, changed = changedFiles) {
|
|
90
|
+
const mine = new Set(blueprintFiles(card.blueprint));
|
|
91
|
+
if (!mine.size)
|
|
92
|
+
return [];
|
|
93
|
+
return others
|
|
94
|
+
.filter((o) => o.id !== card.id && o.cwd === card.cwd && (['approved', 'running'].includes(o.column) || (o.column === 'review' && !o.outcome)))
|
|
95
|
+
.map((o) => {
|
|
96
|
+
const theirs = o.run ? changed(o) : blueprintFiles(o.blueprint);
|
|
97
|
+
return { id: o.id, title: o.title, files: theirs.filter((f) => mine.has(f)) };
|
|
98
|
+
})
|
|
99
|
+
.filter((o) => o.files.length);
|
|
100
|
+
}
|
|
101
|
+
export function diffCard(card) {
|
|
102
|
+
const run = ran(card);
|
|
103
|
+
if (!run.branch)
|
|
104
|
+
return `Card #${card.id} ran in a draft folder, not a git repo. Its files are in ${run.workdir}`;
|
|
105
|
+
const root = gitRoot(card.cwd);
|
|
106
|
+
if (!root)
|
|
107
|
+
throw new Error(`${card.cwd} is no longer a git repo.`);
|
|
108
|
+
return git(root, ['diff', '--stat', '--patch', `HEAD...${run.branch}`]) || 'No changes on the branch.';
|
|
109
|
+
}
|
|
110
|
+
function removeWorktree(root, card) {
|
|
111
|
+
const run = ran(card);
|
|
112
|
+
if (existsSync(run.workdir))
|
|
113
|
+
git(root, ['worktree', 'remove', '--force', run.workdir]);
|
|
114
|
+
}
|
|
115
|
+
/** Merge the card's branch into the repo's current branch, then tidy up the worktree. */
|
|
116
|
+
export function keepCard(card) {
|
|
117
|
+
const run = ran(card);
|
|
118
|
+
if (!run.branch)
|
|
119
|
+
return `Card #${card.id} ran in a draft folder; copy what you want from ${run.workdir}`;
|
|
120
|
+
const root = gitRoot(card.cwd);
|
|
121
|
+
if (!root)
|
|
122
|
+
throw new Error(`${card.cwd} is no longer a git repo.`);
|
|
123
|
+
// Your own unsaved work only blocks Keep when it touches the same files as the card (git's own rule),
|
|
124
|
+
// or when something is staged (git won't put unrelated staged changes into a merge commit).
|
|
125
|
+
const into = git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
126
|
+
const yours = [...new Set(git(root, ['status', '--porcelain', '--untracked-files=all']).split('\n').filter(Boolean)
|
|
127
|
+
.map((l) => l.trim().replace(/^\S+\s+/, '').replace(/^.* -> /, '')))];
|
|
128
|
+
if (yours.length) {
|
|
129
|
+
const theirs = new Set(git(root, ['diff', '--name-only', `HEAD...${run.branch}`]).split('\n').filter(Boolean));
|
|
130
|
+
const clash = yours.filter((f) => theirs.has(f));
|
|
131
|
+
const staged = git(root, ['diff', '--cached', '--name-only']).split('\n').filter(Boolean);
|
|
132
|
+
const list = (fs) => fs.slice(0, 3).join(', ') + (fs.length > 3 ? ` and ${fs.length - 3} more` : '');
|
|
133
|
+
if (clash.length) {
|
|
134
|
+
throw new Error(`Can't keep #${card.id} yet: it changes ${list(clash)}, and you have unsaved changes in ${clash.length === 1 ? 'that file' : 'those files'} in ${root} (branch ${into}). Commit or set them aside first, or press Undo to drop the card's work.`);
|
|
135
|
+
}
|
|
136
|
+
if (staged.length) {
|
|
137
|
+
throw new Error(`Can't keep #${card.id} yet: ${root} has staged changes (${list(staged)}) that a merge would mix in. Commit or unstage them first, or press Undo to drop the card's work.`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
commitLeftovers({ kind: 'worktree', dir: run.workdir }, card); // older runs may have left work uncommitted
|
|
141
|
+
const loose = uncommittedWork(run.workdir);
|
|
142
|
+
if (loose.length) {
|
|
143
|
+
throw new Error(`The card's folder has uncommitted work that keep would lose: ${loose.slice(0, 5).join(', ')}. Commit it in ${run.workdir} first.`);
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
git(root, ['merge', '--no-ff', '-m', `Keep Chompyy card #${card.id}: ${card.title}`, run.branch]);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
try {
|
|
150
|
+
git(root, ['merge', '--abort']);
|
|
151
|
+
}
|
|
152
|
+
catch { }
|
|
153
|
+
throw new Error(`${run.branch} conflicts with ${into}: another card or your own work changed the same lines. Nothing was changed. Run it again on top of the latest with \`chompyy redo ${card.id}\` (or merge by hand: git -C ${root} merge ${run.branch}).`);
|
|
154
|
+
}
|
|
155
|
+
removeWorktree(root, card);
|
|
156
|
+
git(root, ['branch', '-d', run.branch]);
|
|
157
|
+
const note = yours.length ? ` Your ${yours.length} unsaved change${yours.length === 1 ? ' was' : 's were'} left as they were.` : '';
|
|
158
|
+
return `Kept #${card.id}: merged ${run.branch} into ${into}.${note} Undo it with \`git -C ${root} reset --hard HEAD~1\`.`;
|
|
159
|
+
}
|
|
160
|
+
/** Throw the run away: remove the worktree and branch (or the draft folder). */
|
|
161
|
+
export function undoCard(card) {
|
|
162
|
+
const run = ran(card);
|
|
163
|
+
if (!run.branch) {
|
|
164
|
+
rmSync(run.workdir, { recursive: true, force: true });
|
|
165
|
+
return `Undone #${card.id}: removed the draft folder.`;
|
|
166
|
+
}
|
|
167
|
+
const root = gitRoot(card.cwd);
|
|
168
|
+
if (!root)
|
|
169
|
+
throw new Error(`${card.cwd} is no longer a git repo.`);
|
|
170
|
+
removeWorktree(root, card);
|
|
171
|
+
git(root, ['branch', '-D', run.branch]);
|
|
172
|
+
return `Undone #${card.id}: removed branch ${run.branch}. Your own branches were never touched.`;
|
|
173
|
+
}
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
// The one seam: something that runs a prompt headless. ClaudeRunner wraps `claude -p`;
|
|
2
|
+
// tests pass a fake.
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
import { closeSync, openSync, writeSync } from 'node:fs';
|
|
5
|
+
/** The raw output written to disk, cut off after `max` bytes (with a note saying so). */
|
|
6
|
+
export class RawLog {
|
|
7
|
+
max;
|
|
8
|
+
fd = null;
|
|
9
|
+
written = 0;
|
|
10
|
+
constructor(path, max = 50 * 1024 * 1024) {
|
|
11
|
+
this.max = max;
|
|
12
|
+
if (!path)
|
|
13
|
+
return;
|
|
14
|
+
try {
|
|
15
|
+
this.fd = openSync(path, 'w');
|
|
16
|
+
}
|
|
17
|
+
catch { }
|
|
18
|
+
}
|
|
19
|
+
write(chunk) {
|
|
20
|
+
if (this.fd === null)
|
|
21
|
+
return;
|
|
22
|
+
const room = this.max - this.written;
|
|
23
|
+
const buf = Buffer.from(chunk);
|
|
24
|
+
if (buf.length <= room) {
|
|
25
|
+
writeSync(this.fd, buf);
|
|
26
|
+
this.written += buf.length;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (room > 0)
|
|
30
|
+
writeSync(this.fd, buf.subarray(0, room));
|
|
31
|
+
writeSync(this.fd, `\n[raw log cut off at ${this.max} bytes]\n`);
|
|
32
|
+
this.written = this.max;
|
|
33
|
+
this.close();
|
|
34
|
+
}
|
|
35
|
+
close() {
|
|
36
|
+
if (this.fd !== null)
|
|
37
|
+
closeSync(this.fd);
|
|
38
|
+
this.fd = null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export function claudeArgs(req) {
|
|
42
|
+
const args = req.loopRepeat
|
|
43
|
+
? ['-p', '--output-format', 'stream-json', '--verbose', '--no-session-persistence']
|
|
44
|
+
: ['-p', '--output-format', 'text', '--no-session-persistence'];
|
|
45
|
+
if (req.model)
|
|
46
|
+
args.push('--model', req.model);
|
|
47
|
+
if (req.maxTurns)
|
|
48
|
+
args.push('--max-turns', String(req.maxTurns));
|
|
49
|
+
if (req.tools !== undefined)
|
|
50
|
+
args.push('--tools', req.tools);
|
|
51
|
+
if (req.permissionMode)
|
|
52
|
+
args.push('--permission-mode', req.permissionMode);
|
|
53
|
+
if (req.permissionPrompts)
|
|
54
|
+
args.push('--permission-prompts', req.permissionPrompts);
|
|
55
|
+
if (req.allowedTools?.length)
|
|
56
|
+
args.push('--allowedTools', ...req.allowedTools);
|
|
57
|
+
if (req.disallowedTools?.length)
|
|
58
|
+
args.push('--disallowedTools', ...req.disallowedTools);
|
|
59
|
+
if (req.settings)
|
|
60
|
+
args.push('--settings', JSON.stringify(req.settings));
|
|
61
|
+
if (req.extraArgs?.length)
|
|
62
|
+
args.push(...req.extraArgs);
|
|
63
|
+
return args;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Circuit breaker (ralph-claude-code, codeburn guard): notices a run going in circles.
|
|
67
|
+
* - the same tool call (tool + exact input) `repeat` times among the last 20 calls, or
|
|
68
|
+
* - the same shell command failing `repeat - 1` times in a row.
|
|
69
|
+
*/
|
|
70
|
+
export class LoopWatch {
|
|
71
|
+
repeat;
|
|
72
|
+
calls = [];
|
|
73
|
+
pending = new Map();
|
|
74
|
+
lastFailed = '';
|
|
75
|
+
failStreak = 0;
|
|
76
|
+
constructor(repeat) {
|
|
77
|
+
this.repeat = repeat;
|
|
78
|
+
}
|
|
79
|
+
/** Feed one stream-json event; returns why it is stuck, or null. */
|
|
80
|
+
feed(event) {
|
|
81
|
+
const e = event;
|
|
82
|
+
const content = Array.isArray(e.message?.content) ? e.message.content : [];
|
|
83
|
+
if (e.type === 'assistant') {
|
|
84
|
+
for (const block of content) {
|
|
85
|
+
if (block.type !== 'tool_use')
|
|
86
|
+
continue;
|
|
87
|
+
// The free-text description can differ between otherwise identical calls.
|
|
88
|
+
const { description: _d, ...input } = (block.input ?? {});
|
|
89
|
+
const sig = `${block.name}(${JSON.stringify(input)})`;
|
|
90
|
+
this.pending.set(String(block.id), sig);
|
|
91
|
+
this.calls = [...this.calls, sig].slice(-20);
|
|
92
|
+
const times = this.calls.filter((c) => c === sig).length;
|
|
93
|
+
if (times >= this.repeat)
|
|
94
|
+
return `called ${short(sig)} ${times} times`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (e.type === 'user') {
|
|
98
|
+
for (const block of content) {
|
|
99
|
+
if (block.type !== 'tool_result')
|
|
100
|
+
continue;
|
|
101
|
+
const sig = this.pending.get(String(block.tool_use_id)) ?? '';
|
|
102
|
+
if (!sig.startsWith('Bash('))
|
|
103
|
+
continue;
|
|
104
|
+
if (block.is_error) {
|
|
105
|
+
this.failStreak = sig === this.lastFailed ? this.failStreak + 1 : 1;
|
|
106
|
+
this.lastFailed = sig;
|
|
107
|
+
if (this.failStreak >= Math.max(2, this.repeat - 1))
|
|
108
|
+
return `${short(sig)} failed ${this.failStreak} times in a row`;
|
|
109
|
+
}
|
|
110
|
+
else if (sig === this.lastFailed) {
|
|
111
|
+
this.failStreak = 0;
|
|
112
|
+
this.lastFailed = '';
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function short(sig) {
|
|
120
|
+
return sig.length > 120 ? `${sig.slice(0, 117)}…` : sig;
|
|
121
|
+
}
|
|
122
|
+
/** The final text of a stream-json run: the result event, else the assistant's text blocks. */
|
|
123
|
+
export function streamText(events) {
|
|
124
|
+
const t = new FinalText();
|
|
125
|
+
for (const e of events)
|
|
126
|
+
t.feed(e);
|
|
127
|
+
return t.text();
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Keeps only what the final text needs: the result event, else the assistant's text blocks (capped).
|
|
131
|
+
* Not every event: with --verbose the stream carries whole tool results (file reads, build logs), and keeping
|
|
132
|
+
* them all is what ran an 8-hour away out of memory on 2026-11-17.
|
|
133
|
+
*/
|
|
134
|
+
export class FinalText {
|
|
135
|
+
max;
|
|
136
|
+
result = null;
|
|
137
|
+
texts = [];
|
|
138
|
+
size = 0;
|
|
139
|
+
constructor(max = 256 * 1024) {
|
|
140
|
+
this.max = max;
|
|
141
|
+
}
|
|
142
|
+
feed(event) {
|
|
143
|
+
const e = event;
|
|
144
|
+
if (e.type === 'result' && typeof e.result === 'string')
|
|
145
|
+
this.result = e.result;
|
|
146
|
+
if (e.type !== 'assistant' || !Array.isArray(e.message?.content))
|
|
147
|
+
return;
|
|
148
|
+
for (const b of e.message.content) {
|
|
149
|
+
if (b?.type !== 'text' || !b.text)
|
|
150
|
+
continue;
|
|
151
|
+
this.texts.push(b.text);
|
|
152
|
+
this.size += b.text.length;
|
|
153
|
+
while (this.size > this.max && this.texts.length > 1)
|
|
154
|
+
this.size -= this.texts.shift().length;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
text() {
|
|
158
|
+
return this.result ?? this.texts.join('\n');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** A stream-json line longer than this is a giant tool result we don't need: skip it rather than buffer it. */
|
|
162
|
+
export const MAX_LINE = 4 * 1024 * 1024;
|
|
163
|
+
/**
|
|
164
|
+
* Splits a stream into lines in constant memory per line: looks for newlines only in the new chunk (never
|
|
165
|
+
* re-splits what is buffered), and drops a line once it grows past `maxLine`.
|
|
166
|
+
*/
|
|
167
|
+
export class LineReader {
|
|
168
|
+
onLine;
|
|
169
|
+
maxLine;
|
|
170
|
+
buf = '';
|
|
171
|
+
skipping = false;
|
|
172
|
+
constructor(onLine, maxLine = MAX_LINE) {
|
|
173
|
+
this.onLine = onLine;
|
|
174
|
+
this.maxLine = maxLine;
|
|
175
|
+
}
|
|
176
|
+
push(chunk) {
|
|
177
|
+
let start = 0;
|
|
178
|
+
let nl;
|
|
179
|
+
while ((nl = chunk.indexOf('\n', start)) !== -1) {
|
|
180
|
+
if (!this.skipping) {
|
|
181
|
+
const line = this.buf + chunk.slice(start, nl);
|
|
182
|
+
if (line.length <= this.maxLine)
|
|
183
|
+
this.onLine(line);
|
|
184
|
+
}
|
|
185
|
+
this.buf = '';
|
|
186
|
+
this.skipping = false;
|
|
187
|
+
start = nl + 1;
|
|
188
|
+
}
|
|
189
|
+
if (this.skipping || start === chunk.length)
|
|
190
|
+
return;
|
|
191
|
+
if (this.buf.length + chunk.length - start > this.maxLine) {
|
|
192
|
+
this.buf = '';
|
|
193
|
+
this.skipping = true;
|
|
194
|
+
}
|
|
195
|
+
else
|
|
196
|
+
this.buf += chunk.slice(start);
|
|
197
|
+
}
|
|
198
|
+
end() {
|
|
199
|
+
if (!this.skipping && this.buf.trim())
|
|
200
|
+
this.onLine(this.buf);
|
|
201
|
+
this.buf = '';
|
|
202
|
+
this.skipping = false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/** Text that keeps its head and its tail once it passes `max` (CHECKS is at the end, the summary at the start). */
|
|
206
|
+
export class CappedText {
|
|
207
|
+
max;
|
|
208
|
+
head = '';
|
|
209
|
+
tail = '';
|
|
210
|
+
dropped = 0;
|
|
211
|
+
constructor(max = 2 * 1024 * 1024) {
|
|
212
|
+
this.max = max;
|
|
213
|
+
}
|
|
214
|
+
push(chunk) {
|
|
215
|
+
const half = this.max / 2;
|
|
216
|
+
if (this.head.length < half) {
|
|
217
|
+
const take = chunk.slice(0, half - this.head.length);
|
|
218
|
+
this.head += take;
|
|
219
|
+
chunk = chunk.slice(take.length);
|
|
220
|
+
}
|
|
221
|
+
this.tail += chunk;
|
|
222
|
+
if (this.tail.length > half) {
|
|
223
|
+
this.dropped += this.tail.length - half;
|
|
224
|
+
this.tail = this.tail.slice(-half);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
toString() {
|
|
228
|
+
return this.dropped ? `${this.head}\n[… ${this.dropped} characters cut …]\n${this.tail}` : this.head + this.tail;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/** Process groups of agents still running, so Ctrl-C on chompyy stops them too. */
|
|
232
|
+
const active = new Set();
|
|
233
|
+
let handlersInstalled = false;
|
|
234
|
+
function stopActiveOnExit() {
|
|
235
|
+
if (handlersInstalled)
|
|
236
|
+
return;
|
|
237
|
+
handlersInstalled = true;
|
|
238
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
239
|
+
process.once(signal, () => {
|
|
240
|
+
for (const pid of active) {
|
|
241
|
+
try {
|
|
242
|
+
process.kill(-pid, 'SIGTERM');
|
|
243
|
+
}
|
|
244
|
+
catch { }
|
|
245
|
+
}
|
|
246
|
+
process.exit(130);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
export class ClaudeRunner {
|
|
251
|
+
bin;
|
|
252
|
+
constructor(bin = 'claude') {
|
|
253
|
+
this.bin = bin;
|
|
254
|
+
}
|
|
255
|
+
run(req) {
|
|
256
|
+
const started = Date.now();
|
|
257
|
+
return new Promise((resolve) => {
|
|
258
|
+
// The prompt goes in on stdin: no argument-length limits, nothing in `ps`.
|
|
259
|
+
// Own process group, so a timeout also stops commands the agent started (tests, builds).
|
|
260
|
+
const child = spawn(this.bin, claudeArgs(req), { cwd: req.cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: true, env: { ...process.env, ...req.env } });
|
|
261
|
+
stopActiveOnExit();
|
|
262
|
+
if (child.pid) {
|
|
263
|
+
active.add(child.pid);
|
|
264
|
+
req.onSpawn?.(child.pid);
|
|
265
|
+
}
|
|
266
|
+
const killAll = (signal) => {
|
|
267
|
+
try {
|
|
268
|
+
if (child.pid)
|
|
269
|
+
process.kill(-child.pid, signal);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
child.kill(signal);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
const text = new CappedText();
|
|
276
|
+
const stderr = new CappedText(256 * 1024);
|
|
277
|
+
let timedOut = false;
|
|
278
|
+
let stuck;
|
|
279
|
+
const final = new FinalText();
|
|
280
|
+
const raw = new RawLog(req.rawLogPath, req.rawLogMaxBytes);
|
|
281
|
+
const watch = req.loopRepeat ? new LoopWatch(req.loopRepeat) : null;
|
|
282
|
+
const lines = new LineReader((line) => {
|
|
283
|
+
if (!line.trim())
|
|
284
|
+
return;
|
|
285
|
+
let event;
|
|
286
|
+
try {
|
|
287
|
+
event = JSON.parse(line);
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
final.feed(event);
|
|
293
|
+
const why = stuck ? null : watch.feed(event);
|
|
294
|
+
if (why) {
|
|
295
|
+
stuck = why;
|
|
296
|
+
killAll('SIGTERM');
|
|
297
|
+
setTimeout(() => killAll('SIGKILL'), 5000).unref();
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
child.stdout.setEncoding('utf8');
|
|
301
|
+
child.stderr.setEncoding('utf8');
|
|
302
|
+
// No-progress watchdog: any output counts as progress (stream-json prints every tool call and result).
|
|
303
|
+
let stalled;
|
|
304
|
+
let idle;
|
|
305
|
+
const poke = () => {
|
|
306
|
+
if (!req.idleTimeoutMs)
|
|
307
|
+
return;
|
|
308
|
+
clearTimeout(idle);
|
|
309
|
+
idle = setTimeout(() => {
|
|
310
|
+
stalled = `no progress for ${Math.round(req.idleTimeoutMs / 60_000)}m`;
|
|
311
|
+
killAll('SIGTERM');
|
|
312
|
+
setTimeout(() => killAll('SIGKILL'), 5000).unref();
|
|
313
|
+
}, req.idleTimeoutMs);
|
|
314
|
+
};
|
|
315
|
+
poke();
|
|
316
|
+
child.stdout.on('data', (d) => {
|
|
317
|
+
poke();
|
|
318
|
+
raw.write(d);
|
|
319
|
+
if (watch)
|
|
320
|
+
lines.push(d);
|
|
321
|
+
else
|
|
322
|
+
text.push(d);
|
|
323
|
+
});
|
|
324
|
+
child.stderr.on('data', (d) => {
|
|
325
|
+
poke();
|
|
326
|
+
stderr.push(d);
|
|
327
|
+
});
|
|
328
|
+
const timer = setTimeout(() => {
|
|
329
|
+
timedOut = true;
|
|
330
|
+
killAll('SIGTERM');
|
|
331
|
+
setTimeout(() => killAll('SIGKILL'), 5000).unref();
|
|
332
|
+
}, req.timeoutMs);
|
|
333
|
+
const done = (exitCode) => {
|
|
334
|
+
clearTimeout(timer);
|
|
335
|
+
clearTimeout(idle);
|
|
336
|
+
raw.close();
|
|
337
|
+
if (child.pid)
|
|
338
|
+
active.delete(child.pid);
|
|
339
|
+
if (watch)
|
|
340
|
+
lines.end();
|
|
341
|
+
const output = watch ? final.text() : text.toString();
|
|
342
|
+
resolve({ exitCode, output, stderr: stderr.toString(), timedOut, durationMs: Date.now() - started, ...(stuck ? { stuck } : {}), ...(stalled ? { stalled } : {}) });
|
|
343
|
+
};
|
|
344
|
+
child.on('error', (err) => {
|
|
345
|
+
stderr.push(String(err));
|
|
346
|
+
done(null);
|
|
347
|
+
});
|
|
348
|
+
child.on('close', (code) => done(code));
|
|
349
|
+
child.stdin.on('error', () => { }); // child may exit before reading
|
|
350
|
+
child.stdin.end(req.prompt);
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
export function claudeAvailable(bin = 'claude') {
|
|
355
|
+
const r = spawnSync(bin, ['--version'], { stdio: 'ignore', timeout: 10_000 });
|
|
356
|
+
return r.status === 0;
|
|
357
|
+
}
|