@richjava/req0 0.1.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 +117 -0
- package/cockpit/android-chrome-192x192.png +0 -0
- package/cockpit/android-chrome-512x512.png +0 -0
- package/cockpit/app.js +1710 -0
- package/cockpit/apple-touch-icon.png +0 -0
- package/cockpit/favicon-16x16.png +0 -0
- package/cockpit/favicon-32x32.png +0 -0
- package/cockpit/favicon.ico +0 -0
- package/cockpit/index.html +180 -0
- package/cockpit/markdown-editor.js +93 -0
- package/cockpit/req0-logo-horiz.png +0 -0
- package/cockpit/req0-logo-stacked.png +0 -0
- package/cockpit/site.webmanifest +19 -0
- package/cockpit/styles.css +1710 -0
- package/cockpit/tokens.css +118 -0
- package/dist/adapter.d.ts +5 -0
- package/dist/adapter.js +16 -0
- package/dist/browser.d.ts +33 -0
- package/dist/browser.js +524 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +265 -0
- package/dist/compile.d.ts +5 -0
- package/dist/compile.js +456 -0
- package/dist/diff.d.ts +15 -0
- package/dist/diff.js +114 -0
- package/dist/fix-from-proof.d.ts +13 -0
- package/dist/fix-from-proof.js +61 -0
- package/dist/gates.d.ts +7 -0
- package/dist/gates.js +7 -0
- package/dist/implement-brief.d.ts +9 -0
- package/dist/implement-brief.js +142 -0
- package/dist/implement.d.ts +70 -0
- package/dist/implement.js +615 -0
- package/dist/improve-log.d.ts +11 -0
- package/dist/improve-log.js +38 -0
- package/dist/improve-review.d.ts +45 -0
- package/dist/improve-review.js +182 -0
- package/dist/improve.d.ts +16 -0
- package/dist/improve.js +127 -0
- package/dist/jev-pack.d.ts +2 -0
- package/dist/jev-pack.js +114 -0
- package/dist/jev.d.ts +23 -0
- package/dist/jev.js +142 -0
- package/dist/pack.d.ts +101 -0
- package/dist/pack.js +609 -0
- package/dist/personas.d.ts +13 -0
- package/dist/personas.js +88 -0
- package/dist/proof-report.d.ts +8 -0
- package/dist/proof-report.js +82 -0
- package/dist/proof.d.ts +45 -0
- package/dist/proof.js +394 -0
- package/dist/qa-plan.d.ts +6 -0
- package/dist/qa-plan.js +58 -0
- package/dist/ready.d.ts +29 -0
- package/dist/ready.js +317 -0
- package/dist/runtime.d.ts +25 -0
- package/dist/runtime.js +125 -0
- package/dist/server.d.ts +15 -0
- package/dist/server.js +588 -0
- package/dist/stack.d.ts +35 -0
- package/dist/stack.js +220 -0
- package/dist/stages.d.ts +15 -0
- package/dist/stages.js +345 -0
- package/dist/template.d.ts +5 -0
- package/dist/template.js +55 -0
- package/dist/types.d.ts +282 -0
- package/dist/types.js +12 -0
- package/docs/requirement-template.md +341 -0
- package/package.json +81 -0
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { createWriteStream, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { adapterDisplayName } from "./adapter.js";
|
|
5
|
+
export const IMPLEMENT_AGENT_LOG = "implement-agent.log";
|
|
6
|
+
/** Hard cap on `ampx sandbox --once` starts in one Implement / Fix from proof run. */
|
|
7
|
+
export const IMPLEMENT_SANDBOX_MAX = 3;
|
|
8
|
+
/** Wall-clock cap so a debug loop cannot run indefinitely. */
|
|
9
|
+
export const IMPLEMENT_MAX_MS = 20 * 60 * 1000;
|
|
10
|
+
export const IMPLEMENT_STOPPED = "Owner stopped Implement.";
|
|
11
|
+
export const IMPLEMENT_SANDBOX_CAP = `Stopped after ${IMPLEMENT_SANDBOX_MAX} sandbox deploys. Reimplement or Ignore, then Prove.`;
|
|
12
|
+
export const IMPLEMENT_TIME_CAP = `Stopped after ${IMPLEMENT_MAX_MS / 60_000} minutes. Reimplement or Ignore, then Prove.`;
|
|
13
|
+
export class ImplementLockedError extends Error {
|
|
14
|
+
code = "ready_gate";
|
|
15
|
+
constructor(message = "Implement is locked until Ready is Ready. Check this spec with Jev first.") {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ImplementLockedError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export class ImplementDisabledError extends Error {
|
|
21
|
+
code = "implement_off";
|
|
22
|
+
constructor(message = "Implement is off in req0.json. Build this repo another way, then Prove with fixtures/runtime.yaml.") {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "ImplementDisabledError";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function adapterInstructions(adapter, briefPath) {
|
|
28
|
+
if (adapter === "cursor") {
|
|
29
|
+
return `Cursor adapter: agent starts in the product repo with ${briefPath} in the prompt. Do not invent spec IDs.`;
|
|
30
|
+
}
|
|
31
|
+
if (adapter === "copilot") {
|
|
32
|
+
return `Copilot adapter: GitHub Copilot CLI starts in the product repo with ${briefPath} in the prompt. Do not invent spec IDs.`;
|
|
33
|
+
}
|
|
34
|
+
return `Manual adapter: open ${briefPath} in any coding agent and implement from that brief. This path does not start an agent.`;
|
|
35
|
+
}
|
|
36
|
+
export function implementPrompt(briefPath, stackId) {
|
|
37
|
+
const amplify = stackId === "amplify-gen2"
|
|
38
|
+
? " If the stack is amplify-gen2: ampx does not read .env. If there is no AWS_PROFILE, inherited AWS_ACCESS_KEY_ID, or ~/.aws, stop and tell the owner to run npx ampx configure profile. Do not ask for keys. After scaffolding amplify/, run npx ampx sandbox --once (add --profile when using a profile) and wait until amplify_outputs.json has a real user_pool_id, not REPLACE_VIA_SANDBOX. Restart the app, then seed personas. npm install is not a sandbox deploy."
|
|
39
|
+
: "";
|
|
40
|
+
return [
|
|
41
|
+
"Implement this requirement from the brief.",
|
|
42
|
+
`Read ${briefPath} and derived/spec.json.`,
|
|
43
|
+
"Do not invent spec IDs. Implement only the named BR- and UC- IDs.",
|
|
44
|
+
"If this product repo has no customer app, use the stack recorded in req0.json.",
|
|
45
|
+
"Seed the app from existing fixtures/personas.yaml. Do not invent personas.",
|
|
46
|
+
"Finish fixtures/runtime.yaml so baseUrl, startCommand, and resetCommand match the app. Keep login selectors unless you change /login to match.",
|
|
47
|
+
"Write product .env.example with variable names only. No real keys.",
|
|
48
|
+
"Write product README.md using the requirement title and pack fixture paths. Do not invent a product name.",
|
|
49
|
+
"Do not treat this launch as proof the app boots.",
|
|
50
|
+
`At most ${IMPLEMENT_SANDBOX_MAX} npx ampx sandbox --once deploys in this run. After the third, stop and tell the owner what is still failing. Do not start a fourth.`,
|
|
51
|
+
]
|
|
52
|
+
.join(" ")
|
|
53
|
+
.concat(amplify);
|
|
54
|
+
}
|
|
55
|
+
export function fixFromProofPrompt(briefPath, reportPath, implementBriefPath) {
|
|
56
|
+
return [
|
|
57
|
+
"Fix the existing product from the last Prove.",
|
|
58
|
+
`Read ${briefPath}, then ${reportPath}, then ${implementBriefPath}.`,
|
|
59
|
+
"Close only the Failed and Needs review cases. Do not invent spec IDs.",
|
|
60
|
+
"Do not edit requirement.md. Do not scaffold a second application.",
|
|
61
|
+
"Boot or Sign-in observations may be fixtures or runtime.yaml, not a missing control.",
|
|
62
|
+
"Do not treat this launch as proof the app boots.",
|
|
63
|
+
`At most ${IMPLEMENT_SANDBOX_MAX} npx ampx sandbox --once deploys in this run. After the third, stop and tell the owner what is still failing. Do not start a fourth.`,
|
|
64
|
+
].join(" ");
|
|
65
|
+
}
|
|
66
|
+
export function improvePrompt(briefPath) {
|
|
67
|
+
return [
|
|
68
|
+
"Improve this requirement pack from the brief.",
|
|
69
|
+
`Read ${briefPath} and requirement.md.`,
|
|
70
|
+
"Patch requirement.md only. If the brief asks for a persona, you may also edit fixtures/personas.yaml.",
|
|
71
|
+
"Outcome is what a person sees. Do not paste matrix allow/deny cells into Outcome. Look for is deny; Choose is allow.",
|
|
72
|
+
"Do not invent spec IDs. Do not implement the product app.",
|
|
73
|
+
"Stop after the patch so the owner can review the diff, then Check with Jev.",
|
|
74
|
+
].join(" ");
|
|
75
|
+
}
|
|
76
|
+
export function resolveCursorBin() {
|
|
77
|
+
const override = process.env.CURSOR_BIN?.trim();
|
|
78
|
+
if (override && existsSync(override))
|
|
79
|
+
return override;
|
|
80
|
+
const exe = process.platform === "win32" ? "cursor.cmd" : "cursor";
|
|
81
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
82
|
+
if (!dir)
|
|
83
|
+
continue;
|
|
84
|
+
const candidate = path.join(dir, exe);
|
|
85
|
+
if (existsSync(candidate))
|
|
86
|
+
return candidate;
|
|
87
|
+
}
|
|
88
|
+
const mac = "/Applications/Cursor.app/Contents/Resources/app/bin/cursor";
|
|
89
|
+
if (process.platform === "darwin" && existsSync(mac))
|
|
90
|
+
return mac;
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
export function resolveCopilotBin() {
|
|
94
|
+
const override = process.env.COPILOT_BIN?.trim();
|
|
95
|
+
if (override && existsSync(override))
|
|
96
|
+
return override;
|
|
97
|
+
const exe = process.platform === "win32" ? "copilot.cmd" : "copilot";
|
|
98
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
99
|
+
if (!dir)
|
|
100
|
+
continue;
|
|
101
|
+
const candidate = path.join(dir, exe);
|
|
102
|
+
if (existsSync(candidate))
|
|
103
|
+
return candidate;
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
export function cursorAgentStatus(bin) {
|
|
108
|
+
const result = spawnSync(bin, ["agent", "status"], { encoding: "utf8", timeout: 4_000 });
|
|
109
|
+
return `${result.stdout ?? ""}${result.stderr ?? ""}`;
|
|
110
|
+
}
|
|
111
|
+
export function assertImplementAllowed(result) {
|
|
112
|
+
if (result.health.ready.state !== "ready") {
|
|
113
|
+
throw new ImplementLockedError();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
export function implementLogPath(briefPath, logFile = IMPLEMENT_AGENT_LOG) {
|
|
117
|
+
return path.join(path.dirname(briefPath), logFile);
|
|
118
|
+
}
|
|
119
|
+
export function launchAdapter(adapter, repoRoot, briefPath, deps = {}) {
|
|
120
|
+
if (adapter === "manual") {
|
|
121
|
+
return Promise.resolve({
|
|
122
|
+
ok: true,
|
|
123
|
+
message: deps.successMessage ??
|
|
124
|
+
"Manual adapter does not start an agent. Open the brief, or run implement without --adapter=manual to launch Cursor. Build Succeeded is not proof the app boots.",
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
if (!repoRoot) {
|
|
128
|
+
return Promise.resolve({
|
|
129
|
+
ok: false,
|
|
130
|
+
message: `${adapterDisplayName(adapter)} cannot be launched without a product repo root. Use --adapter=manual.`,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
if (adapter === "copilot") {
|
|
134
|
+
return spawnCopilotAgent(repoRoot, briefPath, deps);
|
|
135
|
+
}
|
|
136
|
+
const bin = (deps.resolveBin ?? resolveCursorBin)();
|
|
137
|
+
if (!bin) {
|
|
138
|
+
return Promise.resolve({
|
|
139
|
+
ok: false,
|
|
140
|
+
message: "Cursor was not found. Install Cursor, or set CURSOR_BIN, or retry with --adapter=manual.",
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (!process.env.CURSOR_API_KEY && deps.agentStatus) {
|
|
144
|
+
const status = deps.agentStatus(bin);
|
|
145
|
+
if (/not logged in/i.test(status)) {
|
|
146
|
+
return Promise.resolve({
|
|
147
|
+
ok: false,
|
|
148
|
+
message: `Cursor agent is not logged in, so nothing was generated. In a terminal run: "${bin}" agent login then retry Implement.`,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const run = deps.spawn ?? spawn;
|
|
153
|
+
return spawnCursorAgent(run, bin, repoRoot, briefPath, deps);
|
|
154
|
+
}
|
|
155
|
+
async function spawnCursorAgent(run, bin, repoRoot, briefPath, deps) {
|
|
156
|
+
const platform = deps.platform ?? process.platform;
|
|
157
|
+
const ide = deps.openIde === false
|
|
158
|
+
? Promise.resolve({ ok: true, message: "skipped" })
|
|
159
|
+
: platform === "darwin"
|
|
160
|
+
? launchDetached(run, "open", ["-a", "Cursor", repoRoot], repoRoot)
|
|
161
|
+
: launchDetached(run, bin, [repoRoot], repoRoot);
|
|
162
|
+
const logPath = implementLogPath(briefPath, deps.logFile);
|
|
163
|
+
const agent = launchLogged(run, bin, agentArgs(repoRoot, briefPath, deps), repoRoot, logPath, deps);
|
|
164
|
+
const [, agentLaunch] = await Promise.all([ide, agent]);
|
|
165
|
+
if (!agentLaunch.ok) {
|
|
166
|
+
return { ok: false, message: agentLaunch.message, logPath, stop: agentLaunch.stop };
|
|
167
|
+
}
|
|
168
|
+
const settled = await waitForAgent(agentLaunch.child, deps.settleMs ?? 1500, logPath, bin, "Cursor");
|
|
169
|
+
if (!settled.ok) {
|
|
170
|
+
return {
|
|
171
|
+
...settled,
|
|
172
|
+
logPath,
|
|
173
|
+
child: agentLaunch.child,
|
|
174
|
+
finished: agentLaunch.finished,
|
|
175
|
+
stop: agentLaunch.stop,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
ok: true,
|
|
180
|
+
message: deps.successMessage ??
|
|
181
|
+
"Started a Cursor agent with the implement brief. Activity shows tools and messages as they happen. Build stays running until the agent exits.",
|
|
182
|
+
child: agentLaunch.child,
|
|
183
|
+
logPath,
|
|
184
|
+
finished: agentLaunch.finished,
|
|
185
|
+
stop: agentLaunch.stop,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
async function spawnCopilotAgent(repoRoot, briefPath, deps) {
|
|
189
|
+
const bin = (deps.resolveCopilotBin ?? resolveCopilotBin)();
|
|
190
|
+
if (!bin) {
|
|
191
|
+
return {
|
|
192
|
+
ok: false,
|
|
193
|
+
message: "GitHub Copilot CLI was not found. Install it, set COPILOT_BIN, or retry with --adapter=cursor or --adapter=manual.",
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const run = deps.spawn ?? spawn;
|
|
197
|
+
const logPath = implementLogPath(briefPath, deps.logFile);
|
|
198
|
+
const agentLaunch = await launchLogged(run, bin, copilotArgs(briefPath, deps), repoRoot, logPath, { ...deps, heartbeatLabel: deps.heartbeatLabel ?? "Copilot agent still running.", cliName: "Copilot" });
|
|
199
|
+
if (!agentLaunch.ok) {
|
|
200
|
+
return { ok: false, message: agentLaunch.message, logPath, stop: agentLaunch.stop };
|
|
201
|
+
}
|
|
202
|
+
const settled = await waitForAgent(agentLaunch.child, deps.settleMs ?? 1500, logPath, bin, "Copilot");
|
|
203
|
+
if (!settled.ok) {
|
|
204
|
+
return {
|
|
205
|
+
...settled,
|
|
206
|
+
logPath,
|
|
207
|
+
child: agentLaunch.child,
|
|
208
|
+
finished: agentLaunch.finished,
|
|
209
|
+
stop: agentLaunch.stop,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
ok: true,
|
|
214
|
+
message: deps.successMessage ??
|
|
215
|
+
"Started GitHub Copilot CLI with the implement brief. Activity shows tools and messages as they happen. Build stays running until the agent exits.",
|
|
216
|
+
child: agentLaunch.child,
|
|
217
|
+
logPath,
|
|
218
|
+
finished: agentLaunch.finished,
|
|
219
|
+
stop: agentLaunch.stop,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function agentArgs(repoRoot, briefPath, deps) {
|
|
223
|
+
const prompt = deps.prompt ?? implementPrompt(briefPath);
|
|
224
|
+
const args = [
|
|
225
|
+
"agent",
|
|
226
|
+
"--workspace",
|
|
227
|
+
repoRoot,
|
|
228
|
+
"--trust",
|
|
229
|
+
"--force",
|
|
230
|
+
"--print",
|
|
231
|
+
"--output-format",
|
|
232
|
+
"stream-json",
|
|
233
|
+
prompt,
|
|
234
|
+
];
|
|
235
|
+
const key = process.env.CURSOR_API_KEY?.trim();
|
|
236
|
+
if (key)
|
|
237
|
+
args.splice(1, 0, "--api-key", key);
|
|
238
|
+
return args;
|
|
239
|
+
}
|
|
240
|
+
function copilotArgs(briefPath, deps) {
|
|
241
|
+
const prompt = deps.prompt ?? implementPrompt(briefPath);
|
|
242
|
+
return ["-p", prompt, "--no-ask-user", "--allow-all", "--output-format", "json"];
|
|
243
|
+
}
|
|
244
|
+
function launchDetached(run, bin, args, cwd) {
|
|
245
|
+
return new Promise((resolve) => {
|
|
246
|
+
let child;
|
|
247
|
+
try {
|
|
248
|
+
child = run(bin, args, { cwd, detached: true, stdio: "ignore", env: process.env });
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
resolve({
|
|
252
|
+
ok: false,
|
|
253
|
+
message: err instanceof Error ? err.message : "Cursor launch failed.",
|
|
254
|
+
});
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
child.once("error", (err) => {
|
|
258
|
+
resolve({
|
|
259
|
+
ok: false,
|
|
260
|
+
message: err.message.includes("ENOENT")
|
|
261
|
+
? "Cursor CLI was not found. Install it, set CURSOR_BIN, or retry with --adapter=manual."
|
|
262
|
+
: err.message,
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
child.once("spawn", () => {
|
|
266
|
+
child.unref();
|
|
267
|
+
resolve({ ok: true, message: "started", child });
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
function launchLogged(run, bin, args, cwd, logPath, deps) {
|
|
272
|
+
return new Promise((resolve) => {
|
|
273
|
+
let child;
|
|
274
|
+
try {
|
|
275
|
+
mkdirSync(path.dirname(logPath), { recursive: true });
|
|
276
|
+
child = run(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"], env: process.env });
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
resolve({
|
|
280
|
+
ok: false,
|
|
281
|
+
message: err instanceof Error ? err.message : `${deps.cliName ?? "Cursor"} launch failed.`,
|
|
282
|
+
});
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const stop = {};
|
|
286
|
+
const finished = attachAgentLog(child, logPath, deps.onLogLine, {
|
|
287
|
+
stop,
|
|
288
|
+
sandboxMax: deps.sandboxMax ?? IMPLEMENT_SANDBOX_MAX,
|
|
289
|
+
maxMs: deps.maxMs ?? IMPLEMENT_MAX_MS,
|
|
290
|
+
heartbeatLabel: deps.heartbeatLabel ?? `${deps.cliName ?? "Cursor"} agent still running.`,
|
|
291
|
+
});
|
|
292
|
+
child.once("error", (err) => {
|
|
293
|
+
resolve({
|
|
294
|
+
ok: false,
|
|
295
|
+
message: err.message.includes("ENOENT")
|
|
296
|
+
? `${deps.cliName ?? "Cursor"} CLI was not found. Install it, or retry with --adapter=manual.`
|
|
297
|
+
: err.message,
|
|
298
|
+
finished,
|
|
299
|
+
stop,
|
|
300
|
+
});
|
|
301
|
+
});
|
|
302
|
+
child.once("spawn", () => {
|
|
303
|
+
resolve({ ok: true, message: "started", child, finished, stop });
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
export function attachAgentLog(child, logPath, onLogLine, control = {}) {
|
|
308
|
+
const stream = createWriteStream(logPath, { flags: "w" });
|
|
309
|
+
const stop = control.stop ?? {};
|
|
310
|
+
const sandboxMax = control.sandboxMax ?? IMPLEMENT_SANDBOX_MAX;
|
|
311
|
+
const maxMs = control.maxMs ?? IMPLEMENT_MAX_MS;
|
|
312
|
+
const heartbeatLabel = control.heartbeatLabel ?? "Agent still running.";
|
|
313
|
+
let lastEmit = Date.now();
|
|
314
|
+
let lastShown = "";
|
|
315
|
+
let sandboxStarts = 0;
|
|
316
|
+
const feed = makeLineFeeder((line) => {
|
|
317
|
+
if (isSandboxOnceStart(line)) {
|
|
318
|
+
sandboxStarts += 1;
|
|
319
|
+
if (sandboxStarts > sandboxMax) {
|
|
320
|
+
requestImplementStop(child, stop, IMPLEMENT_SANDBOX_CAP);
|
|
321
|
+
if (IMPLEMENT_SANDBOX_CAP !== lastShown) {
|
|
322
|
+
lastShown = IMPLEMENT_SANDBOX_CAP;
|
|
323
|
+
lastEmit = Date.now();
|
|
324
|
+
onLogLine?.(IMPLEMENT_SANDBOX_CAP);
|
|
325
|
+
}
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const text = summarizeAgentLine(redactSecrets(line));
|
|
330
|
+
if (!text || text === lastShown)
|
|
331
|
+
return;
|
|
332
|
+
lastShown = text;
|
|
333
|
+
lastEmit = Date.now();
|
|
334
|
+
onLogLine?.(text);
|
|
335
|
+
});
|
|
336
|
+
const heartbeat = onLogLine
|
|
337
|
+
? setInterval(() => {
|
|
338
|
+
if (Date.now() - lastEmit < 20_000)
|
|
339
|
+
return;
|
|
340
|
+
lastEmit = Date.now();
|
|
341
|
+
lastShown = heartbeatLabel;
|
|
342
|
+
onLogLine(lastShown);
|
|
343
|
+
}, 5_000)
|
|
344
|
+
: undefined;
|
|
345
|
+
heartbeat?.unref?.();
|
|
346
|
+
const deadline = maxMs > 0
|
|
347
|
+
? setTimeout(() => {
|
|
348
|
+
requestImplementStop(child, stop, IMPLEMENT_TIME_CAP);
|
|
349
|
+
if (IMPLEMENT_TIME_CAP !== lastShown) {
|
|
350
|
+
lastShown = IMPLEMENT_TIME_CAP;
|
|
351
|
+
lastEmit = Date.now();
|
|
352
|
+
onLogLine?.(IMPLEMENT_TIME_CAP);
|
|
353
|
+
}
|
|
354
|
+
}, maxMs)
|
|
355
|
+
: undefined;
|
|
356
|
+
deadline?.unref?.();
|
|
357
|
+
child.stdout?.on("data", (chunk) => {
|
|
358
|
+
stream.write(chunk);
|
|
359
|
+
feed(chunk);
|
|
360
|
+
});
|
|
361
|
+
child.stderr?.on("data", (chunk) => {
|
|
362
|
+
stream.write(chunk);
|
|
363
|
+
feed(chunk);
|
|
364
|
+
});
|
|
365
|
+
return new Promise((resolve) => {
|
|
366
|
+
child.once("close", (code) => {
|
|
367
|
+
if (heartbeat)
|
|
368
|
+
clearInterval(heartbeat);
|
|
369
|
+
if (deadline)
|
|
370
|
+
clearTimeout(deadline);
|
|
371
|
+
feed("\n");
|
|
372
|
+
stream.end();
|
|
373
|
+
resolve({ code });
|
|
374
|
+
});
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
export function requestImplementStop(child, stop, reason) {
|
|
378
|
+
if (stop.reason)
|
|
379
|
+
return;
|
|
380
|
+
stop.reason = reason;
|
|
381
|
+
killImplementTree(child);
|
|
382
|
+
}
|
|
383
|
+
export function killImplementTree(child) {
|
|
384
|
+
const pid = child?.pid;
|
|
385
|
+
try {
|
|
386
|
+
child?.kill("SIGTERM");
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
// already gone
|
|
390
|
+
}
|
|
391
|
+
if (typeof pid !== "number" || pid <= 0)
|
|
392
|
+
return;
|
|
393
|
+
try {
|
|
394
|
+
process.kill(pid, "SIGTERM");
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
// already gone
|
|
398
|
+
}
|
|
399
|
+
try {
|
|
400
|
+
spawnSync("pkill", ["-TERM", "-P", String(pid)], { timeout: 2_000 });
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
// no pkill, or no children
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
export function isSandboxOnceStart(line) {
|
|
407
|
+
const text = line.trim();
|
|
408
|
+
if (!text.includes("sandbox") || !text.includes("--once"))
|
|
409
|
+
return false;
|
|
410
|
+
if (!text.startsWith("{"))
|
|
411
|
+
return /ampx sandbox --once/.test(text);
|
|
412
|
+
try {
|
|
413
|
+
const event = JSON.parse(text);
|
|
414
|
+
if (event.type === "tool_call" && event.subtype !== "started")
|
|
415
|
+
return false;
|
|
416
|
+
if (event.type === "tool.execution_complete" || event.type === "tool_result")
|
|
417
|
+
return false;
|
|
418
|
+
return text.includes("ampx sandbox") && text.includes("--once");
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
export function summarizeAgentLine(line) {
|
|
425
|
+
const text = line.trim();
|
|
426
|
+
if (!text)
|
|
427
|
+
return null;
|
|
428
|
+
if (!text.startsWith("{"))
|
|
429
|
+
return text.slice(0, 280);
|
|
430
|
+
let event;
|
|
431
|
+
try {
|
|
432
|
+
event = JSON.parse(text);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
return text.slice(0, 280);
|
|
436
|
+
}
|
|
437
|
+
const copilot = summarizeCopilotLine(event);
|
|
438
|
+
if (copilot !== undefined)
|
|
439
|
+
return copilot;
|
|
440
|
+
if (event.type === "system" && event.subtype === "init") {
|
|
441
|
+
const model = typeof event.model === "string" && event.model.trim() ? event.model.trim() : "Cursor";
|
|
442
|
+
return `Cursor agent connected (${model}).`;
|
|
443
|
+
}
|
|
444
|
+
if (event.type === "user")
|
|
445
|
+
return null;
|
|
446
|
+
if (event.type === "assistant") {
|
|
447
|
+
const body = assistantText(event);
|
|
448
|
+
return body ? clip(`Agent: ${body}`, 280) : null;
|
|
449
|
+
}
|
|
450
|
+
if (event.type === "tool_call") {
|
|
451
|
+
if (event.subtype !== "started")
|
|
452
|
+
return null;
|
|
453
|
+
return summarizeToolStart(event.tool_call);
|
|
454
|
+
}
|
|
455
|
+
if (event.type === "result") {
|
|
456
|
+
const ms = typeof event.duration_ms === "number" ? event.duration_ms : 0;
|
|
457
|
+
const failed = event.is_error === true || event.subtype === "error";
|
|
458
|
+
return failed
|
|
459
|
+
? `Cursor agent reported an error after ${formatDuration(ms)}.`
|
|
460
|
+
: `Cursor agent finished in ${formatDuration(ms)}.`;
|
|
461
|
+
}
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
function summarizeCopilotLine(event) {
|
|
465
|
+
const type = typeof event.type === "string" ? event.type : "";
|
|
466
|
+
const isCopilot = type.includes(".") || type === "tool_use" || type === "tool_result" || type === "message";
|
|
467
|
+
if (!isCopilot)
|
|
468
|
+
return undefined;
|
|
469
|
+
const data = event.data && typeof event.data === "object" ? event.data : event;
|
|
470
|
+
if (type === "user.message")
|
|
471
|
+
return null;
|
|
472
|
+
if (type === "tool.execution_complete" || type === "tool_result")
|
|
473
|
+
return null;
|
|
474
|
+
if (type === "tool.execution_start" || type === "tool_use") {
|
|
475
|
+
const name = String(data.toolName ?? data.name ?? event.name ?? "a tool");
|
|
476
|
+
const args = (data.arguments ?? data.input ?? event.input);
|
|
477
|
+
return summarizeCopilotTool(name, args);
|
|
478
|
+
}
|
|
479
|
+
if (type === "assistant.message" || type === "assistant" || type === "message") {
|
|
480
|
+
const requests = data.toolRequests;
|
|
481
|
+
if (Array.isArray(requests) && requests[0] && typeof requests[0] === "object") {
|
|
482
|
+
const req = requests[0];
|
|
483
|
+
return summarizeCopilotTool(String(req.name ?? "a tool"), req.arguments);
|
|
484
|
+
}
|
|
485
|
+
const content = data.content ?? event.content;
|
|
486
|
+
const body = typeof content === "string" ? content.trim() : "";
|
|
487
|
+
return body ? clip(`Agent: ${body}`, 280) : null;
|
|
488
|
+
}
|
|
489
|
+
if (type === "session.error") {
|
|
490
|
+
const message = data.message ?? data.error ?? event.message;
|
|
491
|
+
return clip(`Copilot error: ${String(message ?? "unknown")}`, 280);
|
|
492
|
+
}
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
function summarizeCopilotTool(name, args) {
|
|
496
|
+
const kind = name.toLowerCase();
|
|
497
|
+
const file = toolArg(args, "path") !== "…" ? toolArg(args, "path") : toolArg(args, "file_path");
|
|
498
|
+
const command = toolArg(args, "command") !== "…" ? toolArg(args, "command") : toolArg(args, "cmd");
|
|
499
|
+
if (kind.includes("bash") || kind.includes("shell") || command !== "…")
|
|
500
|
+
return clip(`Running ${command}`, 280);
|
|
501
|
+
if (kind.includes("edit") || kind.includes("write") || kind.includes("create"))
|
|
502
|
+
return clip(`Writing ${file}`, 280);
|
|
503
|
+
if (kind.includes("read"))
|
|
504
|
+
return clip(`Reading ${file}`, 280);
|
|
505
|
+
if (kind.includes("grep") || kind.includes("search")) {
|
|
506
|
+
const pattern = toolArg(args, "pattern") !== "…" ? toolArg(args, "pattern") : toolArg(args, "query");
|
|
507
|
+
return clip(`Searching ${pattern}`, 280);
|
|
508
|
+
}
|
|
509
|
+
return clip(`Using ${name}`, 280);
|
|
510
|
+
}
|
|
511
|
+
function assistantText(event) {
|
|
512
|
+
const message = event.message;
|
|
513
|
+
const content = message?.content;
|
|
514
|
+
if (!Array.isArray(content))
|
|
515
|
+
return "";
|
|
516
|
+
return content
|
|
517
|
+
.map((part) => (part && typeof part === "object" && "text" in part ? String(part.text ?? "") : ""))
|
|
518
|
+
.join(" ")
|
|
519
|
+
.replace(/\s+/g, " ")
|
|
520
|
+
.trim();
|
|
521
|
+
}
|
|
522
|
+
function summarizeToolStart(toolCall) {
|
|
523
|
+
if (!toolCall || typeof toolCall !== "object")
|
|
524
|
+
return null;
|
|
525
|
+
const record = toolCall;
|
|
526
|
+
if (record.readToolCall)
|
|
527
|
+
return clip(`Reading ${toolArg(record.readToolCall.args, "path")}`, 280);
|
|
528
|
+
if (record.writeToolCall)
|
|
529
|
+
return clip(`Writing ${toolArg(record.writeToolCall.args, "path")}`, 280);
|
|
530
|
+
if (record.editToolCall)
|
|
531
|
+
return clip(`Editing ${toolArg(record.editToolCall.args, "path")}`, 280);
|
|
532
|
+
if (record.deleteToolCall)
|
|
533
|
+
return clip(`Deleting ${toolArg(record.deleteToolCall.args, "path")}`, 280);
|
|
534
|
+
if (record.shellToolCall)
|
|
535
|
+
return clip(`Running ${toolArg(record.shellToolCall.args, "command")}`, 280);
|
|
536
|
+
if (record.grepToolCall)
|
|
537
|
+
return clip(`Searching ${toolArg(record.grepToolCall.args, "pattern")}`, 280);
|
|
538
|
+
if (record.lsToolCall)
|
|
539
|
+
return clip(`Listing ${toolArg(record.lsToolCall.args, "path")}`, 280);
|
|
540
|
+
if (record.globToolCall)
|
|
541
|
+
return clip(`Finding ${toolArg(record.globToolCall.args, "glob_pattern") || toolArg(record.globToolCall.args, "pattern")}`, 280);
|
|
542
|
+
const fn = record.function;
|
|
543
|
+
if (fn?.args && typeof fn.args.name === "string")
|
|
544
|
+
return clip(`Using ${fn.args.name}`, 280);
|
|
545
|
+
const key = Object.keys(record).find((name) => name.endsWith("ToolCall"));
|
|
546
|
+
return key ? clip(`Using ${key.replace(/ToolCall$/, "")}`, 280) : "Using a tool.";
|
|
547
|
+
}
|
|
548
|
+
function toolArg(args, key) {
|
|
549
|
+
const value = args?.[key];
|
|
550
|
+
if (typeof value !== "string" || !value.trim())
|
|
551
|
+
return "…";
|
|
552
|
+
return value.replace(/\s+/g, " ").trim();
|
|
553
|
+
}
|
|
554
|
+
function formatDuration(ms) {
|
|
555
|
+
if (!Number.isFinite(ms) || ms < 1000)
|
|
556
|
+
return `${Math.max(0, Math.round(ms))}ms`;
|
|
557
|
+
const seconds = Math.round(ms / 1000);
|
|
558
|
+
if (seconds < 60)
|
|
559
|
+
return `${seconds}s`;
|
|
560
|
+
const minutes = Math.floor(seconds / 60);
|
|
561
|
+
const rest = seconds % 60;
|
|
562
|
+
return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
|
|
563
|
+
}
|
|
564
|
+
function clip(value, max) {
|
|
565
|
+
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
|
|
566
|
+
}
|
|
567
|
+
function makeLineFeeder(onLine) {
|
|
568
|
+
let pending = "";
|
|
569
|
+
return (chunk) => {
|
|
570
|
+
pending += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
571
|
+
const lines = pending.split(/\r?\n/);
|
|
572
|
+
pending = lines.pop() ?? "";
|
|
573
|
+
for (const line of lines) {
|
|
574
|
+
const text = line.trim();
|
|
575
|
+
if (text)
|
|
576
|
+
onLine(text.slice(0, 280));
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
function redactSecrets(line) {
|
|
581
|
+
let out = line;
|
|
582
|
+
for (const name of ["CURSOR_API_KEY", "COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"]) {
|
|
583
|
+
const key = process.env[name]?.trim();
|
|
584
|
+
if (key && out.includes(key))
|
|
585
|
+
out = out.split(key).join("…");
|
|
586
|
+
}
|
|
587
|
+
return out;
|
|
588
|
+
}
|
|
589
|
+
async function waitForAgent(child, settleMs, logPath, bin, agentName = "Cursor") {
|
|
590
|
+
if (settleMs > 0) {
|
|
591
|
+
await new Promise((resolve) => setTimeout(resolve, settleMs));
|
|
592
|
+
}
|
|
593
|
+
if (!child || child.exitCode === null || child.exitCode === undefined) {
|
|
594
|
+
return { ok: true, message: "started" };
|
|
595
|
+
}
|
|
596
|
+
const tail = tailLog(logPath);
|
|
597
|
+
const loginHint = agentName === "Copilot"
|
|
598
|
+
? `If you are not logged in, run: "${bin}" /login`
|
|
599
|
+
: `If you are not logged in, run: "${bin}" agent login`;
|
|
600
|
+
return {
|
|
601
|
+
ok: false,
|
|
602
|
+
message: tail
|
|
603
|
+
? `${agentName} agent exited immediately (${child.exitCode}). ${tail}`
|
|
604
|
+
: `${agentName} agent exited immediately (${child.exitCode}). ${loginHint}`,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function tailLog(logPath) {
|
|
608
|
+
try {
|
|
609
|
+
const text = readFileSync(logPath, "utf8").trim().split(/\r?\n/).slice(-4).join(" ");
|
|
610
|
+
return text.slice(0, 280);
|
|
611
|
+
}
|
|
612
|
+
catch {
|
|
613
|
+
return "";
|
|
614
|
+
}
|
|
615
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { PackPaths } from "./pack.js";
|
|
2
|
+
import type { ReadyFinding } from "./types.js";
|
|
3
|
+
export type ImproveLog = {
|
|
4
|
+
accepted: string[];
|
|
5
|
+
pending: string[];
|
|
6
|
+
};
|
|
7
|
+
export declare function readImproveLog(paths: PackPaths): Promise<ImproveLog>;
|
|
8
|
+
export declare function recordImprovePending(paths: PackPaths, findings: ReadyFinding | ReadyFinding[]): Promise<void>;
|
|
9
|
+
export declare function commitImprovePending(paths: PackPaths): Promise<void>;
|
|
10
|
+
export declare function clearImprovePending(paths: PackPaths): Promise<void>;
|
|
11
|
+
export declare function clearImproveLog(paths: PackPaths): Promise<void>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { findingKeys } from "./improve.js";
|
|
3
|
+
export async function readImproveLog(paths) {
|
|
4
|
+
try {
|
|
5
|
+
const raw = JSON.parse(await readFile(paths.improveLog, "utf8"));
|
|
6
|
+
return {
|
|
7
|
+
accepted: Array.isArray(raw.accepted) ? raw.accepted.map(String) : [],
|
|
8
|
+
pending: Array.isArray(raw.pending) ? raw.pending.map(String) : [],
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return { accepted: [], pending: [] };
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export async function recordImprovePending(paths, findings) {
|
|
16
|
+
const list = Array.isArray(findings) ? findings : [findings];
|
|
17
|
+
const log = await readImproveLog(paths);
|
|
18
|
+
log.pending = [...new Set(list.flatMap(findingKeys))];
|
|
19
|
+
await writeImproveLog(paths, log);
|
|
20
|
+
}
|
|
21
|
+
export async function commitImprovePending(paths) {
|
|
22
|
+
const log = await readImproveLog(paths);
|
|
23
|
+
log.accepted = [...new Set([...log.accepted, ...log.pending])];
|
|
24
|
+
log.pending = [];
|
|
25
|
+
await writeImproveLog(paths, log);
|
|
26
|
+
}
|
|
27
|
+
export async function clearImprovePending(paths) {
|
|
28
|
+
const log = await readImproveLog(paths);
|
|
29
|
+
log.pending = [];
|
|
30
|
+
await writeImproveLog(paths, log);
|
|
31
|
+
}
|
|
32
|
+
export async function clearImproveLog(paths) {
|
|
33
|
+
await unlink(paths.improveLog).catch(() => undefined);
|
|
34
|
+
}
|
|
35
|
+
async function writeImproveLog(paths, log) {
|
|
36
|
+
await mkdir(paths.derived, { recursive: true });
|
|
37
|
+
await writeFile(paths.improveLog, `${JSON.stringify(log, null, 2)}\n`, "utf8");
|
|
38
|
+
}
|