sumo-agents 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/AGENTS.md +38 -0
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/bin/sumo.mjs +33 -0
- package/guides/delegation.md +33 -0
- package/guides/feature.md +14 -0
- package/guides/fix.md +14 -0
- package/guides/memory.md +23 -0
- package/guides/projects.md +27 -0
- package/guides/review.md +16 -0
- package/guides/workflows.md +26 -0
- package/logo.txt +19 -0
- package/package.json +42 -4
- package/prompts/agent.md +7 -0
- package/prompts/dream.md +13 -0
- package/prompts/scribe.md +21 -0
- package/spinner.txt +90 -0
- package/src/advisor.mjs +59 -0
- package/src/apply.mjs +368 -0
- package/src/auth.mjs +80 -0
- package/src/card.mjs +72 -0
- package/src/catalog.mjs +167 -0
- package/src/chat.mjs +1162 -0
- package/src/cli.mjs +815 -0
- package/src/cost.mjs +128 -0
- package/src/db.mjs +384 -0
- package/src/dream.mjs +97 -0
- package/src/editor.mjs +198 -0
- package/src/export.mjs +132 -0
- package/src/guard.mjs +121 -0
- package/src/guides.mjs +86 -0
- package/src/herdr.mjs +117 -0
- package/src/hooks.mjs +270 -0
- package/src/images.mjs +89 -0
- package/src/jobs.mjs +1184 -0
- package/src/jobtools.mjs +82 -0
- package/src/local-server.mjs +169 -0
- package/src/lock.mjs +45 -0
- package/src/loop.mjs +838 -0
- package/src/mcp.mjs +604 -0
- package/src/memory.mjs +400 -0
- package/src/model.mjs +270 -0
- package/src/page.html +304 -0
- package/src/page.mjs +135 -0
- package/src/paths.mjs +33 -0
- package/src/prime.mjs +177 -0
- package/src/projects.mjs +232 -0
- package/src/recall.mjs +45 -0
- package/src/redact.mjs +173 -0
- package/src/render.mjs +45 -0
- package/src/route.mjs +287 -0
- package/src/sandbox.mjs +173 -0
- package/src/scan.mjs +204 -0
- package/src/scribe.mjs +349 -0
- package/src/sessions.mjs +371 -0
- package/src/setup.mjs +528 -0
- package/src/sqlite.mjs +66 -0
- package/src/text.mjs +97 -0
- package/src/tools.mjs +987 -0
- package/src/transcript.mjs +106 -0
- package/src/tty.mjs +529 -0
- package/src/ui.mjs +1363 -0
- package/src/verify.mjs +369 -0
- package/src/web.mjs +49 -0
- package/src/workflows.mjs +270 -0
- package/src/worktree.mjs +128 -0
package/src/route.mjs
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { MODELS, usableModels } from './catalog.mjs';
|
|
2
|
+
import { callLocalModel } from './model.mjs';
|
|
3
|
+
import { UsageError } from './memory.mjs';
|
|
4
|
+
import { elapsed } from './text.mjs';
|
|
5
|
+
|
|
6
|
+
export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
7
|
+
/** A failed job can always be retried; a done one only once review found enough wrong with it — and either retry goes up. */
|
|
8
|
+
export const RETRY_IMPORTANT_THRESHOLD = 3;
|
|
9
|
+
|
|
10
|
+
const KINDS = ['mechanical', 'routine', 'hard', 'novel'];
|
|
11
|
+
const SURFACES = ['one spot', 'a few files', 'many interacting parts'];
|
|
12
|
+
|
|
13
|
+
const ROUTER_SYSTEM =
|
|
14
|
+
'You assign a coding job to a model and an effort level. Answer with JSON only. First classify the job, then choose. kind: mechanical (typos, ' +
|
|
15
|
+
'renames, comments, constants, tests for a pure function), routine (an ordinary feature or fix with a clear spec), hard (design, a bug whose ' +
|
|
16
|
+
'cause is unknown, or reviewing risky code), novel (new algorithms, subtle concurrency, deep security review). surface: how much code the job ' +
|
|
17
|
+
'touches. risky: true when it touches security, credentials, money, migrations or concurrency. Model follows kind: haiku for mechanical (it ' +
|
|
18
|
+
'takes no effort setting), sonnet for routine, opus for hard, fable for novel. Effort follows surface: low for one spot, medium for a few ' +
|
|
19
|
+
'files, high for many interacting parts. risky raises the effort one step (low, medium, high, xhigh, max) and makes a routine job hard. ' +
|
|
20
|
+
'History lists only the routes that failed or drew Important review findings on this project: for work like that, go above them.';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The same grammar read for a scout, which reads and reports and changes nothing: the kinds above are told in terms of
|
|
24
|
+
* changing code, and read that way an audit is "novel" and a summary of an unfamiliar project is too — the dearest model
|
|
25
|
+
* for work that is reading. Here they are told in terms of what a reading job asks for.
|
|
26
|
+
*/
|
|
27
|
+
const SCOUT_ROUTER_SYSTEM =
|
|
28
|
+
'You assign a reading job to a model and an effort level. The job is done by a scout: it reads code and reports, and changes nothing. ' +
|
|
29
|
+
'Answer with JSON only. First classify the job, then choose. kind: mechanical (one lookup: where one thing is defined, what one setting ' +
|
|
30
|
+
'is), routine (finding, tracing, listing, describing or summarizing code: what a project does, how a feature works, which endpoints ' +
|
|
31
|
+
'exist, which dependencies are behind — however large or unfamiliar the project), hard (it must judge: an audit of security or ' +
|
|
32
|
+
'correctness, a review, a hunt for the cause of a bug), novel (almost never: only reasoning nobody has written down, such as proving a ' +
|
|
33
|
+
'concurrent algorithm correct). surface: how much code must be read. risky: true when what is judged is security, credentials, money, ' +
|
|
34
|
+
'migrations or concurrency. Model follows kind: haiku for mechanical (it takes no effort setting), sonnet for routine, opus for hard, ' +
|
|
35
|
+
'fable for novel. Effort follows surface: low for one spot, medium for a few files or a whole project read for a summary, high when ' +
|
|
36
|
+
'many interacting parts must be judged together. risky raises the effort one step (low, medium, high, xhigh, max). ' +
|
|
37
|
+
'History lists only the routes that failed or drew Important review findings on this project: for work like that, go above them.';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One answer shape per pairing, so the grammar itself cannot give haiku an effort or another model none.
|
|
41
|
+
* The classification comes first: a small model that names the route first just repeats a route it was
|
|
42
|
+
* shown, and one that has described the job first chooses from the description.
|
|
43
|
+
*/
|
|
44
|
+
const answerShape = (models, efforts) => ({
|
|
45
|
+
type: 'object',
|
|
46
|
+
properties: {
|
|
47
|
+
kind: { type: 'string', enum: KINDS },
|
|
48
|
+
surface: { type: 'string', enum: SURFACES },
|
|
49
|
+
risky: { type: 'boolean' },
|
|
50
|
+
model: { type: 'string', enum: models },
|
|
51
|
+
effort: { type: 'string', enum: efforts },
|
|
52
|
+
reason: { type: 'string', maxLength: 200 },
|
|
53
|
+
},
|
|
54
|
+
required: ['kind', 'surface', 'risky', 'model', 'effort', 'reason'],
|
|
55
|
+
additionalProperties: false,
|
|
56
|
+
});
|
|
57
|
+
/** The grammar over the models that are on: the haiku branch while haiku is, the effort branch over the others. */
|
|
58
|
+
const routerSchema = (usable) => ({
|
|
59
|
+
anyOf: [
|
|
60
|
+
...(usable.includes('haiku') ? [answerShape(['haiku'], ['none'])] : []),
|
|
61
|
+
...(usable.some((m) => m !== 'haiku') ? [answerShape(usable.filter((m) => m !== 'haiku'), EFFORTS)] : []),
|
|
62
|
+
],
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const TASK_CUT = 3500;
|
|
66
|
+
|
|
67
|
+
/** Per model/effort, over this project's finished jobs: how many, how many reviewed, and how they scored. */
|
|
68
|
+
export function routeStats(db, { project } = {}) {
|
|
69
|
+
const where = [`model IS NOT NULL`, `status IN ('done', 'failed')`];
|
|
70
|
+
const params = [];
|
|
71
|
+
if (project) {
|
|
72
|
+
where.push('project = ?');
|
|
73
|
+
params.push(project);
|
|
74
|
+
}
|
|
75
|
+
return db
|
|
76
|
+
.prepare(
|
|
77
|
+
`SELECT model, effort,
|
|
78
|
+
COUNT(*) AS jobs,
|
|
79
|
+
SUM(status = 'done') AS done,
|
|
80
|
+
SUM(status = 'failed') AS failed,
|
|
81
|
+
SUM(important IS NOT NULL) AS reviewed,
|
|
82
|
+
AVG(important) AS avg_important
|
|
83
|
+
FROM jobs WHERE ${where.join(' AND ')} GROUP BY model, effort ORDER BY model, effort`,
|
|
84
|
+
)
|
|
85
|
+
.all(...params)
|
|
86
|
+
.map((r) => ({ model: r.model, effort: r.effort, jobs: r.jobs, done: r.done, failed: r.failed, reviewed: r.reviewed, avgImportant: r.avg_important }));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Only evidence against a route is shown. A clean record says nothing about what a cheaper route
|
|
91
|
+
* would have done, and the router repeats whatever route it sees praised — so a project that
|
|
92
|
+
* started on the dearest one would never leave it.
|
|
93
|
+
*/
|
|
94
|
+
function historyText(db, projectSlug) {
|
|
95
|
+
const rows = routeStats(db, { project: projectSlug }).filter((r) => r.failed > 0 || r.avgImportant > 0);
|
|
96
|
+
if (rows.length === 0) return 'no history yet';
|
|
97
|
+
return rows
|
|
98
|
+
.map(
|
|
99
|
+
(r) =>
|
|
100
|
+
`${r.model}/${r.effort}: ${r.jobs} job${r.jobs === 1 ? '' : 's'}, ${r.done} done, ${r.failed} failed, ${r.reviewed} reviewed${
|
|
101
|
+
r.reviewed > 0 ? `, avg ${r.avgImportant.toFixed(1)} Important findings` : ''
|
|
102
|
+
}`,
|
|
103
|
+
)
|
|
104
|
+
.join('\n');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* `jobs, done, failed, reviewed, avg important` — one line per role and model/effort seen, and, where the ledger holds a
|
|
109
|
+
* job's requests, what a job on that route took on average: requests, time, money. A route's price is what a job on it
|
|
110
|
+
* costs, not what a token on it costs — a cheap model that takes ten times the requests is the dear one.
|
|
111
|
+
*/
|
|
112
|
+
export function statsLines(db, { project } = {}) {
|
|
113
|
+
const rows = db
|
|
114
|
+
.prepare(
|
|
115
|
+
`SELECT j.agent, j.model, j.effort, COUNT(*) AS jobs, SUM(j.status = 'done') AS done, SUM(j.status = 'failed') AS failed,
|
|
116
|
+
SUM(j.important IS NOT NULL) AS reviewed, AVG(j.important) AS important,
|
|
117
|
+
AVG(r.requests) AS requests, AVG(r.seconds) AS seconds, AVG(r.cost) AS cost
|
|
118
|
+
FROM jobs j
|
|
119
|
+
LEFT JOIN (SELECT job_id, COUNT(*) AS requests, SUM(cost_usd) AS cost, (julianday(MAX(ts)) - julianday(MIN(ts))) * 86400 AS seconds
|
|
120
|
+
FROM model_runs WHERE job_id IS NOT NULL GROUP BY job_id) r ON r.job_id = j.id
|
|
121
|
+
WHERE j.model IS NOT NULL AND j.status IN ('done', 'failed')${project ? ' AND j.project = ?' : ''}
|
|
122
|
+
GROUP BY j.agent, j.model, j.effort ORDER BY j.agent, j.model, j.effort`,
|
|
123
|
+
)
|
|
124
|
+
.all(...(project ? [project] : []));
|
|
125
|
+
if (rows.length === 0) return ['no finished jobs yet'];
|
|
126
|
+
return rows.map(
|
|
127
|
+
(r) =>
|
|
128
|
+
`${r.agent} · ${r.model}/${r.effort}: ${r.jobs} job${r.jobs === 1 ? '' : 's'}, ${r.done} done, ${r.failed} failed, ${r.reviewed} reviewed, avg ${r.reviewed > 0 ? r.important.toFixed(1) : '-'} important` +
|
|
129
|
+
(r.requests === null ? '' : ` — a job: ${Math.round(r.requests)} request${Math.round(r.requests) === 1 ? '' : 's'}, ${elapsed(Math.round(r.seconds) * 1000)}, $${r.cost.toFixed(2)}`),
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function stackOf(db, projectSlug) {
|
|
134
|
+
const row = db.prepare(`SELECT body FROM memories WHERE scope = ? AND scan_key = 'stack' AND state = 'active'`).get(`project:${projectSlug}`);
|
|
135
|
+
return row ? row.body.replace(/^stack:\s*/, '') : null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** What the job being retried ran on and how it ended — without it, a retry is routed exactly like the attempt that failed. */
|
|
139
|
+
function retryLine(db, retryOf) {
|
|
140
|
+
const prev = db.prepare('SELECT model, effort, status, important FROM jobs WHERE id = ?').get(retryOf);
|
|
141
|
+
if (!prev) return null;
|
|
142
|
+
const outcome = prev.status === 'failed' ? 'failed' : `was reviewed with ${prev.important ?? 0} Important findings`;
|
|
143
|
+
return `retry of j${retryOf}: it ran on ${prev.model ?? 'no recorded route'}${prev.effort ? `/${prev.effort}` : ''} and ${outcome}`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function routerPrompt(db, { agent, project, task, title, retryOf }) {
|
|
147
|
+
const stack = stackOf(db, project.slug);
|
|
148
|
+
return [
|
|
149
|
+
`role: ${agent}`,
|
|
150
|
+
`project: ${project.slug}${stack ? ` (${stack})` : ''}`,
|
|
151
|
+
`models: ${usableModels(db).join(', ')}`,
|
|
152
|
+
...(retryOf === undefined ? [] : [retryLine(db, retryOf)].filter(Boolean)),
|
|
153
|
+
'history:',
|
|
154
|
+
historyText(db, project.slug),
|
|
155
|
+
`title: ${title ?? ''}`,
|
|
156
|
+
'',
|
|
157
|
+
String(task ?? '').slice(0, TASK_CUT),
|
|
158
|
+
].join('\n');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The same grammar read for a chat turn: the message is the whole job, there is no brief to size it by
|
|
163
|
+
* and no history of turns, so the kinds are told in terms of what a message asks for.
|
|
164
|
+
*/
|
|
165
|
+
const CHAT_ROUTER_SYSTEM =
|
|
166
|
+
'You assign one chat turn to a model and an effort level. The chat is a coding assistant with a shell and an editor; the turn is what the ' +
|
|
167
|
+
'user just typed. Answer with JSON only. First classify the turn, then choose. kind: mechanical (a one-line question, a lookup, a typo, a ' +
|
|
168
|
+
'rename, running a command and reporting), routine (an ordinary feature or fix with a clear ask, a summary, an explanation), hard (design, ' +
|
|
169
|
+
'a bug whose cause is unknown, a review of risky code, planning across a codebase), novel (new algorithms, subtle concurrency, deep security ' +
|
|
170
|
+
'review). surface: how much code the turn touches. risky: true when it touches security, credentials, money, migrations or concurrency. ' +
|
|
171
|
+
'Model follows kind: haiku for mechanical (it takes no effort setting), sonnet for routine, opus for hard, fable for novel. Effort follows ' +
|
|
172
|
+
'surface: low for one spot, medium for a few files, high for many interacting parts. risky raises the effort one step (low, medium, high, ' +
|
|
173
|
+
'xhigh, max) and makes a routine turn hard.';
|
|
174
|
+
|
|
175
|
+
function chatRouterPrompt(db, { project, text }) {
|
|
176
|
+
const stack = project ? stackOf(db, project.slug) : null;
|
|
177
|
+
return [`project: ${project ? `${project.slug}${stack ? ` (${stack})` : ''}` : 'none'}`, `models: ${usableModels(db).join(', ')}`, 'turn:', String(text ?? '').slice(0, TASK_CUT)].join('\n');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const askRouter = (db, { agent, project, task, title, retryOf }) => askFor(db, agent === 'scout' ? SCOUT_ROUTER_SYSTEM : ROUTER_SYSTEM, routerPrompt(db, { agent, project, task, title, retryOf }));
|
|
181
|
+
|
|
182
|
+
async function askFor(db, system, prompt) {
|
|
183
|
+
const usable = usableModels(db);
|
|
184
|
+
if (usable.length === 0) throw new UsageError('no model is on — sumo models enable <name>');
|
|
185
|
+
const result = await callLocalModel(db, { system, prompt, schema: routerSchema(usable) });
|
|
186
|
+
if (!result.ok) return { ok: false, error: result.error };
|
|
187
|
+
const { model, effort, reason, risky } = result.data ?? {};
|
|
188
|
+
// The same pairing the schema enforces, checked again: a backend without grammar support can still answer anything.
|
|
189
|
+
const fits = usable.includes(model) && (model === 'haiku' ? effort === 'none' : EFFORTS.includes(effort));
|
|
190
|
+
if (!fits || typeof reason !== 'string' || !reason.trim()) return { ok: false, error: `the router answered outside its schema: ${JSON.stringify(result.data)}` };
|
|
191
|
+
// Whether the work touches security, credentials, money, migrations or concurrency: kept, so such work is reviewed. Only a plain yes is one.
|
|
192
|
+
return { ok: true, model, effort, reason: reason.replace(/\s+/g, ' ').trim(), risky: risky === true };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Routes compared on one scale: by model first, cheapest to dearest as the catalog lists them, then by effort.
|
|
196
|
+
// Haiku's 'none' sits below every effort.
|
|
197
|
+
const modelRank = (model) => MODELS.indexOf(model);
|
|
198
|
+
const effortRank = (effort) => EFFORTS.indexOf(effort);
|
|
199
|
+
const compareRoutes = (a, b) => modelRank(a.model) - modelRank(b.model) || effortRank(a.effort) - effortRank(b.effort);
|
|
200
|
+
|
|
201
|
+
/** One step above a route: the next model up that is on, keeping the effort (medium, off haiku); on the top one, one effort up, max at most. */
|
|
202
|
+
function stepAbove({ model, effort }, usable) {
|
|
203
|
+
const next = usable.find((m) => modelRank(m) > modelRank(model));
|
|
204
|
+
if (next) return { model: next, effort: EFFORTS.includes(effort) ? effort : 'medium' };
|
|
205
|
+
const top = usable.at(-1);
|
|
206
|
+
if (top === 'haiku') return { model: top, effort: 'none' };
|
|
207
|
+
return { model: top, effort: EFFORTS[Math.min(effortRank(effort) + 1, EFFORTS.length - 1)] };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* What code does to the router's answer before it is a job's route. The router reads only the task's words, the weakest
|
|
212
|
+
* thing to route by, and is merely asked to go above what failed; on the ledger, workers that started on fable finished
|
|
213
|
+
* 2 of 5 at more than twice the price of opus, which finished 5 of 6. So these hold whatever it answers:
|
|
214
|
+
* - A first attempt starts lower: a worker's never runs on fable while opus is on, and no first attempt runs above high effort.
|
|
215
|
+
* - A scout's first attempt does not run on haiku while sonnet is on: on the ledger, haiku scouts left 3 of 11 unfinished,
|
|
216
|
+
* sonnet and opus ones none of 9 — and haiku caches nothing below 4,096 tokens. It runs on sonnet at low effort instead.
|
|
217
|
+
* - A retry of a job that failed, or that drew RETRY_IMPORTANT_THRESHOLD Important findings, runs at least one step above it.
|
|
218
|
+
* - A reviewer pointed at a job runs on at least that job's model, at medium effort or more.
|
|
219
|
+
* Pure: `retryOf` and `reviews` are the rows (id, model, effort, status, important) of the job retried and the job judged,
|
|
220
|
+
* or nothing; `usable` is the models that are on, cheapest first. An attempt with no route Sumo knows has nothing to go
|
|
221
|
+
* above. `policy` says what changed and why, or is null.
|
|
222
|
+
*/
|
|
223
|
+
export function routePolicy({ agent, routed, retryOf: prev, reviews: target, usable }) {
|
|
224
|
+
let route = { model: routed.model, effort: routed.effort };
|
|
225
|
+
const why = [];
|
|
226
|
+
if (!prev) {
|
|
227
|
+
if (agent === 'worker' && route.model === 'fable' && usable.includes('opus')) {
|
|
228
|
+
route.model = 'opus';
|
|
229
|
+
why.push('a first attempt starts on opus, not fable');
|
|
230
|
+
}
|
|
231
|
+
if (agent === 'scout' && route.model === 'haiku' && usable.includes('sonnet')) {
|
|
232
|
+
route = { model: 'sonnet', effort: 'low' };
|
|
233
|
+
why.push("a scout's first attempt starts on sonnet at low effort, not haiku");
|
|
234
|
+
}
|
|
235
|
+
if (effortRank(route.effort) > effortRank('high')) {
|
|
236
|
+
route.effort = 'high';
|
|
237
|
+
why.push('a first attempt runs at high effort at most');
|
|
238
|
+
}
|
|
239
|
+
} else if (modelRank(prev.model) >= 0 && (prev.status === 'failed' || (prev.important ?? 0) >= RETRY_IMPORTANT_THRESHOLD)) {
|
|
240
|
+
const floor = stepAbove(prev, usable);
|
|
241
|
+
if (compareRoutes(floor, route) > 0) {
|
|
242
|
+
route = floor;
|
|
243
|
+
const outcome = prev.status === 'failed' ? 'failed' : `drew ${prev.important} Important findings`;
|
|
244
|
+
why.push(`a retry goes above j${prev.id}'s ${prev.model}/${prev.effort}, which ${outcome}`);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (agent === 'reviewer' && target?.model) {
|
|
248
|
+
if (modelRank(route.model) < modelRank(target.model)) {
|
|
249
|
+
// The judged job's model, or the nearest one that is on: above it if there is one, else the top one.
|
|
250
|
+
route.model = usable.find((m) => modelRank(m) >= modelRank(target.model)) ?? usable.at(-1);
|
|
251
|
+
why.push(`a reviewer is at least as strong as j${target.id}'s ${target.model}`);
|
|
252
|
+
}
|
|
253
|
+
if (route.model !== 'haiku' && effortRank(route.effort) < effortRank('medium')) {
|
|
254
|
+
route.effort = 'medium';
|
|
255
|
+
why.push('a reviewer runs at medium effort at least');
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return { ...route, policy: why.length === 0 ? null : `${why.join('; ')} (the router said ${routed.model}/${routed.effort})` };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const jobRoute = (db, id) => (id === undefined || id === null ? null : (db.prepare('SELECT id, model, effort, status, important FROM jobs WHERE id = ?').get(id) ?? null));
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Chooses a job's model and effort: the local router is asked — every job, every retry, no exceptions — and
|
|
265
|
+
* `routePolicy` holds its answer to a few rules. A router that cannot answer refuses the job, with no default
|
|
266
|
+
* to fall back to. A retry tells the router what the previous attempt ran on and how it ended; the models it
|
|
267
|
+
* may pick are the ones that are on (`sumo models`). Then the policy: a worker's first attempt starts on
|
|
268
|
+
* opus, not fable, and no first attempt runs above high effort; a retry of a job that failed or drew enough
|
|
269
|
+
* Important findings runs at least one step above it — the next model up, or on the top one a higher effort —
|
|
270
|
+
* and never below what the router answered; a reviewer created with `--reviews` runs on at least the judged
|
|
271
|
+
* job's model, at medium effort or more; a scout's first attempt runs on sonnet at low effort, not haiku, while sonnet is
|
|
272
|
+
* on. What the policy changed follows the router's reason. `risky` is the router's word on whether the work touches
|
|
273
|
+
* security, credentials, money, migrations or concurrency — kept with the job, so such work is reviewed once it is done.
|
|
274
|
+
*/
|
|
275
|
+
export async function chooseRoute(db, { agent, project, task, title, retryOf, reviews }) {
|
|
276
|
+
const routed = await askRouter(db, { agent, project, task, title, retryOf });
|
|
277
|
+
if (!routed.ok) throw new UsageError(`the router failed: ${routed.error} — no job was created`);
|
|
278
|
+
const { model, effort, policy } = routePolicy({ agent, routed, retryOf: jobRoute(db, retryOf), reviews: jobRoute(db, reviews), usable: usableModels(db) });
|
|
279
|
+
return { model, effort, reason: `router: ${routed.reason}${policy ? `; policy: ${policy}` : ''}`, risky: routed.risky };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The chat's route for one turn on auto, by the same router: its answer or a refusal, nothing in between. */
|
|
283
|
+
export async function chooseChatRoute(db, { project, text }) {
|
|
284
|
+
const routed = await askFor(db, CHAT_ROUTER_SYSTEM, chatRouterPrompt(db, { project, text }));
|
|
285
|
+
if (!routed.ok) throw new UsageError(`the router failed: ${routed.error}`);
|
|
286
|
+
return { model: routed.model, effort: routed.effort, reason: routed.reason };
|
|
287
|
+
}
|
package/src/sandbox.mjs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { homedir, tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { paths } from './paths.mjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The OS sandbox around the model's shell: macOS Seatbelt, the way Codex and Claude Code wrap their commands. Reads and
|
|
9
|
+
* the network stay open — git over ssh reads ~/.ssh, a smoke test calls out, and the user chose to give the shell their
|
|
10
|
+
* environment — while writes are held to the project, its git directory, the temporary folders, Sumo's own home and
|
|
11
|
+
* the tool caches, and never reach git's hooks or config, which run later outside it. The user can close the network
|
|
12
|
+
* past this machine (`shell.network off`). The guard refuses the commands it knows; this stops the ones it does not,
|
|
13
|
+
* whatever they are spelled as.
|
|
14
|
+
* `sandbox-exec` execs into the shell in place, so the shell keeps its pid and its process group, and a stop still reaches it.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Only the one in /usr/bin: one found on the PATH could be anything. */
|
|
18
|
+
const SANDBOX_EXEC = '/usr/bin/sandbox-exec';
|
|
19
|
+
|
|
20
|
+
/** The caches under the home a build or an install writes into: each is writable when it exists. */
|
|
21
|
+
const TOOL_CACHES = ['.npm', 'Library/Caches', '.cache', 'go/pkg', '.cargo/registry', '.cargo/git', 'Library/pnpm', '.bun/install/cache', '.gradle/caches', '.m2/repository'];
|
|
22
|
+
|
|
23
|
+
/** What is printed for a write the sandbox refused — Codex looks for the same two — in any case: Node says `EPERM: operation not permitted`. */
|
|
24
|
+
const BLOCKED = /operation not permitted|read-only file system/i;
|
|
25
|
+
|
|
26
|
+
/** Why the model's shell cannot be sandboxed here, or null when it can. */
|
|
27
|
+
export function unsandboxable({ platform = process.platform, exec = SANDBOX_EXEC } = {}) {
|
|
28
|
+
if (platform !== 'darwin') return 'there is a sandbox for it only on macOS so far';
|
|
29
|
+
if (!existsSync(exec)) return `${exec} is missing`;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const real = (path) => {
|
|
34
|
+
try {
|
|
35
|
+
return realpathSync(path);
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Each root's git common directory, asked of git once: a root does not turn into a worktree of another repository halfway through. */
|
|
42
|
+
const commonDirs = new Map();
|
|
43
|
+
|
|
44
|
+
/** The git directory a root's history is written to, when it lies outside the root — a worktree's is in the main checkout. */
|
|
45
|
+
function gitCommonDir(root) {
|
|
46
|
+
if (!commonDirs.has(root)) {
|
|
47
|
+
let dir = null;
|
|
48
|
+
try {
|
|
49
|
+
const said = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 }).trim();
|
|
50
|
+
dir = said ? real(resolve(root, said)) : null;
|
|
51
|
+
} catch {
|
|
52
|
+
// Not in a repository, or no git: there is nothing outside the root to write history to.
|
|
53
|
+
}
|
|
54
|
+
commonDirs.set(root, dir && dir !== root && !dir.startsWith(`${root}/`) ? dir : null);
|
|
55
|
+
}
|
|
56
|
+
return commonDirs.get(root);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Each root's hooks directory when git's config moves it, asked of git once, like the common directory. */
|
|
60
|
+
const hooksPaths = new Map();
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Where git runs a root's hooks from when its config sets `core.hooksPath` — husky's `.husky/_` — by its real path where it
|
|
64
|
+
* is there, else as git would find it: a relative one from the top of the working tree, where git runs its hooks. Null when unset.
|
|
65
|
+
*/
|
|
66
|
+
function hooksPathOf(root) {
|
|
67
|
+
if (!hooksPaths.has(root)) {
|
|
68
|
+
let dir = null;
|
|
69
|
+
try {
|
|
70
|
+
const ask = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 }).trim();
|
|
71
|
+
const said = ask('config', '--type=path', '--get', 'core.hooksPath');
|
|
72
|
+
if (said) {
|
|
73
|
+
const path = resolve(ask('rev-parse', '--show-toplevel') || root, said);
|
|
74
|
+
dir = real(path) ?? path;
|
|
75
|
+
}
|
|
76
|
+
} catch {
|
|
77
|
+
// Not set, not in a repository, or no git: the hooks are in the git directory, kept already.
|
|
78
|
+
}
|
|
79
|
+
hooksPaths.set(root, dir);
|
|
80
|
+
}
|
|
81
|
+
return hooksPaths.get(root);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The per-user cache folder macOS gives every program — clang's module cache and swift's are in it — asked of getconf once a process; null where there is none. */
|
|
85
|
+
let userCacheDir;
|
|
86
|
+
function darwinUserCache() {
|
|
87
|
+
if (userCacheDir === undefined) {
|
|
88
|
+
try {
|
|
89
|
+
userCacheDir = execFileSync('/usr/bin/getconf', ['DARWIN_USER_CACHE_DIR'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 }).trim() || null;
|
|
90
|
+
} catch {
|
|
91
|
+
userCacheDir = null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return userCacheDir;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The places a sandboxed command may write, by their real paths — the sandbox sees through a link — each once: every
|
|
99
|
+
* root and the git directory it commits to, the temporary folders, Sumo's home (the shell runs `sumo job note` and
|
|
100
|
+
* `sumo job finish`, which write there), the per-user cache macOS gives compilers, and the tool caches that exist. A
|
|
101
|
+
* place that does not exist is left out.
|
|
102
|
+
*/
|
|
103
|
+
export function writablePlaces(roots, { home = homedir(), tmp = tmpdir(), sumo = paths().home, userCache = darwinUserCache() } = {}) {
|
|
104
|
+
const places = [];
|
|
105
|
+
for (const root of roots.map(real).filter(Boolean)) places.push(root, gitCommonDir(root));
|
|
106
|
+
places.push(real(tmp), real('/private/tmp'), real(sumo), userCache && real(userCache), ...TOOL_CACHES.map((cache) => real(join(home, cache))));
|
|
107
|
+
return [...new Set(places.filter(Boolean))];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const isDirectory = (path) => {
|
|
111
|
+
try {
|
|
112
|
+
return statSync(path).isDirectory();
|
|
113
|
+
} catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* What stays read-only inside the places a command may write, by real paths: git's hooks and its config, which run or
|
|
120
|
+
* are read later outside the sandbox — a hook on the user's next commit — in each root's git directory and in the
|
|
121
|
+
* common one a worktree commits into, outside it; a root's `.git` that is a file, which says where its git
|
|
122
|
+
* directory is; and the hooks directory git's config names instead, where it does — husky's `.husky/_` is in the project.
|
|
123
|
+
* Only for a repository that is there when the command starts: `git init` makes its own.
|
|
124
|
+
*/
|
|
125
|
+
export function readOnlyPlaces(roots) {
|
|
126
|
+
const places = [];
|
|
127
|
+
for (const root of roots.map(real).filter(Boolean)) {
|
|
128
|
+
const dotGit = join(root, '.git');
|
|
129
|
+
const gitDir = real(dotGit);
|
|
130
|
+
if (gitDir && isDirectory(gitDir)) places.push(join(gitDir, 'hooks'), join(gitDir, 'config'));
|
|
131
|
+
else if (gitDir) places.push(gitDir);
|
|
132
|
+
const common = gitCommonDir(root);
|
|
133
|
+
if (common) places.push(join(common, 'hooks'), join(common, 'config'));
|
|
134
|
+
const hooks = hooksPathOf(root);
|
|
135
|
+
if (hooks) places.push(hooks);
|
|
136
|
+
}
|
|
137
|
+
return [...new Set(places)];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Every directory above a path, up to and without the root of the disk. */
|
|
141
|
+
function ancestors(path) {
|
|
142
|
+
const above = [];
|
|
143
|
+
for (let up = dirname(path); up !== dirname(up); up = dirname(up)) above.push(up);
|
|
144
|
+
return above;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* What a command runs under: sandbox-exec with a profile that allows everything but writing, then writing to each
|
|
149
|
+
* place — given as a parameter, so no path is ever spelled inside the profile — but never to what is kept read-only in
|
|
150
|
+
* them, carved out with require-not as Codex does; and to the devices every shell writes to. No directory above a path
|
|
151
|
+
* kept read-only can be moved or removed: renamed aside, what is under it would be out of the carve-out, and could be
|
|
152
|
+
* written and moved back. With the network off, nothing past this machine is reached; loopback — a dev server, a
|
|
153
|
+
* test's own — and local sockets stay open. The shell and its command follow it.
|
|
154
|
+
*/
|
|
155
|
+
export function sandboxWrap(writable, { readOnly = [], network = true } = {}) {
|
|
156
|
+
const places = writable.map((_, i) => `(subpath (param "W${i}"))`).join(' ');
|
|
157
|
+
const kept = readOnly.map((_, i) => `(require-not (literal (param "R${i}"))) (require-not (subpath (param "R${i}")))`).join(' ');
|
|
158
|
+
const above = [...new Set(readOnly.flatMap(ancestors))];
|
|
159
|
+
const rules = [
|
|
160
|
+
'(version 1)',
|
|
161
|
+
'(allow default)',
|
|
162
|
+
'(deny file-write*)',
|
|
163
|
+
`(allow file-write* ${readOnly.length === 0 ? places : `(require-all (require-any ${places}) ${kept})`} (literal "/dev/null") (regex #"^/dev/(tty|fd/|zero|dtracehelper)"))`,
|
|
164
|
+
];
|
|
165
|
+
if (!network) rules.push('(deny network-outbound (remote ip))', '(allow network-outbound (remote ip "localhost:*"))');
|
|
166
|
+
// Last, so no allowance after it opens the unlink a rename is made of.
|
|
167
|
+
if (above.length > 0) rules.push(`(deny file-write-unlink (require-all (vnode-type DIRECTORY) (require-any ${above.map((_, i) => `(literal (param "A${i}"))`).join(' ')})))`);
|
|
168
|
+
const params = [...writable.map((place, i) => `-DW${i}=${place}`), ...readOnly.map((place, i) => `-DR${i}=${place}`), ...above.map((place, i) => `-DA${i}=${place}`)];
|
|
169
|
+
return [SANDBOX_EXEC, '-p', rules.join('\n'), ...params, '--'];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Whether what a failed command printed says a write was refused. */
|
|
173
|
+
export const blockedWrite = (output) => BLOCKED.test(output);
|
package/src/scan.mjs
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Reads what a repository says about itself — deterministically, with no model.
|
|
7
|
+
* Each fact has a stable key so a re-scan replaces exactly the fact it updates.
|
|
8
|
+
*
|
|
9
|
+
* Only pointers are taken, never content: what a repo already records stays in
|
|
10
|
+
* the repo, and the agent is told where to read it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const ABOUT_MAX = 200;
|
|
14
|
+
|
|
15
|
+
/** More than any README, Makefile or package.json a scan takes a pointer from. */
|
|
16
|
+
const READ_MAX_BYTES = 1024 * 1024;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A file of the repository's own, as text — or null. A link that leads out of the repository (a README that is
|
|
20
|
+
* really ~/.netrc) is not the repository's to say, and what is not a plain file of sane size (a FIFO, /dev/zero)
|
|
21
|
+
* would hang the scan or fill memory, while the database waits on it.
|
|
22
|
+
*/
|
|
23
|
+
const read = (root, name) => {
|
|
24
|
+
try {
|
|
25
|
+
const real = realpathSync(join(root, name));
|
|
26
|
+
const home = realpathSync(root);
|
|
27
|
+
if (!real.startsWith(`${home}/`)) return null;
|
|
28
|
+
const stat = statSync(real);
|
|
29
|
+
if (!stat.isFile() || stat.size > READ_MAX_BYTES) return null;
|
|
30
|
+
return readFileSync(real, 'utf8');
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const readJson = (root, name) => {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(read(root, name));
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export function gitRemote(root) {
|
|
45
|
+
try {
|
|
46
|
+
return execFileSync('git', ['-C', root, 'remote', 'get-url', 'origin'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function nodePackageManager(root) {
|
|
53
|
+
if (existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb'))) return 'bun';
|
|
54
|
+
if (existsSync(join(root, 'pnpm-lock.yaml'))) return 'pnpm';
|
|
55
|
+
if (existsSync(join(root, 'yarn.lock'))) return 'yarn';
|
|
56
|
+
return 'npm';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function stack(root, pkg) {
|
|
60
|
+
const parts = [];
|
|
61
|
+
if (pkg) {
|
|
62
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
63
|
+
parts.push(existsSync(join(root, 'tsconfig.json')) || 'typescript' in deps ? 'TypeScript' : 'JavaScript');
|
|
64
|
+
for (const [dep, label] of [['next', 'Next.js'], ['react', 'React'], ['vue', 'Vue'], ['svelte', 'Svelte'], ['express', 'Express']]) {
|
|
65
|
+
if (dep in deps) {
|
|
66
|
+
parts.push(label);
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
parts.push(nodePackageManager(root));
|
|
71
|
+
}
|
|
72
|
+
if (existsSync(join(root, 'pyproject.toml')) || existsSync(join(root, 'requirements.txt'))) {
|
|
73
|
+
parts.push('Python');
|
|
74
|
+
if (existsSync(join(root, 'uv.lock'))) parts.push('uv');
|
|
75
|
+
else if (existsSync(join(root, 'poetry.lock'))) parts.push('poetry');
|
|
76
|
+
}
|
|
77
|
+
if (existsSync(join(root, 'go.mod'))) parts.push('Go');
|
|
78
|
+
if (existsSync(join(root, 'Cargo.toml'))) parts.push('Rust');
|
|
79
|
+
if (existsSync(join(root, 'Gemfile'))) parts.push('Ruby');
|
|
80
|
+
if (existsSync(join(root, 'pom.xml')) || existsSync(join(root, 'build.gradle')) || existsSync(join(root, 'build.gradle.kts'))) parts.push('JVM');
|
|
81
|
+
if (existsSync(join(root, 'Package.swift'))) parts.push('Swift');
|
|
82
|
+
return parts.length > 0 ? `stack: ${parts.join(', ')}` : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A make target's own lines — its rule and the recipe under it. */
|
|
86
|
+
function recipe(makefile, target) {
|
|
87
|
+
const lines = makefile.split('\n');
|
|
88
|
+
const at = lines.findIndex((l) => l.startsWith(`${target}:`));
|
|
89
|
+
// make reads past a blank or comment line inside a recipe; only the next line of anything else ends it.
|
|
90
|
+
const end = lines.findIndex((l, i) => i > at && !l.startsWith('\t') && l.trim() !== '' && !l.trimStart().startsWith('#'));
|
|
91
|
+
const own = lines.slice(at, end === -1 ? lines.length : end);
|
|
92
|
+
while (own.length > 1 && !own.at(-1).startsWith('\t')) own.pop();
|
|
93
|
+
return own.join('\n');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The commands a project declares about itself, as data: the card prints them
|
|
98
|
+
* and a job's verification runs them, so the two can never disagree. Where the
|
|
99
|
+
* project itself says what a command runs — a script, a recipe — that is its
|
|
100
|
+
* `definition`, so a job that rewrites it can be told apart from one that does not.
|
|
101
|
+
*/
|
|
102
|
+
export function projectCommands(root, pkg = readJson(root, 'package.json')) {
|
|
103
|
+
const found = [];
|
|
104
|
+
if (pkg?.scripts) {
|
|
105
|
+
const pm = nodePackageManager(root);
|
|
106
|
+
// `bun test` is bun's own runner, not the package's test script, so bun always goes through `run`.
|
|
107
|
+
const run = (script) => (script === 'test' && pm !== 'bun' ? `${pm} test` : `${pm} run ${script}`);
|
|
108
|
+
for (const script of ['check', 'test', 'lint', 'typecheck', 'build', 'dev']) {
|
|
109
|
+
if (script in pkg.scripts) found.push({ name: script, command: run(script), definition: String(pkg.scripts[script]) });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const makefile = read(root, 'Makefile');
|
|
113
|
+
if (makefile) {
|
|
114
|
+
for (const target of ['check', 'test', 'lint', 'build']) {
|
|
115
|
+
if (new RegExp(`^${target}:`, 'm').test(makefile) && !found.some((f) => f.name === target)) {
|
|
116
|
+
found.push({ name: target, command: `make ${target}`, definition: recipe(makefile, target) });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (found.length === 0) {
|
|
121
|
+
if (existsSync(join(root, 'go.mod'))) found.push({ name: 'test', command: 'go test ./...' });
|
|
122
|
+
if (existsSync(join(root, 'Cargo.toml'))) found.push({ name: 'test', command: 'cargo test' });
|
|
123
|
+
if (/\bpytest\b/.test(read(root, 'pyproject.toml') ?? '')) found.push({ name: 'test', command: 'pytest' });
|
|
124
|
+
}
|
|
125
|
+
return found;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* What proves a change in this project. `check` is the project's own gate — the
|
|
130
|
+
* one command its CI runs — so when it exists it is the whole answer; running
|
|
131
|
+
* its parts beside it would only pay for the suite twice.
|
|
132
|
+
*/
|
|
133
|
+
export function verifyCommands(root) {
|
|
134
|
+
const all = projectCommands(root);
|
|
135
|
+
const gate = all.filter((c) => c.name === 'check');
|
|
136
|
+
return gate.length > 0 ? gate : all.filter((c) => ['test', 'lint', 'typecheck'].includes(c.name));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function commands(root, pkg) {
|
|
140
|
+
const found = projectCommands(root, pkg).map((c) => `${c.name} \`${c.command}\``);
|
|
141
|
+
return found.length > 0 ? `commands: ${found.join(' · ')}` : null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** What this project has not set up, so nobody mistakes "nothing failed" for "it was checked". Said once, on the card. */
|
|
145
|
+
function gaps(root, pkg) {
|
|
146
|
+
const names = new Set(projectCommands(root, pkg).map((c) => c.name));
|
|
147
|
+
const missing = [];
|
|
148
|
+
if (!names.has('test') && !names.has('check')) missing.push('a test command');
|
|
149
|
+
if (!names.has('lint') && !names.has('check')) missing.push('a lint command');
|
|
150
|
+
if (ci(root) === null) missing.push('a CI workflow');
|
|
151
|
+
if (instructions(root) === null) missing.push('AGENTS.md');
|
|
152
|
+
return missing.length > 0 ? `not set up here: ${missing.join(', ')}` : null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The first real paragraph of the README: not a heading, badge, image, or HTML. */
|
|
156
|
+
function about(root) {
|
|
157
|
+
const name = ['README.md', 'readme.md', 'README', 'README.rst'].find((f) => existsSync(join(root, f)));
|
|
158
|
+
const text = name ? read(root, name) : null;
|
|
159
|
+
if (!text) return null;
|
|
160
|
+
const paragraph = text
|
|
161
|
+
.split(/\n\s*\n/)
|
|
162
|
+
.map((p) => p.replace(/\s+/g, ' ').trim())
|
|
163
|
+
.find((p) => p.length > 20 && !/^(#|!\[|\[!\[|<|```|=+$|-+$|>)/.test(p));
|
|
164
|
+
if (!paragraph) return null;
|
|
165
|
+
const plain = paragraph.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').replace(/[*_`]/g, '');
|
|
166
|
+
return `about: ${plain.length > ABOUT_MAX ? `${plain.slice(0, ABOUT_MAX - 1)}…` : plain}`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function instructions(root) {
|
|
170
|
+
const files = ['AGENTS.md', 'CLAUDE.md', join('.claude', 'CLAUDE.md')].filter((f) => existsSync(join(root, f)));
|
|
171
|
+
// File names only: the card's first line already carries the project path, and a full path here gets clipped into uselessness.
|
|
172
|
+
return files.length > 0 ? `has its own instructions — read ${files.join(' and ')} in the project root before editing` : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function workspaces(root, pkg) {
|
|
176
|
+
const globs = Array.isArray(pkg?.workspaces) ? pkg.workspaces : pkg?.workspaces?.packages;
|
|
177
|
+
if (globs?.length) return `monorepo: workspaces ${globs.join(', ')}`;
|
|
178
|
+
if (existsSync(join(root, 'pnpm-workspace.yaml'))) return 'monorepo: pnpm workspaces (see pnpm-workspace.yaml)';
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function ci(root) {
|
|
183
|
+
try {
|
|
184
|
+
const count = readdirSync(join(root, '.github', 'workflows')).filter((f) => /\.ya?ml$/.test(f)).length;
|
|
185
|
+
return count > 0 ? `CI: GitHub Actions, ${count} workflow${count === 1 ? '' : 's'}` : null;
|
|
186
|
+
} catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Facts in the order the project card should show them. A key with nothing to say is simply absent. */
|
|
192
|
+
export function scan(root) {
|
|
193
|
+
const pkg = readJson(root, 'package.json');
|
|
194
|
+
const facts = [
|
|
195
|
+
['instructions', instructions(root)],
|
|
196
|
+
['stack', stack(root, pkg)],
|
|
197
|
+
['commands', commands(root, pkg)],
|
|
198
|
+
['workspaces', workspaces(root, pkg)],
|
|
199
|
+
['ci', ci(root)],
|
|
200
|
+
['gaps', gaps(root, pkg)],
|
|
201
|
+
['about', about(root)],
|
|
202
|
+
];
|
|
203
|
+
return facts.filter(([, body]) => body !== null).map(([key, body]) => ({ key, body }));
|
|
204
|
+
}
|