copilot-agent 0.4.0 → 0.6.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/dist/index.js +333 -17
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -130,6 +130,102 @@ function findLatestIncomplete() {
|
|
|
130
130
|
}
|
|
131
131
|
return null;
|
|
132
132
|
}
|
|
133
|
+
function getSessionReport(sid) {
|
|
134
|
+
if (!validateSession(sid)) return null;
|
|
135
|
+
const ws = readWorkspace(sid);
|
|
136
|
+
let lines;
|
|
137
|
+
try {
|
|
138
|
+
lines = readFileSync(join(SESSION_DIR, sid, "events.jsonl"), "utf-8").trimEnd().split("\n");
|
|
139
|
+
} catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const report = {
|
|
143
|
+
id: sid,
|
|
144
|
+
cwd: ws.cwd ?? "",
|
|
145
|
+
summary: ws.summary ?? "",
|
|
146
|
+
startTime: "",
|
|
147
|
+
endTime: "",
|
|
148
|
+
durationMs: 0,
|
|
149
|
+
complete: false,
|
|
150
|
+
userMessages: 0,
|
|
151
|
+
assistantTurns: 0,
|
|
152
|
+
outputTokens: 0,
|
|
153
|
+
premiumRequests: 0,
|
|
154
|
+
toolUsage: {},
|
|
155
|
+
gitCommits: [],
|
|
156
|
+
filesCreated: [],
|
|
157
|
+
filesEdited: [],
|
|
158
|
+
errors: [],
|
|
159
|
+
taskCompletions: []
|
|
160
|
+
};
|
|
161
|
+
for (const line of lines) {
|
|
162
|
+
let event;
|
|
163
|
+
try {
|
|
164
|
+
event = JSON.parse(line);
|
|
165
|
+
} catch {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const type = event.type;
|
|
169
|
+
const ts = event.timestamp;
|
|
170
|
+
const data = event.data ?? {};
|
|
171
|
+
if (ts && !report.startTime) report.startTime = ts;
|
|
172
|
+
if (ts) report.endTime = ts;
|
|
173
|
+
switch (type) {
|
|
174
|
+
case "user.message":
|
|
175
|
+
report.userMessages++;
|
|
176
|
+
break;
|
|
177
|
+
case "assistant.message":
|
|
178
|
+
report.assistantTurns++;
|
|
179
|
+
report.outputTokens += data.outputTokens ?? 0;
|
|
180
|
+
break;
|
|
181
|
+
case "tool.execution_start": {
|
|
182
|
+
const toolName = data.toolName;
|
|
183
|
+
if (toolName) {
|
|
184
|
+
report.toolUsage[toolName] = (report.toolUsage[toolName] ?? 0) + 1;
|
|
185
|
+
}
|
|
186
|
+
if (toolName === "bash") {
|
|
187
|
+
const args = data.arguments;
|
|
188
|
+
const cmd = args?.command ?? "";
|
|
189
|
+
if (cmd.includes("git") && cmd.includes("commit") && cmd.includes("-m")) {
|
|
190
|
+
const msgMatch = cmd.match(/-m\s+"([^"]{1,120})/);
|
|
191
|
+
if (msgMatch) report.gitCommits.push(msgMatch[1]);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (toolName === "create") {
|
|
195
|
+
const args = data.arguments;
|
|
196
|
+
if (args?.path) report.filesCreated.push(args.path);
|
|
197
|
+
}
|
|
198
|
+
if (toolName === "edit") {
|
|
199
|
+
const args = data.arguments;
|
|
200
|
+
if (args?.path && !report.filesEdited.includes(args.path)) {
|
|
201
|
+
report.filesEdited.push(args.path);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
case "session.task_complete": {
|
|
207
|
+
const summary = data.summary;
|
|
208
|
+
report.taskCompletions.push(summary ?? "(task completed)");
|
|
209
|
+
report.complete = true;
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
case "session.error": {
|
|
213
|
+
const msg = data.message;
|
|
214
|
+
if (msg) report.errors.push(msg);
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
case "session.shutdown": {
|
|
218
|
+
const premium = data.totalPremiumRequests;
|
|
219
|
+
if (premium != null) report.premiumRequests = premium;
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (report.startTime && report.endTime) {
|
|
225
|
+
report.durationMs = new Date(report.endTime).getTime() - new Date(report.startTime).getTime();
|
|
226
|
+
}
|
|
227
|
+
return report;
|
|
228
|
+
}
|
|
133
229
|
|
|
134
230
|
// src/lib/process.ts
|
|
135
231
|
import { execSync as execSync2, spawn } from "child_process";
|
|
@@ -311,8 +407,11 @@ async function waitForExit(pid, timeoutMs = 144e5) {
|
|
|
311
407
|
}
|
|
312
408
|
async function runCopilot(args, options) {
|
|
313
409
|
const dir = options?.cwd ?? process.cwd();
|
|
314
|
-
|
|
315
|
-
|
|
410
|
+
if (options?.useWorktree) {
|
|
411
|
+
} else {
|
|
412
|
+
await waitForCopilotInDir(dir);
|
|
413
|
+
}
|
|
414
|
+
return new Promise((resolve7) => {
|
|
316
415
|
const child = spawn("copilot", args, {
|
|
317
416
|
cwd: options?.cwd,
|
|
318
417
|
stdio: "inherit",
|
|
@@ -322,14 +421,14 @@ async function runCopilot(args, options) {
|
|
|
322
421
|
await sleep(3e3);
|
|
323
422
|
const sid = getLatestSessionId();
|
|
324
423
|
const premium = sid ? getSessionPremium(sid) : 0;
|
|
325
|
-
|
|
424
|
+
resolve7({
|
|
326
425
|
exitCode: code ?? 1,
|
|
327
426
|
sessionId: sid,
|
|
328
427
|
premium
|
|
329
428
|
});
|
|
330
429
|
});
|
|
331
430
|
child.on("error", () => {
|
|
332
|
-
|
|
431
|
+
resolve7({ exitCode: 1, sessionId: null, premium: 0 });
|
|
333
432
|
});
|
|
334
433
|
});
|
|
335
434
|
}
|
|
@@ -346,7 +445,7 @@ function runCopilotResume(sid, steps, message, cwd) {
|
|
|
346
445
|
if (message) args.push("-p", message);
|
|
347
446
|
return runCopilot(args, { cwd });
|
|
348
447
|
}
|
|
349
|
-
function runCopilotTask(prompt, steps, cwd) {
|
|
448
|
+
function runCopilotTask(prompt, steps, cwd, useWorktree) {
|
|
350
449
|
return runCopilot([
|
|
351
450
|
"-p",
|
|
352
451
|
prompt,
|
|
@@ -355,7 +454,7 @@ function runCopilotTask(prompt, steps, cwd) {
|
|
|
355
454
|
"--max-autopilot-continues",
|
|
356
455
|
String(steps),
|
|
357
456
|
"--no-ask-user"
|
|
358
|
-
], { cwd });
|
|
457
|
+
], { cwd, useWorktree });
|
|
359
458
|
}
|
|
360
459
|
function sleep(ms) {
|
|
361
460
|
return new Promise((r) => setTimeout(r, ms));
|
|
@@ -754,16 +853,34 @@ function gitCountCommits(dir, from, to) {
|
|
|
754
853
|
function gitStatus(dir) {
|
|
755
854
|
return gitExec(dir, "git status --porcelain") ?? "";
|
|
756
855
|
}
|
|
856
|
+
function createWorktree(repoDir, branch) {
|
|
857
|
+
const safeBranch = branch.replace(/[^a-zA-Z0-9._/-]/g, "-");
|
|
858
|
+
const worktreePath = resolve4(repoDir, "..", `${resolve4(repoDir).split("/").pop()}-wt-${safeBranch}`);
|
|
859
|
+
if (existsSync4(worktreePath)) {
|
|
860
|
+
return worktreePath;
|
|
861
|
+
}
|
|
862
|
+
const branchExists = gitExec(repoDir, `git rev-parse --verify ${safeBranch}`) !== null;
|
|
863
|
+
const cmd = branchExists ? `git worktree add "${worktreePath}" ${safeBranch}` : `git worktree add -b ${safeBranch} "${worktreePath}"`;
|
|
864
|
+
if (gitExec(repoDir, cmd) !== null) {
|
|
865
|
+
return worktreePath;
|
|
866
|
+
}
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
869
|
+
function removeWorktree(repoDir, worktreePath) {
|
|
870
|
+
const result = gitExec(repoDir, `git worktree remove "${worktreePath}" --force`);
|
|
871
|
+
return result !== null;
|
|
872
|
+
}
|
|
757
873
|
|
|
758
874
|
// src/commands/run.ts
|
|
759
875
|
function registerRunCommand(program2) {
|
|
760
|
-
program2.command("run [dir]").description("Discover and fix issues in a project").option("-s, --steps <n>", "Max autopilot continues per task", "30").option("-t, --max-tasks <n>", "Max number of tasks to run", "5").option("-p, --max-premium <n>", "Max total premium requests", "50").option("--dry-run", "Show tasks without executing").action(async (dir, opts) => {
|
|
876
|
+
program2.command("run [dir]").description("Discover and fix issues in a project").option("-s, --steps <n>", "Max autopilot continues per task", "30").option("-t, --max-tasks <n>", "Max number of tasks to run", "5").option("-p, --max-premium <n>", "Max total premium requests", "50").option("--dry-run", "Show tasks without executing").option("--worktree", "Use git worktree for parallel execution (default: wait for idle)").action(async (dir, opts) => {
|
|
761
877
|
try {
|
|
762
878
|
await runCommand(dir ?? process.cwd(), {
|
|
763
879
|
steps: parseInt(opts.steps, 10),
|
|
764
880
|
maxTasks: parseInt(opts.maxTasks, 10),
|
|
765
881
|
maxPremium: parseInt(opts.maxPremium, 10),
|
|
766
|
-
dryRun: opts.dryRun ?? false
|
|
882
|
+
dryRun: opts.dryRun ?? false,
|
|
883
|
+
useWorktree: opts.worktree ?? false
|
|
767
884
|
});
|
|
768
885
|
} catch (err) {
|
|
769
886
|
fail(`Run error: ${err instanceof Error ? err.message : err}`);
|
|
@@ -814,15 +931,35 @@ ${"\u2550".repeat(60)}`);
|
|
|
814
931
|
}
|
|
815
932
|
}
|
|
816
933
|
info(`Running: ${task.title}\u2026`);
|
|
934
|
+
let taskDir = dir;
|
|
935
|
+
let worktreeCreated = false;
|
|
936
|
+
if (opts.useWorktree && isGitRepo(dir)) {
|
|
937
|
+
try {
|
|
938
|
+
taskDir = createWorktree(dir, branchName, mainBranch ?? void 0);
|
|
939
|
+
worktreeCreated = true;
|
|
940
|
+
info(`Created worktree: ${taskDir}`);
|
|
941
|
+
} catch (err) {
|
|
942
|
+
warn(`Worktree creation failed, falling back to main dir: ${err}`);
|
|
943
|
+
taskDir = dir;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
817
946
|
const result = await withLock(
|
|
818
947
|
"copilot-run",
|
|
819
|
-
() => runCopilotTask(task.prompt, opts.steps,
|
|
948
|
+
() => runCopilotTask(task.prompt, opts.steps, taskDir, opts.useWorktree)
|
|
820
949
|
);
|
|
821
|
-
const
|
|
950
|
+
const commitRef = worktreeCreated ? taskDir : dir;
|
|
951
|
+
const commits = mainBranch ? gitCountCommits(commitRef, mainBranch, "HEAD") : 0;
|
|
822
952
|
premiumTotal += result.premium;
|
|
823
953
|
completed++;
|
|
824
954
|
ok(`${task.title} \u2014 ${commits} commit(s), ${result.premium} premium`);
|
|
825
|
-
if (
|
|
955
|
+
if (worktreeCreated) {
|
|
956
|
+
try {
|
|
957
|
+
removeWorktree(dir, taskDir);
|
|
958
|
+
} catch (err) {
|
|
959
|
+
warn(`Worktree cleanup failed: ${err}`);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
if (!worktreeCreated && originalBranch && isGitRepo(dir)) {
|
|
826
963
|
gitCheckout(dir, mainBranch ?? originalBranch);
|
|
827
964
|
}
|
|
828
965
|
}
|
|
@@ -836,14 +973,15 @@ ${BOLD}\u2550\u2550\u2550 Run Summary \u2550\u2550\u2550${RESET}`);
|
|
|
836
973
|
import { join as join5 } from "path";
|
|
837
974
|
import { homedir as homedir3 } from "os";
|
|
838
975
|
function registerOvernightCommand(program2) {
|
|
839
|
-
program2.command("overnight [dir]").description("Run tasks continuously until a deadline").option("-u, --until <HH>", "Stop at this hour (24h format)", "07").option("-s, --steps <n>", "Max autopilot continues per task", "50").option("-c, --cooldown <n>", "Seconds between tasks", "15").option("-p, --max-premium <n>", "Max premium requests budget", "300").option("--dry-run", "Show plan without executing").action(async (dir, opts) => {
|
|
976
|
+
program2.command("overnight [dir]").description("Run tasks continuously until a deadline").option("-u, --until <HH>", "Stop at this hour (24h format)", "07").option("-s, --steps <n>", "Max autopilot continues per task", "50").option("-c, --cooldown <n>", "Seconds between tasks", "15").option("-p, --max-premium <n>", "Max premium requests budget", "300").option("--dry-run", "Show plan without executing").option("--worktree", "Use git worktree for parallel execution (default: wait for idle)").action(async (dir, opts) => {
|
|
840
977
|
try {
|
|
841
978
|
await overnightCommand(dir ?? process.cwd(), {
|
|
842
979
|
until: parseInt(opts.until, 10),
|
|
843
980
|
steps: parseInt(opts.steps, 10),
|
|
844
981
|
cooldown: parseInt(opts.cooldown, 10),
|
|
845
982
|
maxPremium: parseInt(opts.maxPremium, 10),
|
|
846
|
-
dryRun: opts.dryRun ?? false
|
|
983
|
+
dryRun: opts.dryRun ?? false,
|
|
984
|
+
useWorktree: opts.worktree ?? false
|
|
847
985
|
});
|
|
848
986
|
} catch (err) {
|
|
849
987
|
fail(`Overnight error: ${err instanceof Error ? err.message : err}`);
|
|
@@ -918,12 +1056,25 @@ ${"\u2550".repeat(60)}`);
|
|
|
918
1056
|
gitCreateBranch(dir, branchName);
|
|
919
1057
|
}
|
|
920
1058
|
info(`Running: ${task.title}\u2026`);
|
|
1059
|
+
let taskDir = dir;
|
|
1060
|
+
let worktreeCreated = false;
|
|
1061
|
+
if (opts.useWorktree && isGitRepo(dir)) {
|
|
1062
|
+
try {
|
|
1063
|
+
taskDir = createWorktree(dir, branchName, mainBranch ?? void 0);
|
|
1064
|
+
worktreeCreated = true;
|
|
1065
|
+
info(`Created worktree: ${taskDir}`);
|
|
1066
|
+
} catch (err) {
|
|
1067
|
+
warn(`Worktree creation failed, falling back to main dir: ${err}`);
|
|
1068
|
+
taskDir = dir;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
921
1071
|
try {
|
|
922
1072
|
const result = await withLock(
|
|
923
1073
|
"copilot-overnight",
|
|
924
|
-
() => runCopilotTask(task.prompt, opts.steps,
|
|
1074
|
+
() => runCopilotTask(task.prompt, opts.steps, taskDir, opts.useWorktree)
|
|
925
1075
|
);
|
|
926
|
-
const
|
|
1076
|
+
const commitRef = worktreeCreated ? taskDir : dir;
|
|
1077
|
+
const commits = mainBranch ? gitCountCommits(commitRef, mainBranch, "HEAD") : 0;
|
|
927
1078
|
totalPremium += result.premium;
|
|
928
1079
|
totalCommits += commits;
|
|
929
1080
|
if (commits > 0) {
|
|
@@ -934,7 +1085,15 @@ ${"\u2550".repeat(60)}`);
|
|
|
934
1085
|
} catch (err) {
|
|
935
1086
|
fail(`Task failed: ${err}`);
|
|
936
1087
|
}
|
|
937
|
-
if (
|
|
1088
|
+
if (worktreeCreated) {
|
|
1089
|
+
try {
|
|
1090
|
+
removeWorktree(dir, taskDir);
|
|
1091
|
+
info(`Removed worktree: ${taskDir}`);
|
|
1092
|
+
} catch (err) {
|
|
1093
|
+
warn(`Worktree cleanup failed: ${err}`);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (!worktreeCreated && mainBranch && isGitRepo(dir)) {
|
|
938
1097
|
gitCheckout(dir, mainBranch);
|
|
939
1098
|
}
|
|
940
1099
|
if (!isPastDeadline(opts.until)) {
|
|
@@ -1016,13 +1175,170 @@ async function researchCommand(dir, opts) {
|
|
|
1016
1175
|
notify("Research complete", projectName);
|
|
1017
1176
|
}
|
|
1018
1177
|
|
|
1178
|
+
// src/commands/report.ts
|
|
1179
|
+
import { resolve as resolve6 } from "path";
|
|
1180
|
+
function registerReportCommand(program2) {
|
|
1181
|
+
program2.command("report [session-id]").description("Show what copilot did \u2014 timeline, tools, commits, files changed").option("-l, --limit <n>", "Number of recent sessions to report (when no ID given)", "1").option("--project <dir>", "Filter sessions by project directory").option("--json", "Output raw JSON").action((sessionId, opts) => {
|
|
1182
|
+
try {
|
|
1183
|
+
if (sessionId) {
|
|
1184
|
+
reportSingle(sessionId, opts.json ?? false);
|
|
1185
|
+
} else {
|
|
1186
|
+
reportRecent(parseInt(opts.limit, 10), opts.project, opts.json ?? false);
|
|
1187
|
+
}
|
|
1188
|
+
} catch (err) {
|
|
1189
|
+
fail(`Report error: ${err instanceof Error ? err.message : err}`);
|
|
1190
|
+
process.exit(1);
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
function reportRecent(limit, projectDir, json = false) {
|
|
1195
|
+
let sessions = listSessions(limit * 3);
|
|
1196
|
+
if (projectDir) {
|
|
1197
|
+
const target = resolve6(projectDir);
|
|
1198
|
+
sessions = sessions.filter((s) => s.cwd && resolve6(s.cwd) === target);
|
|
1199
|
+
}
|
|
1200
|
+
sessions = sessions.slice(0, limit);
|
|
1201
|
+
if (sessions.length === 0) {
|
|
1202
|
+
warn("No sessions found.");
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
for (const s of sessions) {
|
|
1206
|
+
reportSingle(s.id, json);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
function reportSingle(sid, json = false) {
|
|
1210
|
+
const report = getSessionReport(sid);
|
|
1211
|
+
if (!report) {
|
|
1212
|
+
warn(`Session ${sid} not found or invalid.`);
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
if (json) {
|
|
1216
|
+
log(JSON.stringify(report, null, 2));
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
renderReport(report);
|
|
1220
|
+
}
|
|
1221
|
+
function formatDuration(ms) {
|
|
1222
|
+
if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
|
|
1223
|
+
if (ms < 36e5) return `${Math.round(ms / 6e4)}m`;
|
|
1224
|
+
const h = Math.floor(ms / 36e5);
|
|
1225
|
+
const m = Math.round(ms % 36e5 / 6e4);
|
|
1226
|
+
return `${h}h ${m}m`;
|
|
1227
|
+
}
|
|
1228
|
+
function formatTime(iso) {
|
|
1229
|
+
if (!iso) return "\u2014";
|
|
1230
|
+
const d = new Date(iso);
|
|
1231
|
+
return d.toLocaleString("en-GB", {
|
|
1232
|
+
month: "short",
|
|
1233
|
+
day: "numeric",
|
|
1234
|
+
hour: "2-digit",
|
|
1235
|
+
minute: "2-digit"
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
function bar(value, max, width = 20) {
|
|
1239
|
+
const filled = Math.round(value / Math.max(max, 1) * width);
|
|
1240
|
+
return "\u2588".repeat(filled) + "\u2591".repeat(width - filled);
|
|
1241
|
+
}
|
|
1242
|
+
function renderReport(r) {
|
|
1243
|
+
const status = r.complete ? `${GREEN}\u2714 Completed${RESET}` : `${YELLOW}\u23F8 Interrupted${RESET}`;
|
|
1244
|
+
const projectName = r.cwd.split("/").pop() ?? r.cwd;
|
|
1245
|
+
log("");
|
|
1246
|
+
log(`${BOLD}\u2554${"\u2550".repeat(62)}\u2557${RESET}`);
|
|
1247
|
+
log(`${BOLD}\u2551${RESET} \u{1F4CB} Session Report: ${CYAN}${r.id.slice(0, 8)}\u2026${RESET}${" ".repeat(62 - 28 - r.id.slice(0, 8).length)}${BOLD}\u2551${RESET}`);
|
|
1248
|
+
log(`${BOLD}\u255A${"\u2550".repeat(62)}\u255D${RESET}`);
|
|
1249
|
+
log("");
|
|
1250
|
+
log(`${BOLD} Overview${RESET}`);
|
|
1251
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1252
|
+
log(` Project: ${CYAN}${projectName}${RESET} ${DIM}${r.cwd}${RESET}`);
|
|
1253
|
+
log(` Status: ${status}`);
|
|
1254
|
+
log(` Duration: ${BOLD}${formatDuration(r.durationMs)}${RESET} ${DIM}(${formatTime(r.startTime)} \u2192 ${formatTime(r.endTime)})${RESET}`);
|
|
1255
|
+
log(` Summary: ${r.summary || DIM + "(none)" + RESET}`);
|
|
1256
|
+
log("");
|
|
1257
|
+
log(`${BOLD} Activity${RESET}`);
|
|
1258
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1259
|
+
log(` User messages: ${BOLD}${r.userMessages}${RESET}`);
|
|
1260
|
+
log(` Assistant turns: ${BOLD}${r.assistantTurns}${RESET}`);
|
|
1261
|
+
log(` Output tokens: ${BOLD}${r.outputTokens.toLocaleString()}${RESET}`);
|
|
1262
|
+
log(` Premium requests: ${BOLD}${r.premiumRequests}${RESET}`);
|
|
1263
|
+
log(` Tool calls: ${BOLD}${Object.values(r.toolUsage).reduce((a, b) => a + b, 0)}${RESET}`);
|
|
1264
|
+
const toolEntries = Object.entries(r.toolUsage).sort((a, b) => b[1] - a[1]);
|
|
1265
|
+
if (toolEntries.length > 0) {
|
|
1266
|
+
const maxCount = toolEntries[0][1];
|
|
1267
|
+
log("");
|
|
1268
|
+
log(`${BOLD} Tools Used${RESET}`);
|
|
1269
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1270
|
+
for (const [tool, count] of toolEntries.slice(0, 10)) {
|
|
1271
|
+
const barStr = bar(count, maxCount, 15);
|
|
1272
|
+
log(` ${DIM}${barStr}${RESET} ${String(count).padStart(5)} ${tool}`);
|
|
1273
|
+
}
|
|
1274
|
+
if (toolEntries.length > 10) {
|
|
1275
|
+
log(` ${DIM} \u2026 and ${toolEntries.length - 10} more tools${RESET}`);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
if (r.gitCommits.length > 0) {
|
|
1279
|
+
log("");
|
|
1280
|
+
log(`${BOLD} Git Commits (${r.gitCommits.length})${RESET}`);
|
|
1281
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1282
|
+
for (const msg of r.gitCommits) {
|
|
1283
|
+
log(` ${GREEN}\u25CF${RESET} ${msg.slice(0, 70)}${msg.length > 70 ? "\u2026" : ""}`);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
if (r.filesCreated.length > 0) {
|
|
1287
|
+
log("");
|
|
1288
|
+
log(`${BOLD} Files Created (${r.filesCreated.length})${RESET}`);
|
|
1289
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1290
|
+
for (const f of r.filesCreated.slice(0, 15)) {
|
|
1291
|
+
const short = f.includes(projectName) ? f.split(projectName + "/")[1] ?? f : f;
|
|
1292
|
+
log(` ${GREEN}+${RESET} ${short}`);
|
|
1293
|
+
}
|
|
1294
|
+
if (r.filesCreated.length > 15) {
|
|
1295
|
+
log(` ${DIM} \u2026 and ${r.filesCreated.length - 15} more${RESET}`);
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
if (r.filesEdited.length > 0) {
|
|
1299
|
+
log("");
|
|
1300
|
+
log(`${BOLD} Files Edited (${r.filesEdited.length})${RESET}`);
|
|
1301
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1302
|
+
for (const f of r.filesEdited.slice(0, 15)) {
|
|
1303
|
+
const short = f.includes(projectName) ? f.split(projectName + "/")[1] ?? f : f;
|
|
1304
|
+
log(` ${YELLOW}~${RESET} ${short}`);
|
|
1305
|
+
}
|
|
1306
|
+
if (r.filesEdited.length > 15) {
|
|
1307
|
+
log(` ${DIM} \u2026 and ${r.filesEdited.length - 15} more${RESET}`);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
if (r.taskCompletions.length > 0) {
|
|
1311
|
+
log("");
|
|
1312
|
+
log(`${BOLD} Tasks Completed (${r.taskCompletions.length})${RESET}`);
|
|
1313
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1314
|
+
for (const t of r.taskCompletions) {
|
|
1315
|
+
const lines = t.split("\n");
|
|
1316
|
+
const first = lines[0].slice(0, 70);
|
|
1317
|
+
log(` ${GREEN}\u2714${RESET} ${first}${first.length < lines[0].length ? "\u2026" : ""}`);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
if (r.errors.length > 0) {
|
|
1321
|
+
log("");
|
|
1322
|
+
log(`${BOLD} Errors (${r.errors.length})${RESET}`);
|
|
1323
|
+
log(` ${"\u2500".repeat(58)}`);
|
|
1324
|
+
for (const e of r.errors.slice(0, 5)) {
|
|
1325
|
+
log(` ${RED}\u2716${RESET} ${e.slice(0, 70)}`);
|
|
1326
|
+
}
|
|
1327
|
+
if (r.errors.length > 5) {
|
|
1328
|
+
log(` ${DIM} \u2026 and ${r.errors.length - 5} more${RESET}`);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
log("");
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1019
1334
|
// src/index.ts
|
|
1020
1335
|
var program = new Command();
|
|
1021
|
-
program.name("copilot-agent").version("0.
|
|
1336
|
+
program.name("copilot-agent").version("0.6.0").description("Autonomous GitHub Copilot CLI agent \u2014 auto-resume, task discovery, overnight runs");
|
|
1022
1337
|
registerStatusCommand(program);
|
|
1023
1338
|
registerWatchCommand(program);
|
|
1024
1339
|
registerRunCommand(program);
|
|
1025
1340
|
registerOvernightCommand(program);
|
|
1026
1341
|
registerResearchCommand(program);
|
|
1342
|
+
registerReportCommand(program);
|
|
1027
1343
|
program.parse();
|
|
1028
1344
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/lib/session.ts","../src/lib/process.ts","../src/lib/logger.ts","../src/lib/colors.ts","../src/commands/status.ts","../src/commands/watch.ts","../src/lib/detect.ts","../src/lib/tasks.ts","../src/lib/lock.ts","../src/lib/git.ts","../src/commands/run.ts","../src/commands/overnight.ts","../src/commands/research.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { registerStatusCommand } from './commands/status.js';\nimport { registerWatchCommand } from './commands/watch.js';\nimport { registerRunCommand } from './commands/run.js';\nimport { registerOvernightCommand } from './commands/overnight.js';\nimport { registerResearchCommand } from './commands/research.js';\n\nconst program = new Command();\n\nprogram\n .name('copilot-agent')\n .version('0.4.0')\n .description('Autonomous GitHub Copilot CLI agent — auto-resume, task discovery, overnight runs');\n\nregisterStatusCommand(program);\nregisterWatchCommand(program);\nregisterRunCommand(program);\nregisterOvernightCommand(program);\nregisterResearchCommand(program);\n\nprogram.parse();\n","import {\n existsSync,\n readdirSync,\n readFileSync,\n statSync,\n} from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport interface Session {\n id: string;\n dir: string;\n mtime: number;\n lastEvent: string;\n premiumRequests: number;\n summary: string;\n cwd: string;\n complete: boolean;\n}\n\nconst SESSION_DIR = join(homedir(), '.copilot', 'session-state');\n\nexport function getSessionDir(): string {\n return SESSION_DIR;\n}\n\nexport function validateSession(sid: string): boolean {\n const events = join(SESSION_DIR, sid, 'events.jsonl');\n try {\n return existsSync(events) && statSync(events).size > 0;\n } catch {\n return false;\n }\n}\n\nexport function listSessions(limit = 20): Session[] {\n if (!existsSync(SESSION_DIR)) return [];\n\n const entries = readdirSync(SESSION_DIR, { withFileTypes: true })\n .filter(d => d.isDirectory());\n\n const dirs: { id: string; dir: string; mtime: number }[] = [];\n for (const entry of entries) {\n const dirPath = join(SESSION_DIR, entry.name);\n if (!existsSync(join(dirPath, 'events.jsonl'))) continue;\n try {\n const stat = statSync(dirPath);\n dirs.push({ id: entry.name, dir: dirPath, mtime: stat.mtimeMs });\n } catch { /* skip */ }\n }\n\n dirs.sort((a, b) => b.mtime - a.mtime);\n\n return dirs.slice(0, limit).map(s => ({\n id: s.id,\n dir: s.dir,\n mtime: s.mtime,\n lastEvent: getLastEvent(s.id),\n premiumRequests: getSessionPremium(s.id),\n summary: getSessionSummary(s.id),\n cwd: getSessionCwd(s.id),\n complete: hasTaskComplete(s.id),\n }));\n}\n\nexport function getLatestSessionId(): string | null {\n if (!existsSync(SESSION_DIR)) return null;\n\n const entries = readdirSync(SESSION_DIR, { withFileTypes: true })\n .filter(d => d.isDirectory());\n\n let latest: { id: string; mtime: number } | null = null;\n for (const entry of entries) {\n try {\n const stat = statSync(join(SESSION_DIR, entry.name));\n if (!latest || stat.mtimeMs > latest.mtime) {\n latest = { id: entry.name, mtime: stat.mtimeMs };\n }\n } catch { /* skip */ }\n }\n return latest?.id ?? null;\n}\n\nexport function hasTaskComplete(sid: string): boolean {\n if (!validateSession(sid)) return false;\n try {\n const content = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8');\n return content.includes('\"session.task_complete\"');\n } catch {\n return false;\n }\n}\n\nexport function getLastEvent(sid: string): string {\n if (!validateSession(sid)) return 'invalid';\n try {\n const lines = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8')\n .trimEnd()\n .split('\\n');\n const last = JSON.parse(lines[lines.length - 1]);\n return last.type ?? 'unknown';\n } catch {\n return 'corrupted';\n }\n}\n\nexport function getSessionPremium(sid: string): number {\n if (!validateSession(sid)) return 0;\n try {\n const content = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8');\n const lines = content.trimEnd().split('\\n');\n for (let i = lines.length - 1; i >= 0; i--) {\n try {\n const event = JSON.parse(lines[i]);\n if (event.type === 'session.shutdown' && event.data?.totalPremiumRequests != null) {\n return event.data.totalPremiumRequests;\n }\n } catch { /* skip malformed line */ }\n }\n return 0;\n } catch {\n return 0;\n }\n}\n\nfunction parseSimpleYaml(content: string): Record<string, string> {\n const result: Record<string, string> = {};\n for (const line of content.split('\\n')) {\n const idx = line.indexOf(': ');\n if (idx === -1) continue;\n const key = line.substring(0, idx).trim();\n const value = line.substring(idx + 2).trim();\n if (key) result[key] = value;\n }\n return result;\n}\n\nfunction readWorkspace(sid: string): Record<string, string> {\n const wsPath = join(SESSION_DIR, sid, 'workspace.yaml');\n if (!existsSync(wsPath)) return {};\n try {\n return parseSimpleYaml(readFileSync(wsPath, 'utf-8'));\n } catch {\n return {};\n }\n}\n\nexport function getSessionSummary(sid: string): string {\n return readWorkspace(sid).summary ?? '';\n}\n\nexport function getSessionCwd(sid: string): string {\n return readWorkspace(sid).cwd ?? '';\n}\n\nexport function findSessionForProject(projectPath: string): string | null {\n const resolved = resolve(projectPath);\n const sessions = listSessions(50);\n for (const s of sessions) {\n if (s.cwd && resolve(s.cwd) === resolved) return s.id;\n }\n return null;\n}\n\nexport function findLatestIncomplete(): string | null {\n const sessions = listSessions(50);\n for (const s of sessions) {\n if (!s.complete) return s.id;\n }\n return null;\n}\n","import { execSync, spawn } from 'node:child_process';\nimport { resolve } from 'node:path';\nimport { getLatestSessionId, getSessionPremium, getSessionCwd } from './session.js';\nimport { log, warn, fail } from './logger.js';\n\nexport interface CopilotProcess {\n pid: number;\n command: string;\n sessionId?: string;\n cwd?: string;\n}\n\nexport interface CopilotResult {\n exitCode: number;\n sessionId: string | null;\n premium: number;\n}\n\nexport function isCopilotInstalled(): boolean {\n try {\n execSync('which copilot', { stdio: 'pipe', encoding: 'utf-8' });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function assertCopilot(): void {\n if (!isCopilotInstalled()) {\n fail('copilot CLI not found. Install with: npm i -g @githubnext/copilot');\n process.exit(1);\n }\n}\n\nexport function findCopilotProcesses(): CopilotProcess[] {\n try {\n const output = execSync('ps -eo pid,command', { encoding: 'utf-8' });\n const results: CopilotProcess[] = [];\n const myPid = process.pid;\n const parentPid = process.ppid;\n for (const line of output.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n if (\n (trimmed.includes('copilot') || trimmed.includes('@githubnext/copilot')) &&\n !trimmed.includes('ps -eo') &&\n !trimmed.includes('copilot-agent') &&\n !trimmed.includes('grep')\n ) {\n const match = trimmed.match(/^(\\d+)\\s+(.+)$/);\n if (match) {\n const pid = parseInt(match[1], 10);\n // Exclude our own process tree\n if (pid === myPid || pid === parentPid) continue;\n const cmd = match[2];\n const sidMatch = cmd.match(/resume[= ]+([a-f0-9-]{36})/);\n // Try to get cwd of the process\n let cwd: string | undefined;\n try {\n cwd = execSync(`lsof -p ${pid} -Fn 2>/dev/null | grep '^n/' | head -1`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim().slice(1) || undefined;\n } catch { /* best effort */ }\n // Fallback: get cwd from session if we know the session\n const sid = sidMatch?.[1];\n if (!cwd && sid) {\n cwd = getSessionCwd(sid) || undefined;\n }\n results.push({ pid, command: cmd, sessionId: sid, cwd });\n }\n }\n }\n return results;\n } catch {\n return [];\n }\n}\n\nexport function findPidForSession(sid: string): number | null {\n const procs = findCopilotProcesses();\n const matching = procs\n .filter(p => p.command.includes(sid))\n .sort((a, b) => b.pid - a.pid);\n return matching[0]?.pid ?? null;\n}\n\n/**\n * SAFETY: Wait until no copilot is running in the SAME directory.\n * Copilot in different directories/worktrees can run in parallel.\n */\nexport async function waitForCopilotInDir(\n dir: string,\n timeoutMs = 14_400_000,\n pollMs = 10_000,\n): Promise<void> {\n const targetDir = resolve(dir);\n const start = Date.now();\n let warned = false;\n while (Date.now() - start < timeoutMs) {\n const procs = findCopilotProcesses();\n const conflicting = procs.filter(p => {\n if (!p.cwd) return false;\n return resolve(p.cwd) === targetDir;\n });\n if (conflicting.length === 0) return;\n if (!warned) {\n warn(`Waiting for copilot in ${targetDir} to finish...`);\n for (const p of conflicting) {\n log(` PID ${p.pid}: ${p.command.slice(0, 80)}`);\n }\n warned = true;\n }\n await sleep(pollMs);\n }\n warn('Timeout waiting for copilot to finish in directory');\n}\n\n/**\n * SAFETY: Check if a session already has a running copilot process.\n * If so, refuse to spawn another one to prevent corruption.\n */\nexport function assertSessionNotRunning(sid: string): void {\n const pid = findPidForSession(sid);\n if (pid) {\n fail(`Session ${sid.slice(0, 8)}… already has copilot running (PID ${pid}). Cannot resume — would corrupt the session.`);\n process.exit(1);\n }\n}\n\nexport async function waitForExit(pid: number, timeoutMs = 14_400_000): Promise<boolean> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n process.kill(pid, 0);\n await sleep(5000);\n } catch {\n return true; // process exited\n }\n }\n return false; // timeout\n}\n\nexport async function runCopilot(\n args: string[],\n options?: { cwd?: string },\n): Promise<CopilotResult> {\n // SAFETY: Wait for copilot in same directory only (parallel in different dirs is OK)\n const dir = options?.cwd ?? process.cwd();\n await waitForCopilotInDir(dir);\n\n return new Promise((resolve) => {\n const child = spawn('copilot', args, {\n cwd: options?.cwd,\n stdio: 'inherit',\n env: { ...process.env },\n });\n\n child.on('close', async (code) => {\n await sleep(3000); // let events flush\n const sid = getLatestSessionId();\n const premium = sid ? getSessionPremium(sid) : 0;\n resolve({\n exitCode: code ?? 1,\n sessionId: sid,\n premium,\n });\n });\n\n child.on('error', () => {\n resolve({ exitCode: 1, sessionId: null, premium: 0 });\n });\n });\n}\n\nexport function runCopilotResume(\n sid: string,\n steps: number,\n message?: string,\n cwd?: string,\n): Promise<CopilotResult> {\n // SAFETY: Refuse if session already running\n assertSessionNotRunning(sid);\n\n const args = [\n `--resume=${sid}`,\n '--autopilot',\n '--allow-all',\n '--max-autopilot-continues',\n String(steps),\n '--no-ask-user',\n ];\n if (message) args.push('-p', message);\n return runCopilot(args, { cwd });\n}\n\nexport function runCopilotTask(\n prompt: string,\n steps: number,\n cwd?: string,\n): Promise<CopilotResult> {\n return runCopilot([\n '-p', prompt,\n '--autopilot',\n '--allow-all',\n '--max-autopilot-continues', String(steps),\n '--no-ask-user',\n ], { cwd });\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms));\n}\n","import { appendFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { RED, GREEN, YELLOW, CYAN, DIM, RESET } from './colors.js';\n\nlet logFilePath: string | null = null;\n\nconst ANSI_RE =\n /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;\n\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '');\n}\n\nfunction writeToFile(msg: string): void {\n if (!logFilePath) return;\n try {\n appendFileSync(logFilePath, stripAnsi(msg) + '\\n');\n } catch { /* ignore file write errors */ }\n}\n\nexport function setLogFile(path: string): void {\n mkdirSync(dirname(path), { recursive: true });\n logFilePath = path;\n}\n\nexport function log(msg: string): void {\n console.log(msg);\n writeToFile(msg);\n}\n\nexport function warn(msg: string): void {\n const out = `${YELLOW}⚠ ${msg}${RESET}`;\n console.log(out);\n writeToFile(`⚠ ${msg}`);\n}\n\nexport function ok(msg: string): void {\n const out = `${GREEN}✔ ${msg}${RESET}`;\n console.log(out);\n writeToFile(`✔ ${msg}`);\n}\n\nexport function fail(msg: string): void {\n const out = `${RED}✖ ${msg}${RESET}`;\n console.error(out);\n writeToFile(`✖ ${msg}`);\n}\n\nexport function info(msg: string): void {\n const out = `${CYAN}ℹ ${msg}${RESET}`;\n console.log(out);\n writeToFile(`ℹ ${msg}`);\n}\n\nexport function dim(msg: string): void {\n const out = `${DIM}${msg}${RESET}`;\n console.log(out);\n writeToFile(msg);\n}\n\nexport function notify(message: string, title = 'copilot-agent'): void {\n try {\n if (process.platform === 'darwin') {\n execSync(\n `osascript -e 'display notification \"${message.replace(/\"/g, '\\\\\"')}\" with title \"${title.replace(/\"/g, '\\\\\"')}\"'`,\n { stdio: 'ignore' },\n );\n } else {\n try {\n execSync('which notify-send', { stdio: 'pipe' });\n execSync(\n `notify-send \"${title}\" \"${message.replace(/\"/g, '\\\\\"')}\"`,\n { stdio: 'ignore' },\n );\n } catch { /* notify-send not available */ }\n }\n } catch { /* notification not available */ }\n}\n","export const RED = '\\x1b[31m';\nexport const GREEN = '\\x1b[32m';\nexport const YELLOW = '\\x1b[33m';\nexport const BLUE = '\\x1b[34m';\nexport const CYAN = '\\x1b[36m';\nexport const DIM = '\\x1b[2m';\nexport const BOLD = '\\x1b[1m';\nexport const RESET = '\\x1b[0m';\n","import type { Command } from 'commander';\nimport {\n listSessions,\n hasTaskComplete,\n getLastEvent,\n getSessionPremium,\n} from '../lib/session.js';\nimport { findCopilotProcesses } from '../lib/process.js';\nimport { log } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, GREEN, YELLOW, RESET } from '../lib/colors.js';\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command('status')\n .description('Show copilot session status')\n .option('-l, --limit <n>', 'Number of sessions to show', '10')\n .option('-a, --active', 'Show only active (running) processes')\n .option('-i, --incomplete', 'Only show incomplete sessions')\n .action((opts) => {\n if (opts.active) {\n showActive();\n } else {\n showRecent(parseInt(opts.limit, 10), opts.incomplete ?? false);\n }\n });\n}\n\nfunction showActive(): void {\n const procs = findCopilotProcesses();\n if (procs.length === 0) {\n log(`${DIM}No active copilot processes.${RESET}`);\n return;\n }\n\n log(`\\n${BOLD}${'PID'.padEnd(8)} ${'Session'.padEnd(40)} Command${RESET}`);\n log('─'.repeat(108));\n\n for (const p of procs) {\n log(\n `${CYAN}${String(p.pid).padEnd(8)}${RESET} ${(p.sessionId ?? '—').padEnd(40)} ${truncate(p.command, 58)}`,\n );\n }\n log('');\n}\n\nfunction showRecent(limit: number, incompleteOnly: boolean): void {\n let sessions = listSessions(limit);\n if (incompleteOnly) {\n sessions = sessions.filter(s => !s.complete);\n }\n\n if (sessions.length === 0) {\n log(`${DIM}No sessions found.${RESET}`);\n return;\n }\n\n log(\n `\\n${BOLD}${'Status'.padEnd(10)} ${'Premium'.padEnd(10)} ${'Last Event'.padEnd(25)} ${'Summary'.padEnd(40)} ID${RESET}`,\n );\n log('─'.repeat(120));\n\n for (const s of sessions) {\n const status = s.complete\n ? `${GREEN}✔ done${RESET}`\n : `${YELLOW}⏸ stop${RESET}`;\n const premium = String(s.premiumRequests);\n const summary = truncate(s.summary || '—', 38);\n\n log(\n `${status.padEnd(10 + 9)} ${premium.padEnd(10)} ${s.lastEvent.padEnd(25)} ${summary.padEnd(40)} ${DIM}${s.id}${RESET}`,\n );\n }\n log(`\\n${DIM}Total: ${sessions.length} session(s)${RESET}`);\n}\n\nfunction truncate(s: string, max: number): string {\n if (s.length <= max) return s;\n return s.substring(0, max - 1) + '…';\n}\n","import type { Command } from 'commander';\nimport {\n validateSession,\n hasTaskComplete,\n getSessionSummary,\n getLastEvent,\n findLatestIncomplete,\n getSessionCwd,\n} from '../lib/session.js';\nimport {\n findPidForSession,\n waitForExit,\n runCopilotResume,\n assertCopilot,\n} from '../lib/process.js';\nimport { log, ok, warn, fail, info, notify } from '../lib/logger.js';\nimport { CYAN, RESET } from '../lib/colors.js';\n\nexport function registerWatchCommand(program: Command): void {\n program\n .command('watch [session-id]')\n .description('Watch a session and auto-resume when it stops')\n .option('-s, --steps <n>', 'Max autopilot continues per resume', '30')\n .option('-r, --max-resumes <n>', 'Max number of resumes', '10')\n .option('-c, --cooldown <n>', 'Seconds between resumes', '10')\n .option('-m, --message <msg>', 'Message to send on resume')\n .action(async (sid: string | undefined, opts) => {\n try {\n await watchCommand(sid, {\n steps: parseInt(opts.steps, 10),\n maxResumes: parseInt(opts.maxResumes, 10),\n cooldown: parseInt(opts.cooldown, 10),\n message: opts.message,\n });\n } catch (err) {\n fail(`Watch error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface WatchOptions {\n steps: number;\n maxResumes: number;\n cooldown: number;\n message?: string;\n}\n\nasync function watchCommand(sid: string | undefined, opts: WatchOptions): Promise<void> {\n assertCopilot();\n\n if (!sid) {\n sid = findLatestIncomplete() ?? undefined;\n if (!sid) {\n fail('No incomplete session found.');\n process.exit(1);\n }\n info(`Auto-detected incomplete session: ${CYAN}${sid}${RESET}`);\n }\n\n if (!validateSession(sid)) {\n fail(`Invalid session: ${sid}`);\n process.exit(1);\n }\n\n if (hasTaskComplete(sid)) {\n ok(`Session ${sid} already completed.`);\n return;\n }\n\n let resumes = 0;\n\n while (resumes < opts.maxResumes) {\n const pid = findPidForSession(sid);\n\n if (pid) {\n info(`Watching PID ${pid} for session ${CYAN}${sid.slice(0, 8)}${RESET}…`);\n const exited = await waitForExit(pid);\n\n if (!exited) {\n warn('Timeout waiting for process exit.');\n break;\n }\n }\n\n // Small delay for events to flush\n await sleep(3000);\n\n if (hasTaskComplete(sid)) {\n ok(`Task complete! Summary: ${getSessionSummary(sid) || 'none'}`);\n notify('Task completed!', `Session ${sid.slice(0, 8)}`);\n return;\n }\n\n // Interrupted — resume\n resumes++;\n log(`Session interrupted (${getLastEvent(sid)}). Resume ${resumes}/${opts.maxResumes}…`);\n\n if (opts.cooldown > 0 && resumes > 1) {\n info(`Cooldown ${opts.cooldown}s...`);\n await sleep(opts.cooldown * 1000);\n }\n\n const cwd = getSessionCwd(sid) || undefined;\n const result = await runCopilotResume(\n sid,\n opts.steps,\n opts.message ?? 'Continue remaining work. Pick up where you left off and complete the task.',\n cwd,\n );\n\n if (result.sessionId && result.sessionId !== sid) {\n info(`New session created: ${CYAN}${result.sessionId}${RESET}`);\n sid = result.sessionId;\n }\n }\n\n warn(`Max resumes (${opts.maxResumes}) reached.`);\n notify('Max resumes reached', `Session ${sid.slice(0, 8)}`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms));\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, basename, resolve } from 'node:path';\nimport { execSync } from 'node:child_process';\n\nexport type ProjectType =\n | 'kmp' | 'kotlin' | 'java'\n | 'node' | 'typescript' | 'react' | 'next'\n | 'python' | 'rust' | 'swift' | 'go' | 'flutter'\n | 'unknown';\n\nexport function detectProjectType(dir: string): ProjectType {\n const exists = (f: string) => existsSync(join(dir, f));\n\n if (exists('build.gradle.kts') || exists('build.gradle')) {\n if (exists('composeApp') || exists('gradle.properties')) {\n try {\n const gradle = readFileSync(join(dir, 'build.gradle.kts'), 'utf-8');\n if (gradle.includes('multiplatform') || gradle.includes('KotlinMultiplatform')) return 'kmp';\n } catch { /* ignore */ }\n }\n if (exists('pom.xml')) return 'java';\n return 'kotlin';\n }\n if (exists('pubspec.yaml')) return 'flutter';\n if (exists('Package.swift')) return 'swift';\n try {\n const entries = readdirSync(dir);\n if (entries.some(e => e.endsWith('.xcodeproj'))) return 'swift';\n } catch { /* ignore */ }\n if (exists('Cargo.toml')) return 'rust';\n if (exists('go.mod')) return 'go';\n if (exists('pyproject.toml') || exists('setup.py') || exists('requirements.txt')) return 'python';\n if (exists('package.json')) {\n try {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (allDeps['next']) return 'next';\n if (allDeps['react']) return 'react';\n if (allDeps['typescript'] || exists('tsconfig.json')) return 'typescript';\n } catch { /* ignore */ }\n return 'node';\n }\n if (exists('pom.xml')) return 'java';\n return 'unknown';\n}\n\nexport function detectProjectName(dir: string): string {\n try {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n if (pkg.name) return pkg.name;\n } catch { /* ignore */ }\n return basename(resolve(dir));\n}\n\nexport function detectMainBranch(dir: string): string {\n try {\n const ref = execSync('git symbolic-ref refs/remotes/origin/HEAD', {\n cwd: dir,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n return ref.split('/').pop() ?? 'main';\n } catch { /* ignore */ }\n\n try {\n const branch = execSync('git branch --show-current', {\n cwd: dir,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n if (branch) return branch;\n } catch { /* ignore */ }\n\n return 'main';\n}\n","import type { ProjectType } from \"./detect.js\";\n\ninterface TaskPrompt {\n title: string;\n prompt: string;\n priority: number;\n}\n\nconst COMMON_TASKS: TaskPrompt[] = [\n {\n title: \"Fix TODOs\",\n prompt:\n \"Scan for TODO, FIXME, HACK comments. Fix the most impactful ones. Run tests to verify.\",\n priority: 1,\n },\n {\n title: \"Update dependencies\",\n prompt:\n \"Check for outdated dependencies. Update patch/minor versions that are safe. Run tests after updating.\",\n priority: 2,\n },\n {\n title: \"Improve test coverage\",\n prompt:\n \"Find untested public functions. Write tests for the most critical ones. Target 80%+ coverage.\",\n priority: 3,\n },\n {\n title: \"Fix lint warnings\",\n prompt:\n \"Run the project linter. Fix all warnings without changing behavior. Run tests.\",\n priority: 4,\n },\n {\n title: \"Improve documentation\",\n prompt:\n \"Review README and code docs. Add missing JSDoc/KDoc for public APIs. Update outdated sections.\",\n priority: 5,\n },\n {\n title: \"Security audit\",\n prompt:\n \"Check for common security issues: hardcoded secrets, SQL injection, XSS, insecure defaults. Fix any found.\",\n priority: 6,\n },\n];\n\nconst TYPE_TASKS: Partial<Record<ProjectType, TaskPrompt[]>> = {\n kmp: [\n {\n title: \"KMP: Optimize Compose\",\n prompt:\n \"Review Compose UI code for recomposition issues. Add @Stable/@Immutable where needed. Check remember usage.\",\n priority: 2,\n },\n {\n title: \"KMP: Check expect/actual\",\n prompt:\n \"Review expect/actual declarations. Ensure all platforms have proper implementations. Check for missing iOS/Desktop actuals.\",\n priority: 3,\n },\n {\n title: \"KMP: Room migrations\",\n prompt:\n \"Check Room database schema. Ensure migrations are defined for schema changes. Add missing migration tests.\",\n priority: 4,\n },\n ],\n typescript: [\n {\n title: \"TS: Strict type safety\",\n prompt:\n \"Find `any` types and loose assertions. Replace with proper types. Enable stricter tsconfig options if safe.\",\n priority: 2,\n },\n ],\n react: [\n {\n title: \"React: Performance\",\n prompt:\n \"Find unnecessary re-renders. Add React.memo, useMemo, useCallback where beneficial. Check bundle size.\",\n priority: 2,\n },\n ],\n python: [\n {\n title: \"Python: Type hints\",\n prompt:\n \"Add type hints to public functions. Run mypy to check type safety. Fix any type errors.\",\n priority: 2,\n },\n ],\n node: [\n {\n title: \"Node: Error handling\",\n prompt:\n \"Review async error handling. Add try/catch for unhandled promises. Check for missing error middleware.\",\n priority: 2,\n },\n ],\n};\n\nexport function getTasksForProject(type: ProjectType): TaskPrompt[] {\n const specific = TYPE_TASKS[type] ?? [];\n return [...specific, ...COMMON_TASKS].sort(\n (a, b) => a.priority - b.priority,\n );\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nconst LOCK_BASE = join(homedir(), '.copilot', 'locks');\n\nfunction lockDir(name: string): string {\n return join(LOCK_BASE, `${name}.lock`);\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function acquireLock(name: string, timeoutMs = 30_000): boolean {\n mkdirSync(LOCK_BASE, { recursive: true });\n const dir = lockDir(name);\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n try {\n mkdirSync(dir);\n // Lock acquired — write metadata\n writeFileSync(join(dir, 'pid'), String(process.pid));\n writeFileSync(join(dir, 'acquired'), new Date().toISOString());\n return true;\n } catch {\n // Lock dir exists — check if holder is still alive\n try {\n const holderPid = parseInt(readFileSync(join(dir, 'pid'), 'utf-8').trim(), 10);\n if (!isPidAlive(holderPid)) {\n // Stale lock — break it\n rmSync(dir, { recursive: true, force: true });\n continue;\n }\n } catch {\n // Can't read pid file — try breaking\n rmSync(dir, { recursive: true, force: true });\n continue;\n }\n // Holder is alive — wait and retry\n const waitMs = Math.min(500, deadline - Date.now());\n if (waitMs > 0) {\n const start = Date.now();\n while (Date.now() - start < waitMs) { /* spin wait */ }\n }\n }\n }\n return false;\n}\n\nexport function releaseLock(name: string): void {\n const dir = lockDir(name);\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch { /* already released */ }\n}\n\nexport async function withLock<T>(name: string, fn: () => T | Promise<T>): Promise<T> {\n if (!acquireLock(name)) {\n throw new Error(`Failed to acquire lock: ${name}`);\n }\n try {\n return await fn();\n } finally {\n releaseLock(name);\n }\n}\n","import { existsSync, rmSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { execSync } from 'node:child_process';\n\nfunction gitExec(dir: string, cmd: string): string | null {\n try {\n return execSync(cmd, {\n cwd: dir,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch {\n return null;\n }\n}\n\nexport function isGitRepo(dir: string): boolean {\n return existsSync(join(dir, '.git'));\n}\n\nexport function gitCurrentBranch(dir: string): string | null {\n return gitExec(dir, 'git branch --show-current');\n}\n\nexport function gitStash(dir: string): boolean {\n return gitExec(dir, 'git stash -q') !== null;\n}\n\nexport function gitStashPop(dir: string): boolean {\n return gitExec(dir, 'git stash pop -q') !== null;\n}\n\nexport function gitCheckout(dir: string, branch: string): boolean {\n return gitExec(dir, `git checkout ${branch} -q`) !== null;\n}\n\nexport function gitCreateBranch(dir: string, branch: string): boolean {\n return gitExec(dir, `git checkout -b ${branch}`) !== null;\n}\n\nexport function gitCountCommits(dir: string, from: string, to: string): number {\n const result = gitExec(dir, `git log ${from}..${to} --oneline`);\n if (!result) return 0;\n return result.split('\\n').filter(l => l.trim()).length;\n}\n\nexport function gitStatus(dir: string): string {\n return gitExec(dir, 'git status --porcelain') ?? '';\n}\n\nexport function gitRoot(dir: string): string | null {\n return gitExec(dir, 'git rev-parse --show-toplevel');\n}\n\n// ── Worktree support ──\n\nexport function listWorktrees(dir: string): { path: string; branch: string; bare: boolean }[] {\n const raw = gitExec(dir, 'git worktree list --porcelain');\n if (!raw) return [];\n const trees: { path: string; branch: string; bare: boolean }[] = [];\n let current: { path: string; branch: string; bare: boolean } = { path: '', branch: '', bare: false };\n for (const line of raw.split('\\n')) {\n if (line.startsWith('worktree ')) {\n if (current.path) trees.push(current);\n current = { path: line.slice(9), branch: '', bare: false };\n } else if (line.startsWith('branch ')) {\n current.branch = line.slice(7).replace('refs/heads/', '');\n } else if (line === 'bare') {\n current.bare = true;\n }\n }\n if (current.path) trees.push(current);\n return trees;\n}\n\n/**\n * Create a git worktree for parallel copilot work.\n * Returns the worktree path or null on failure.\n */\nexport function createWorktree(repoDir: string, branch: string): string | null {\n const safeBranch = branch.replace(/[^a-zA-Z0-9._/-]/g, '-');\n const worktreePath = resolve(repoDir, '..', `${resolve(repoDir).split('/').pop()}-wt-${safeBranch}`);\n\n if (existsSync(worktreePath)) {\n return worktreePath; // already exists\n }\n\n // Create branch if it doesn't exist, then add worktree\n const branchExists = gitExec(repoDir, `git rev-parse --verify ${safeBranch}`) !== null;\n const cmd = branchExists\n ? `git worktree add \"${worktreePath}\" ${safeBranch}`\n : `git worktree add -b ${safeBranch} \"${worktreePath}\"`;\n\n if (gitExec(repoDir, cmd) !== null) {\n return worktreePath;\n }\n return null;\n}\n\n/**\n * Remove a worktree (prune).\n */\nexport function removeWorktree(repoDir: string, worktreePath: string): boolean {\n const result = gitExec(repoDir, `git worktree remove \"${worktreePath}\" --force`);\n return result !== null;\n}\n\n/**\n * Clean up all copilot-agent worktrees.\n */\nexport function cleanupWorktrees(repoDir: string): number {\n const trees = listWorktrees(repoDir);\n let cleaned = 0;\n for (const t of trees) {\n if (t.path.includes('-wt-')) {\n if (removeWorktree(repoDir, t.path)) cleaned++;\n }\n }\n gitExec(repoDir, 'git worktree prune');\n return cleaned;\n}\n","import type { Command } from 'commander';\nimport { detectProjectType, detectProjectName, detectMainBranch } from '../lib/detect.js';\nimport { getTasksForProject } from '../lib/tasks.js';\nimport { runCopilotTask, assertCopilot } from '../lib/process.js';\nimport { withLock } from '../lib/lock.js';\nimport { isGitRepo, gitCurrentBranch, gitStatus, gitStash, gitCheckout, gitCreateBranch, gitCountCommits } from '../lib/git.js';\nimport { log, ok, warn, fail, info, notify } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, GREEN, RESET, YELLOW } from '../lib/colors.js';\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run [dir]')\n .description('Discover and fix issues in a project')\n .option('-s, --steps <n>', 'Max autopilot continues per task', '30')\n .option('-t, --max-tasks <n>', 'Max number of tasks to run', '5')\n .option('-p, --max-premium <n>', 'Max total premium requests', '50')\n .option('--dry-run', 'Show tasks without executing')\n .action(async (dir: string | undefined, opts) => {\n try {\n await runCommand(dir ?? process.cwd(), {\n steps: parseInt(opts.steps, 10),\n maxTasks: parseInt(opts.maxTasks, 10),\n maxPremium: parseInt(opts.maxPremium, 10),\n dryRun: opts.dryRun ?? false,\n });\n } catch (err) {\n fail(`Run error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface RunOptions {\n steps: number;\n maxTasks: number;\n maxPremium: number;\n dryRun: boolean;\n}\n\nasync function runCommand(dir: string, opts: RunOptions): Promise<void> {\n assertCopilot();\n\n const projectType = detectProjectType(dir);\n const name = detectProjectName(dir);\n const mainBranch = isGitRepo(dir) ? detectMainBranch(dir) : null;\n\n info(`Project: ${CYAN}${name}${RESET} (${projectType})`);\n if (mainBranch) info(`Main branch: ${mainBranch}`);\n\n const tasks = getTasksForProject(projectType).slice(0, opts.maxTasks);\n\n if (tasks.length === 0) {\n warn('No tasks found for this project type.');\n return;\n }\n\n log(`Found ${tasks.length} tasks:`);\n for (const t of tasks) {\n log(` ${DIM}•${RESET} ${t.title}`);\n }\n\n if (opts.dryRun) {\n log(`${DIM}(dry-run — not executing)${RESET}`);\n return;\n }\n\n const originalBranch = isGitRepo(dir) ? gitCurrentBranch(dir) : null;\n let completed = 0;\n let premiumTotal = 0;\n\n for (const task of tasks) {\n if (premiumTotal >= opts.maxPremium) {\n warn(`Premium request limit reached (${premiumTotal}/${opts.maxPremium}).`);\n break;\n }\n\n log(`\\n${'═'.repeat(60)}`);\n log(`${BOLD}${CYAN}Task: ${task.title}${RESET}`);\n log(`${'═'.repeat(60)}`);\n\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 6);\n const branchName = `agent/fix-${completed + 1}-${timestamp}-${random}`;\n\n if (mainBranch && isGitRepo(dir)) {\n if (gitStatus(dir)) gitStash(dir);\n gitCheckout(dir, mainBranch);\n if (!gitCreateBranch(dir, branchName)) {\n warn(`Could not create branch ${branchName}, continuing on current.`);\n }\n }\n\n info(`Running: ${task.title}…`);\n\n const result = await withLock('copilot-run', () =>\n runCopilotTask(task.prompt, opts.steps, dir),\n );\n\n const commits = mainBranch ? gitCountCommits(dir, mainBranch, 'HEAD') : 0;\n premiumTotal += result.premium;\n completed++;\n ok(`${task.title} — ${commits} commit(s), ${result.premium} premium`);\n\n if (originalBranch && isGitRepo(dir)) {\n gitCheckout(dir, mainBranch ?? originalBranch);\n }\n }\n\n log(`\\n${BOLD}═══ Run Summary ═══${RESET}`);\n log(`Completed ${completed}/${tasks.length} tasks. Total premium: ${premiumTotal}`);\n notify(`Completed ${completed} tasks`, name);\n}\n","import type { Command } from 'commander';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { detectProjectType, detectProjectName, detectMainBranch } from '../lib/detect.js';\nimport { getTasksForProject } from '../lib/tasks.js';\nimport { runCopilotTask, assertCopilot, findPidForSession, findCopilotProcesses, waitForExit, waitForCopilotInDir, runCopilotResume } from '../lib/process.js';\nimport { withLock } from '../lib/lock.js';\nimport { isGitRepo, gitCurrentBranch, gitStash, gitCheckout, gitCreateBranch, gitCountCommits, createWorktree, removeWorktree } from '../lib/git.js';\nimport { findLatestIncomplete, validateSession, hasTaskComplete, getSessionCwd } from '../lib/session.js';\nimport { log, ok, warn, fail, info, setLogFile, notify } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, RESET } from '../lib/colors.js';\n\nexport function registerOvernightCommand(program: Command): void {\n program\n .command('overnight [dir]')\n .description('Run tasks continuously until a deadline')\n .option('-u, --until <HH>', 'Stop at this hour (24h format)', '07')\n .option('-s, --steps <n>', 'Max autopilot continues per task', '50')\n .option('-c, --cooldown <n>', 'Seconds between tasks', '15')\n .option('-p, --max-premium <n>', 'Max premium requests budget', '300')\n .option('--dry-run', 'Show plan without executing')\n .action(async (dir: string | undefined, opts) => {\n try {\n await overnightCommand(dir ?? process.cwd(), {\n until: parseInt(opts.until, 10),\n steps: parseInt(opts.steps, 10),\n cooldown: parseInt(opts.cooldown, 10),\n maxPremium: parseInt(opts.maxPremium, 10),\n dryRun: opts.dryRun ?? false,\n });\n } catch (err) {\n fail(`Overnight error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface OvernightOptions {\n until: number;\n steps: number;\n cooldown: number;\n maxPremium: number;\n dryRun: boolean;\n}\n\nfunction isPastDeadline(untilHour: number): boolean {\n const hour = new Date().getHours();\n return hour >= untilHour && hour < 20;\n}\n\nasync function overnightCommand(dir: string, opts: OvernightOptions): Promise<void> {\n assertCopilot();\n\n const ts = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);\n const logPath = join(homedir(), '.copilot', 'auto-resume-logs', `overnight-${ts}.log`);\n setLogFile(logPath);\n\n const name = detectProjectName(dir);\n const projectType = detectProjectType(dir);\n const mainBranch = isGitRepo(dir) ? detectMainBranch(dir) : null;\n\n info(`Overnight runner for ${CYAN}${name}${RESET} (${projectType})`);\n info(`Deadline: ${String(opts.until).padStart(2, '0')}:00`);\n info(`Max premium: ${opts.maxPremium}, Steps: ${opts.steps}`);\n info(`Log: ${logPath}`);\n\n const tasks = getTasksForProject(projectType);\n\n if (opts.dryRun) {\n log(`\\nWould run ${tasks.length} tasks:`);\n for (const t of tasks) log(` ${DIM}•${RESET} ${t.title}`);\n return;\n }\n\n // Phase 1: Resume existing incomplete session\n const existingSession = findLatestIncomplete();\n if (existingSession && validateSession(existingSession)) {\n info(`Found incomplete session: ${existingSession}`);\n const pid = findPidForSession(existingSession);\n if (pid) {\n info(`Waiting for running copilot (PID ${pid})...`);\n await waitForExit(pid);\n }\n\n if (!hasTaskComplete(existingSession) && !isPastDeadline(opts.until)) {\n info('Resuming incomplete session...');\n const cwd = getSessionCwd(existingSession) || dir;\n await runCopilotResume(\n existingSession,\n opts.steps,\n 'Continue remaining work. Complete the task.',\n cwd,\n );\n }\n }\n\n // Phase 2: Loop tasks until deadline\n const originalBranch = isGitRepo(dir) ? gitCurrentBranch(dir) : null;\n let taskIdx = 0;\n let totalPremium = 0;\n let totalCommits = 0;\n\n while (!isPastDeadline(opts.until) && taskIdx < tasks.length) {\n if (totalPremium >= opts.maxPremium) {\n warn(`Premium budget exhausted: ${totalPremium}/${opts.maxPremium}`);\n break;\n }\n\n const task = tasks[taskIdx % tasks.length];\n taskIdx++;\n\n log(`\\n${'═'.repeat(60)}`);\n log(`${BOLD}${CYAN}[${new Date().toLocaleTimeString()}] Task ${taskIdx}: ${task.title}${RESET}`);\n log(`${DIM}Premium: ${totalPremium}/${opts.maxPremium}${RESET}`);\n log(`${'═'.repeat(60)}`);\n\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 6);\n const branchName = `agent/overnight-${taskIdx}-${timestamp}-${random}`;\n\n if (mainBranch && isGitRepo(dir)) {\n gitStash(dir);\n gitCheckout(dir, mainBranch);\n gitCreateBranch(dir, branchName);\n }\n\n info(`Running: ${task.title}…`);\n\n try {\n const result = await withLock('copilot-overnight', () =>\n runCopilotTask(task.prompt, opts.steps, dir),\n );\n\n const commits = mainBranch ? gitCountCommits(dir, mainBranch, 'HEAD') : 0;\n totalPremium += result.premium;\n totalCommits += commits;\n\n if (commits > 0) {\n ok(`${commits} commit(s) on ${branchName}`);\n } else {\n log(`${DIM}No commits on ${branchName}${RESET}`);\n }\n } catch (err) {\n fail(`Task failed: ${err}`);\n }\n\n if (mainBranch && isGitRepo(dir)) {\n gitCheckout(dir, mainBranch);\n }\n\n if (!isPastDeadline(opts.until)) {\n info(`Cooldown ${opts.cooldown}s…`);\n await sleep(opts.cooldown * 1000);\n }\n }\n\n if (originalBranch && isGitRepo(dir)) {\n gitCheckout(dir, originalBranch);\n }\n\n const summary = `Overnight done — ${taskIdx} tasks, ${totalCommits} commits, ${totalPremium} premium.`;\n ok(summary);\n notify(summary, name);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms));\n}\n","import type { Command } from 'commander';\nimport { existsSync, copyFileSync, mkdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { homedir } from 'node:os';\nimport { detectProjectType, detectProjectName } from '../lib/detect.js';\nimport { runCopilotTask, assertCopilot } from '../lib/process.js';\nimport { withLock } from '../lib/lock.js';\nimport { log, ok, warn, fail, info, notify } from '../lib/logger.js';\nimport { CYAN, RESET } from '../lib/colors.js';\n\nexport function registerResearchCommand(program: Command): void {\n program\n .command('research [project]')\n .description('Research improvements or a specific topic')\n .option('-s, --steps <n>', 'Max autopilot continues', '50')\n .action(async (project: string | undefined, opts) => {\n try {\n await researchCommand(project ?? process.cwd(), {\n steps: parseInt(opts.steps, 10),\n });\n } catch (err) {\n fail(`Research error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface ResearchOptions {\n steps: number;\n}\n\nfunction buildResearchPrompt(projectType: string, projectName: string): string {\n return `You are a senior software architect. Analyze this ${projectType} project \"${projectName}\" thoroughly.\n\nResearch and produce a file called RESEARCH-PROPOSALS.md with:\n\n1. **Architecture Assessment** — Current architecture, patterns used, strengths and weaknesses\n2. **Code Quality Report** — Common issues, anti-patterns, technical debt areas\n3. **Security Audit** — Potential vulnerabilities, dependency risks, configuration issues\n4. **Performance Analysis** — Bottlenecks, optimization opportunities, resource usage\n5. **Testing Gap Analysis** — Untested areas, test quality, coverage recommendations\n6. **Improvement Proposals** — Prioritized list of actionable improvements with effort estimates\n\nFor each proposal, include:\n- Priority (P0/P1/P2)\n- Estimated effort (hours)\n- Impact description\n- Suggested implementation approach\n\nWrite RESEARCH-PROPOSALS.md in the project root.`;\n}\n\nasync function researchCommand(dir: string, opts: ResearchOptions): Promise<void> {\n assertCopilot();\n\n const projectDir = resolve(dir);\n const projectType = detectProjectType(projectDir);\n const projectName = detectProjectName(projectDir);\n\n info(`Researching: ${CYAN}${projectName}${RESET} (${projectType})`);\n\n const prompt = buildResearchPrompt(projectType, projectName);\n\n const result = await withLock('copilot-research', () =>\n runCopilotTask(prompt, opts.steps, projectDir),\n );\n\n log(`Copilot exited with code ${result.exitCode}`);\n\n // Check for output file\n const proposalsFile = join(projectDir, 'RESEARCH-PROPOSALS.md');\n if (existsSync(proposalsFile)) {\n ok('RESEARCH-PROPOSALS.md generated.');\n\n // Backup to ~/.copilot/research-reports/\n const backupDir = join(homedir(), '.copilot', 'research-reports');\n mkdirSync(backupDir, { recursive: true });\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const backupFile = join(backupDir, `${projectName}-${timestamp}.md`);\n copyFileSync(proposalsFile, backupFile);\n ok(`Backup saved: ${backupFile}`);\n } else {\n warn('RESEARCH-PROPOSALS.md was not generated. Check copilot output.');\n }\n\n notify('Research complete', projectName);\n}\n"],"mappings":";AAAA,SAAS,eAAe;;;ACAxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,MAAM,eAAe;AAC9B,SAAS,eAAe;AAaxB,IAAM,cAAc,KAAK,QAAQ,GAAG,YAAY,eAAe;AAMxD,SAAS,gBAAgB,KAAsB;AACpD,QAAM,SAAS,KAAK,aAAa,KAAK,cAAc;AACpD,MAAI;AACF,WAAO,WAAW,MAAM,KAAK,SAAS,MAAM,EAAE,OAAO;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,aAAa,QAAQ,IAAe;A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AAqB,WAAW;AACzC;;;Ab/EA,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,eAAe,EACpB,QAAQ,OAAO,EACf,YAAY,wFAAmF;AAElG,sBAAsB,OAAO;AAC7B,qBAAqB,OAAO;AAC5B,mBAAmB,OAAO;AAC1B,yBAAyB,OAAO;AAChC,wBAAwB,OAAO;AAE/B,QAAQ,MAAM;","names":["execSync","resolve","execSync","resolve","program","program","sleep","existsSync","readFileSync","readdirSync","join","resolve","execSync","mkdirSync","readFileSync","join","homedir","existsSync","join","resolve","execSync","program","join","homedir","program","join","homedir","sleep","existsSync","mkdirSync","join","resolve","homedir","program","resolve","join","existsSync","homedir","mkdirSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/session.ts","../src/lib/process.ts","../src/lib/logger.ts","../src/lib/colors.ts","../src/commands/status.ts","../src/commands/watch.ts","../src/lib/detect.ts","../src/lib/tasks.ts","../src/lib/lock.ts","../src/lib/git.ts","../src/commands/run.ts","../src/commands/overnight.ts","../src/commands/research.ts","../src/commands/report.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { registerStatusCommand } from './commands/status.js';\nimport { registerWatchCommand } from './commands/watch.js';\nimport { registerRunCommand } from './commands/run.js';\nimport { registerOvernightCommand } from './commands/overnight.js';\nimport { registerResearchCommand } from './commands/research.js';\nimport { registerReportCommand } from './commands/report.js';\n\nconst program = new Command();\n\nprogram\n .name('copilot-agent')\n .version('0.6.0')\n .description('Autonomous GitHub Copilot CLI agent — auto-resume, task discovery, overnight runs');\n\nregisterStatusCommand(program);\nregisterWatchCommand(program);\nregisterRunCommand(program);\nregisterOvernightCommand(program);\nregisterResearchCommand(program);\nregisterReportCommand(program);\n\nprogram.parse();\n","import {\n existsSync,\n readdirSync,\n readFileSync,\n statSync,\n} from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport interface Session {\n id: string;\n dir: string;\n mtime: number;\n lastEvent: string;\n premiumRequests: number;\n summary: string;\n cwd: string;\n complete: boolean;\n}\n\nexport interface SessionReport {\n id: string;\n cwd: string;\n summary: string;\n startTime: string;\n endTime: string;\n durationMs: number;\n complete: boolean;\n userMessages: number;\n assistantTurns: number;\n outputTokens: number;\n premiumRequests: number;\n toolUsage: Record<string, number>;\n gitCommits: string[];\n filesCreated: string[];\n filesEdited: string[];\n errors: string[];\n taskCompletions: string[];\n}\n\nconst SESSION_DIR = join(homedir(), '.copilot', 'session-state');\n\nexport function getSessionDir(): string {\n return SESSION_DIR;\n}\n\nexport function validateSession(sid: string): boolean {\n const events = join(SESSION_DIR, sid, 'events.jsonl');\n try {\n return existsSync(events) && statSync(events).size > 0;\n } catch {\n return false;\n }\n}\n\nexport function listSessions(limit = 20): Session[] {\n if (!existsSync(SESSION_DIR)) return [];\n\n const entries = readdirSync(SESSION_DIR, { withFileTypes: true })\n .filter(d => d.isDirectory());\n\n const dirs: { id: string; dir: string; mtime: number }[] = [];\n for (const entry of entries) {\n const dirPath = join(SESSION_DIR, entry.name);\n if (!existsSync(join(dirPath, 'events.jsonl'))) continue;\n try {\n const stat = statSync(dirPath);\n dirs.push({ id: entry.name, dir: dirPath, mtime: stat.mtimeMs });\n } catch { /* skip */ }\n }\n\n dirs.sort((a, b) => b.mtime - a.mtime);\n\n return dirs.slice(0, limit).map(s => ({\n id: s.id,\n dir: s.dir,\n mtime: s.mtime,\n lastEvent: getLastEvent(s.id),\n premiumRequests: getSessionPremium(s.id),\n summary: getSessionSummary(s.id),\n cwd: getSessionCwd(s.id),\n complete: hasTaskComplete(s.id),\n }));\n}\n\nexport function getLatestSessionId(): string | null {\n if (!existsSync(SESSION_DIR)) return null;\n\n const entries = readdirSync(SESSION_DIR, { withFileTypes: true })\n .filter(d => d.isDirectory());\n\n let latest: { id: string; mtime: number } | null = null;\n for (const entry of entries) {\n try {\n const stat = statSync(join(SESSION_DIR, entry.name));\n if (!latest || stat.mtimeMs > latest.mtime) {\n latest = { id: entry.name, mtime: stat.mtimeMs };\n }\n } catch { /* skip */ }\n }\n return latest?.id ?? null;\n}\n\nexport function hasTaskComplete(sid: string): boolean {\n if (!validateSession(sid)) return false;\n try {\n const content = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8');\n return content.includes('\"session.task_complete\"');\n } catch {\n return false;\n }\n}\n\nexport function getLastEvent(sid: string): string {\n if (!validateSession(sid)) return 'invalid';\n try {\n const lines = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8')\n .trimEnd()\n .split('\\n');\n const last = JSON.parse(lines[lines.length - 1]);\n return last.type ?? 'unknown';\n } catch {\n return 'corrupted';\n }\n}\n\nexport function getSessionPremium(sid: string): number {\n if (!validateSession(sid)) return 0;\n try {\n const content = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8');\n const lines = content.trimEnd().split('\\n');\n for (let i = lines.length - 1; i >= 0; i--) {\n try {\n const event = JSON.parse(lines[i]);\n if (event.type === 'session.shutdown' && event.data?.totalPremiumRequests != null) {\n return event.data.totalPremiumRequests;\n }\n } catch { /* skip malformed line */ }\n }\n return 0;\n } catch {\n return 0;\n }\n}\n\nfunction parseSimpleYaml(content: string): Record<string, string> {\n const result: Record<string, string> = {};\n for (const line of content.split('\\n')) {\n const idx = line.indexOf(': ');\n if (idx === -1) continue;\n const key = line.substring(0, idx).trim();\n const value = line.substring(idx + 2).trim();\n if (key) result[key] = value;\n }\n return result;\n}\n\nfunction readWorkspace(sid: string): Record<string, string> {\n const wsPath = join(SESSION_DIR, sid, 'workspace.yaml');\n if (!existsSync(wsPath)) return {};\n try {\n return parseSimpleYaml(readFileSync(wsPath, 'utf-8'));\n } catch {\n return {};\n }\n}\n\nexport function getSessionSummary(sid: string): string {\n return readWorkspace(sid).summary ?? '';\n}\n\nexport function getSessionCwd(sid: string): string {\n return readWorkspace(sid).cwd ?? '';\n}\n\nexport function findSessionForProject(projectPath: string): string | null {\n const resolved = resolve(projectPath);\n const sessions = listSessions(50);\n for (const s of sessions) {\n if (s.cwd && resolve(s.cwd) === resolved) return s.id;\n }\n return null;\n}\n\nexport function findLatestIncomplete(): string | null {\n const sessions = listSessions(50);\n for (const s of sessions) {\n if (!s.complete) return s.id;\n }\n return null;\n}\n\nexport function getSessionReport(sid: string): SessionReport | null {\n if (!validateSession(sid)) return null;\n\n const ws = readWorkspace(sid);\n let lines: string[];\n try {\n lines = readFileSync(join(SESSION_DIR, sid, 'events.jsonl'), 'utf-8')\n .trimEnd()\n .split('\\n');\n } catch {\n return null;\n }\n\n const report: SessionReport = {\n id: sid,\n cwd: ws.cwd ?? '',\n summary: ws.summary ?? '',\n startTime: '',\n endTime: '',\n durationMs: 0,\n complete: false,\n userMessages: 0,\n assistantTurns: 0,\n outputTokens: 0,\n premiumRequests: 0,\n toolUsage: {},\n gitCommits: [],\n filesCreated: [],\n filesEdited: [],\n errors: [],\n taskCompletions: [],\n };\n\n for (const line of lines) {\n let event: Record<string, unknown>;\n try {\n event = JSON.parse(line);\n } catch {\n continue;\n }\n\n const type = event.type as string;\n const ts = event.timestamp as string | undefined;\n const data = (event.data ?? {}) as Record<string, unknown>;\n\n if (ts && !report.startTime) report.startTime = ts;\n if (ts) report.endTime = ts;\n\n switch (type) {\n case 'user.message':\n report.userMessages++;\n break;\n\n case 'assistant.message':\n report.assistantTurns++;\n report.outputTokens += (data.outputTokens as number) ?? 0;\n break;\n\n case 'tool.execution_start': {\n const toolName = data.toolName as string;\n if (toolName) {\n report.toolUsage[toolName] = (report.toolUsage[toolName] ?? 0) + 1;\n }\n // Track git commits\n if (toolName === 'bash') {\n const args = data.arguments as Record<string, string> | undefined;\n const cmd = args?.command ?? '';\n if (cmd.includes('git') && cmd.includes('commit') && cmd.includes('-m')) {\n const msgMatch = cmd.match(/-m\\s+\"([^\"]{1,120})/);\n if (msgMatch) report.gitCommits.push(msgMatch[1]);\n }\n }\n // Track file creates/edits\n if (toolName === 'create') {\n const args = data.arguments as Record<string, string> | undefined;\n if (args?.path) report.filesCreated.push(args.path);\n }\n if (toolName === 'edit') {\n const args = data.arguments as Record<string, string> | undefined;\n if (args?.path && !report.filesEdited.includes(args.path)) {\n report.filesEdited.push(args.path);\n }\n }\n break;\n }\n\n case 'session.task_complete': {\n const summary = data.summary as string | undefined;\n report.taskCompletions.push(summary ?? '(task completed)');\n report.complete = true;\n break;\n }\n\n case 'session.error': {\n const msg = data.message as string | undefined;\n if (msg) report.errors.push(msg);\n break;\n }\n\n case 'session.shutdown': {\n const premium = data.totalPremiumRequests as number | undefined;\n if (premium != null) report.premiumRequests = premium;\n break;\n }\n }\n }\n\n if (report.startTime && report.endTime) {\n report.durationMs = new Date(report.endTime).getTime() - new Date(report.startTime).getTime();\n }\n\n return report;\n}\n","import { execSync, spawn } from 'node:child_process';\nimport { resolve } from 'node:path';\nimport { getLatestSessionId, getSessionPremium, getSessionCwd } from './session.js';\nimport { log, warn, fail } from './logger.js';\n\nexport interface CopilotProcess {\n pid: number;\n command: string;\n sessionId?: string;\n cwd?: string;\n}\n\nexport interface CopilotResult {\n exitCode: number;\n sessionId: string | null;\n premium: number;\n}\n\nexport function isCopilotInstalled(): boolean {\n try {\n execSync('which copilot', { stdio: 'pipe', encoding: 'utf-8' });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function assertCopilot(): void {\n if (!isCopilotInstalled()) {\n fail('copilot CLI not found. Install with: npm i -g @githubnext/copilot');\n process.exit(1);\n }\n}\n\nexport function findCopilotProcesses(): CopilotProcess[] {\n try {\n const output = execSync('ps -eo pid,command', { encoding: 'utf-8' });\n const results: CopilotProcess[] = [];\n const myPid = process.pid;\n const parentPid = process.ppid;\n for (const line of output.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n if (\n (trimmed.includes('copilot') || trimmed.includes('@githubnext/copilot')) &&\n !trimmed.includes('ps -eo') &&\n !trimmed.includes('copilot-agent') &&\n !trimmed.includes('grep')\n ) {\n const match = trimmed.match(/^(\\d+)\\s+(.+)$/);\n if (match) {\n const pid = parseInt(match[1], 10);\n // Exclude our own process tree\n if (pid === myPid || pid === parentPid) continue;\n const cmd = match[2];\n const sidMatch = cmd.match(/resume[= ]+([a-f0-9-]{36})/);\n // Try to get cwd of the process\n let cwd: string | undefined;\n try {\n cwd = execSync(`lsof -p ${pid} -Fn 2>/dev/null | grep '^n/' | head -1`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim().slice(1) || undefined;\n } catch { /* best effort */ }\n // Fallback: get cwd from session if we know the session\n const sid = sidMatch?.[1];\n if (!cwd && sid) {\n cwd = getSessionCwd(sid) || undefined;\n }\n results.push({ pid, command: cmd, sessionId: sid, cwd });\n }\n }\n }\n return results;\n } catch {\n return [];\n }\n}\n\nexport function findPidForSession(sid: string): number | null {\n const procs = findCopilotProcesses();\n const matching = procs\n .filter(p => p.command.includes(sid))\n .sort((a, b) => b.pid - a.pid);\n return matching[0]?.pid ?? null;\n}\n\n/**\n * SAFETY: Wait until no copilot is running in the SAME directory.\n * Copilot in different directories/worktrees can run in parallel.\n */\nexport async function waitForCopilotInDir(\n dir: string,\n timeoutMs = 14_400_000,\n pollMs = 10_000,\n): Promise<void> {\n const targetDir = resolve(dir);\n const start = Date.now();\n let warned = false;\n while (Date.now() - start < timeoutMs) {\n const procs = findCopilotProcesses();\n const conflicting = procs.filter(p => {\n if (!p.cwd) return false;\n return resolve(p.cwd) === targetDir;\n });\n if (conflicting.length === 0) return;\n if (!warned) {\n warn(`Waiting for copilot in ${targetDir} to finish...`);\n for (const p of conflicting) {\n log(` PID ${p.pid}: ${p.command.slice(0, 80)}`);\n }\n warned = true;\n }\n await sleep(pollMs);\n }\n warn('Timeout waiting for copilot to finish in directory');\n}\n\n/**\n * SAFETY: Check if a session already has a running copilot process.\n * If so, refuse to spawn another one to prevent corruption.\n */\nexport function assertSessionNotRunning(sid: string): void {\n const pid = findPidForSession(sid);\n if (pid) {\n fail(`Session ${sid.slice(0, 8)}… already has copilot running (PID ${pid}). Cannot resume — would corrupt the session.`);\n process.exit(1);\n }\n}\n\nexport async function waitForExit(pid: number, timeoutMs = 14_400_000): Promise<boolean> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n process.kill(pid, 0);\n await sleep(5000);\n } catch {\n return true; // process exited\n }\n }\n return false; // timeout\n}\n\nexport async function runCopilot(\n args: string[],\n options?: { cwd?: string; useWorktree?: boolean },\n): Promise<CopilotResult> {\n const dir = options?.cwd ?? process.cwd();\n\n if (options?.useWorktree) {\n // Worktree mode: create separate worktree, no waiting needed\n // (caller is responsible for creating worktree and passing its path)\n } else {\n // Default: wait for copilot in same directory to finish\n await waitForCopilotInDir(dir);\n }\n\n return new Promise((resolve) => {\n const child = spawn('copilot', args, {\n cwd: options?.cwd,\n stdio: 'inherit',\n env: { ...process.env },\n });\n\n child.on('close', async (code) => {\n await sleep(3000); // let events flush\n const sid = getLatestSessionId();\n const premium = sid ? getSessionPremium(sid) : 0;\n resolve({\n exitCode: code ?? 1,\n sessionId: sid,\n premium,\n });\n });\n\n child.on('error', () => {\n resolve({ exitCode: 1, sessionId: null, premium: 0 });\n });\n });\n}\n\nexport function runCopilotResume(\n sid: string,\n steps: number,\n message?: string,\n cwd?: string,\n): Promise<CopilotResult> {\n // SAFETY: Refuse if session already running\n assertSessionNotRunning(sid);\n\n const args = [\n `--resume=${sid}`,\n '--autopilot',\n '--allow-all',\n '--max-autopilot-continues',\n String(steps),\n '--no-ask-user',\n ];\n if (message) args.push('-p', message);\n return runCopilot(args, { cwd });\n}\n\nexport function runCopilotTask(\n prompt: string,\n steps: number,\n cwd?: string,\n useWorktree?: boolean,\n): Promise<CopilotResult> {\n return runCopilot([\n '-p', prompt,\n '--autopilot',\n '--allow-all',\n '--max-autopilot-continues', String(steps),\n '--no-ask-user',\n ], { cwd, useWorktree });\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms));\n}\n","import { appendFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { RED, GREEN, YELLOW, CYAN, DIM, RESET } from './colors.js';\n\nlet logFilePath: string | null = null;\n\nconst ANSI_RE =\n /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;\n\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '');\n}\n\nfunction writeToFile(msg: string): void {\n if (!logFilePath) return;\n try {\n appendFileSync(logFilePath, stripAnsi(msg) + '\\n');\n } catch { /* ignore file write errors */ }\n}\n\nexport function setLogFile(path: string): void {\n mkdirSync(dirname(path), { recursive: true });\n logFilePath = path;\n}\n\nexport function log(msg: string): void {\n console.log(msg);\n writeToFile(msg);\n}\n\nexport function warn(msg: string): void {\n const out = `${YELLOW}⚠ ${msg}${RESET}`;\n console.log(out);\n writeToFile(`⚠ ${msg}`);\n}\n\nexport function ok(msg: string): void {\n const out = `${GREEN}✔ ${msg}${RESET}`;\n console.log(out);\n writeToFile(`✔ ${msg}`);\n}\n\nexport function fail(msg: string): void {\n const out = `${RED}✖ ${msg}${RESET}`;\n console.error(out);\n writeToFile(`✖ ${msg}`);\n}\n\nexport function info(msg: string): void {\n const out = `${CYAN}ℹ ${msg}${RESET}`;\n console.log(out);\n writeToFile(`ℹ ${msg}`);\n}\n\nexport function dim(msg: string): void {\n const out = `${DIM}${msg}${RESET}`;\n console.log(out);\n writeToFile(msg);\n}\n\nexport function notify(message: string, title = 'copilot-agent'): void {\n try {\n if (process.platform === 'darwin') {\n execSync(\n `osascript -e 'display notification \"${message.replace(/\"/g, '\\\\\"')}\" with title \"${title.replace(/\"/g, '\\\\\"')}\"'`,\n { stdio: 'ignore' },\n );\n } else {\n try {\n execSync('which notify-send', { stdio: 'pipe' });\n execSync(\n `notify-send \"${title}\" \"${message.replace(/\"/g, '\\\\\"')}\"`,\n { stdio: 'ignore' },\n );\n } catch { /* notify-send not available */ }\n }\n } catch { /* notification not available */ }\n}\n","export const RED = '\\x1b[31m';\nexport const GREEN = '\\x1b[32m';\nexport const YELLOW = '\\x1b[33m';\nexport const BLUE = '\\x1b[34m';\nexport const CYAN = '\\x1b[36m';\nexport const DIM = '\\x1b[2m';\nexport const BOLD = '\\x1b[1m';\nexport const RESET = '\\x1b[0m';\n","import type { Command } from 'commander';\nimport {\n listSessions,\n hasTaskComplete,\n getLastEvent,\n getSessionPremium,\n} from '../lib/session.js';\nimport { findCopilotProcesses } from '../lib/process.js';\nimport { log } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, GREEN, YELLOW, RESET } from '../lib/colors.js';\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command('status')\n .description('Show copilot session status')\n .option('-l, --limit <n>', 'Number of sessions to show', '10')\n .option('-a, --active', 'Show only active (running) processes')\n .option('-i, --incomplete', 'Only show incomplete sessions')\n .action((opts) => {\n if (opts.active) {\n showActive();\n } else {\n showRecent(parseInt(opts.limit, 10), opts.incomplete ?? false);\n }\n });\n}\n\nfunction showActive(): void {\n const procs = findCopilotProcesses();\n if (procs.length === 0) {\n log(`${DIM}No active copilot processes.${RESET}`);\n return;\n }\n\n log(`\\n${BOLD}${'PID'.padEnd(8)} ${'Session'.padEnd(40)} Command${RESET}`);\n log('─'.repeat(108));\n\n for (const p of procs) {\n log(\n `${CYAN}${String(p.pid).padEnd(8)}${RESET} ${(p.sessionId ?? '—').padEnd(40)} ${truncate(p.command, 58)}`,\n );\n }\n log('');\n}\n\nfunction showRecent(limit: number, incompleteOnly: boolean): void {\n let sessions = listSessions(limit);\n if (incompleteOnly) {\n sessions = sessions.filter(s => !s.complete);\n }\n\n if (sessions.length === 0) {\n log(`${DIM}No sessions found.${RESET}`);\n return;\n }\n\n log(\n `\\n${BOLD}${'Status'.padEnd(10)} ${'Premium'.padEnd(10)} ${'Last Event'.padEnd(25)} ${'Summary'.padEnd(40)} ID${RESET}`,\n );\n log('─'.repeat(120));\n\n for (const s of sessions) {\n const status = s.complete\n ? `${GREEN}✔ done${RESET}`\n : `${YELLOW}⏸ stop${RESET}`;\n const premium = String(s.premiumRequests);\n const summary = truncate(s.summary || '—', 38);\n\n log(\n `${status.padEnd(10 + 9)} ${premium.padEnd(10)} ${s.lastEvent.padEnd(25)} ${summary.padEnd(40)} ${DIM}${s.id}${RESET}`,\n );\n }\n log(`\\n${DIM}Total: ${sessions.length} session(s)${RESET}`);\n}\n\nfunction truncate(s: string, max: number): string {\n if (s.length <= max) return s;\n return s.substring(0, max - 1) + '…';\n}\n","import type { Command } from 'commander';\nimport {\n validateSession,\n hasTaskComplete,\n getSessionSummary,\n getLastEvent,\n findLatestIncomplete,\n getSessionCwd,\n} from '../lib/session.js';\nimport {\n findPidForSession,\n waitForExit,\n runCopilotResume,\n assertCopilot,\n} from '../lib/process.js';\nimport { log, ok, warn, fail, info, notify } from '../lib/logger.js';\nimport { CYAN, RESET } from '../lib/colors.js';\n\nexport function registerWatchCommand(program: Command): void {\n program\n .command('watch [session-id]')\n .description('Watch a session and auto-resume when it stops')\n .option('-s, --steps <n>', 'Max autopilot continues per resume', '30')\n .option('-r, --max-resumes <n>', 'Max number of resumes', '10')\n .option('-c, --cooldown <n>', 'Seconds between resumes', '10')\n .option('-m, --message <msg>', 'Message to send on resume')\n .action(async (sid: string | undefined, opts) => {\n try {\n await watchCommand(sid, {\n steps: parseInt(opts.steps, 10),\n maxResumes: parseInt(opts.maxResumes, 10),\n cooldown: parseInt(opts.cooldown, 10),\n message: opts.message,\n });\n } catch (err) {\n fail(`Watch error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface WatchOptions {\n steps: number;\n maxResumes: number;\n cooldown: number;\n message?: string;\n}\n\nasync function watchCommand(sid: string | undefined, opts: WatchOptions): Promise<void> {\n assertCopilot();\n\n if (!sid) {\n sid = findLatestIncomplete() ?? undefined;\n if (!sid) {\n fail('No incomplete session found.');\n process.exit(1);\n }\n info(`Auto-detected incomplete session: ${CYAN}${sid}${RESET}`);\n }\n\n if (!validateSession(sid)) {\n fail(`Invalid session: ${sid}`);\n process.exit(1);\n }\n\n if (hasTaskComplete(sid)) {\n ok(`Session ${sid} already completed.`);\n return;\n }\n\n let resumes = 0;\n\n while (resumes < opts.maxResumes) {\n const pid = findPidForSession(sid);\n\n if (pid) {\n info(`Watching PID ${pid} for session ${CYAN}${sid.slice(0, 8)}${RESET}…`);\n const exited = await waitForExit(pid);\n\n if (!exited) {\n warn('Timeout waiting for process exit.');\n break;\n }\n }\n\n // Small delay for events to flush\n await sleep(3000);\n\n if (hasTaskComplete(sid)) {\n ok(`Task complete! Summary: ${getSessionSummary(sid) || 'none'}`);\n notify('Task completed!', `Session ${sid.slice(0, 8)}`);\n return;\n }\n\n // Interrupted — resume\n resumes++;\n log(`Session interrupted (${getLastEvent(sid)}). Resume ${resumes}/${opts.maxResumes}…`);\n\n if (opts.cooldown > 0 && resumes > 1) {\n info(`Cooldown ${opts.cooldown}s...`);\n await sleep(opts.cooldown * 1000);\n }\n\n const cwd = getSessionCwd(sid) || undefined;\n const result = await runCopilotResume(\n sid,\n opts.steps,\n opts.message ?? 'Continue remaining work. Pick up where you left off and complete the task.',\n cwd,\n );\n\n if (result.sessionId && result.sessionId !== sid) {\n info(`New session created: ${CYAN}${result.sessionId}${RESET}`);\n sid = result.sessionId;\n }\n }\n\n warn(`Max resumes (${opts.maxResumes}) reached.`);\n notify('Max resumes reached', `Session ${sid.slice(0, 8)}`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms));\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, basename, resolve } from 'node:path';\nimport { execSync } from 'node:child_process';\n\nexport type ProjectType =\n | 'kmp' | 'kotlin' | 'java'\n | 'node' | 'typescript' | 'react' | 'next'\n | 'python' | 'rust' | 'swift' | 'go' | 'flutter'\n | 'unknown';\n\nexport function detectProjectType(dir: string): ProjectType {\n const exists = (f: string) => existsSync(join(dir, f));\n\n if (exists('build.gradle.kts') || exists('build.gradle')) {\n if (exists('composeApp') || exists('gradle.properties')) {\n try {\n const gradle = readFileSync(join(dir, 'build.gradle.kts'), 'utf-8');\n if (gradle.includes('multiplatform') || gradle.includes('KotlinMultiplatform')) return 'kmp';\n } catch { /* ignore */ }\n }\n if (exists('pom.xml')) return 'java';\n return 'kotlin';\n }\n if (exists('pubspec.yaml')) return 'flutter';\n if (exists('Package.swift')) return 'swift';\n try {\n const entries = readdirSync(dir);\n if (entries.some(e => e.endsWith('.xcodeproj'))) return 'swift';\n } catch { /* ignore */ }\n if (exists('Cargo.toml')) return 'rust';\n if (exists('go.mod')) return 'go';\n if (exists('pyproject.toml') || exists('setup.py') || exists('requirements.txt')) return 'python';\n if (exists('package.json')) {\n try {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n if (allDeps['next']) return 'next';\n if (allDeps['react']) return 'react';\n if (allDeps['typescript'] || exists('tsconfig.json')) return 'typescript';\n } catch { /* ignore */ }\n return 'node';\n }\n if (exists('pom.xml')) return 'java';\n return 'unknown';\n}\n\nexport function detectProjectName(dir: string): string {\n try {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));\n if (pkg.name) return pkg.name;\n } catch { /* ignore */ }\n return basename(resolve(dir));\n}\n\nexport function detectMainBranch(dir: string): string {\n try {\n const ref = execSync('git symbolic-ref refs/remotes/origin/HEAD', {\n cwd: dir,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n return ref.split('/').pop() ?? 'main';\n } catch { /* ignore */ }\n\n try {\n const branch = execSync('git branch --show-current', {\n cwd: dir,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n if (branch) return branch;\n } catch { /* ignore */ }\n\n return 'main';\n}\n","import type { ProjectType } from \"./detect.js\";\n\ninterface TaskPrompt {\n title: string;\n prompt: string;\n priority: number;\n}\n\nconst COMMON_TASKS: TaskPrompt[] = [\n {\n title: \"Fix TODOs\",\n prompt:\n \"Scan for TODO, FIXME, HACK comments. Fix the most impactful ones. Run tests to verify.\",\n priority: 1,\n },\n {\n title: \"Update dependencies\",\n prompt:\n \"Check for outdated dependencies. Update patch/minor versions that are safe. Run tests after updating.\",\n priority: 2,\n },\n {\n title: \"Improve test coverage\",\n prompt:\n \"Find untested public functions. Write tests for the most critical ones. Target 80%+ coverage.\",\n priority: 3,\n },\n {\n title: \"Fix lint warnings\",\n prompt:\n \"Run the project linter. Fix all warnings without changing behavior. Run tests.\",\n priority: 4,\n },\n {\n title: \"Improve documentation\",\n prompt:\n \"Review README and code docs. Add missing JSDoc/KDoc for public APIs. Update outdated sections.\",\n priority: 5,\n },\n {\n title: \"Security audit\",\n prompt:\n \"Check for common security issues: hardcoded secrets, SQL injection, XSS, insecure defaults. Fix any found.\",\n priority: 6,\n },\n];\n\nconst TYPE_TASKS: Partial<Record<ProjectType, TaskPrompt[]>> = {\n kmp: [\n {\n title: \"KMP: Optimize Compose\",\n prompt:\n \"Review Compose UI code for recomposition issues. Add @Stable/@Immutable where needed. Check remember usage.\",\n priority: 2,\n },\n {\n title: \"KMP: Check expect/actual\",\n prompt:\n \"Review expect/actual declarations. Ensure all platforms have proper implementations. Check for missing iOS/Desktop actuals.\",\n priority: 3,\n },\n {\n title: \"KMP: Room migrations\",\n prompt:\n \"Check Room database schema. Ensure migrations are defined for schema changes. Add missing migration tests.\",\n priority: 4,\n },\n ],\n typescript: [\n {\n title: \"TS: Strict type safety\",\n prompt:\n \"Find `any` types and loose assertions. Replace with proper types. Enable stricter tsconfig options if safe.\",\n priority: 2,\n },\n ],\n react: [\n {\n title: \"React: Performance\",\n prompt:\n \"Find unnecessary re-renders. Add React.memo, useMemo, useCallback where beneficial. Check bundle size.\",\n priority: 2,\n },\n ],\n python: [\n {\n title: \"Python: Type hints\",\n prompt:\n \"Add type hints to public functions. Run mypy to check type safety. Fix any type errors.\",\n priority: 2,\n },\n ],\n node: [\n {\n title: \"Node: Error handling\",\n prompt:\n \"Review async error handling. Add try/catch for unhandled promises. Check for missing error middleware.\",\n priority: 2,\n },\n ],\n};\n\nexport function getTasksForProject(type: ProjectType): TaskPrompt[] {\n const specific = TYPE_TASKS[type] ?? [];\n return [...specific, ...COMMON_TASKS].sort(\n (a, b) => a.priority - b.priority,\n );\n}\n","import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nconst LOCK_BASE = join(homedir(), '.copilot', 'locks');\n\nfunction lockDir(name: string): string {\n return join(LOCK_BASE, `${name}.lock`);\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function acquireLock(name: string, timeoutMs = 30_000): boolean {\n mkdirSync(LOCK_BASE, { recursive: true });\n const dir = lockDir(name);\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n try {\n mkdirSync(dir);\n // Lock acquired — write metadata\n writeFileSync(join(dir, 'pid'), String(process.pid));\n writeFileSync(join(dir, 'acquired'), new Date().toISOString());\n return true;\n } catch {\n // Lock dir exists — check if holder is still alive\n try {\n const holderPid = parseInt(readFileSync(join(dir, 'pid'), 'utf-8').trim(), 10);\n if (!isPidAlive(holderPid)) {\n // Stale lock — break it\n rmSync(dir, { recursive: true, force: true });\n continue;\n }\n } catch {\n // Can't read pid file — try breaking\n rmSync(dir, { recursive: true, force: true });\n continue;\n }\n // Holder is alive — wait and retry\n const waitMs = Math.min(500, deadline - Date.now());\n if (waitMs > 0) {\n const start = Date.now();\n while (Date.now() - start < waitMs) { /* spin wait */ }\n }\n }\n }\n return false;\n}\n\nexport function releaseLock(name: string): void {\n const dir = lockDir(name);\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch { /* already released */ }\n}\n\nexport async function withLock<T>(name: string, fn: () => T | Promise<T>): Promise<T> {\n if (!acquireLock(name)) {\n throw new Error(`Failed to acquire lock: ${name}`);\n }\n try {\n return await fn();\n } finally {\n releaseLock(name);\n }\n}\n","import { existsSync, rmSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { execSync } from 'node:child_process';\n\nfunction gitExec(dir: string, cmd: string): string | null {\n try {\n return execSync(cmd, {\n cwd: dir,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n } catch {\n return null;\n }\n}\n\nexport function isGitRepo(dir: string): boolean {\n return existsSync(join(dir, '.git'));\n}\n\nexport function gitCurrentBranch(dir: string): string | null {\n return gitExec(dir, 'git branch --show-current');\n}\n\nexport function gitStash(dir: string): boolean {\n return gitExec(dir, 'git stash -q') !== null;\n}\n\nexport function gitStashPop(dir: string): boolean {\n return gitExec(dir, 'git stash pop -q') !== null;\n}\n\nexport function gitCheckout(dir: string, branch: string): boolean {\n return gitExec(dir, `git checkout ${branch} -q`) !== null;\n}\n\nexport function gitCreateBranch(dir: string, branch: string): boolean {\n return gitExec(dir, `git checkout -b ${branch}`) !== null;\n}\n\nexport function gitCountCommits(dir: string, from: string, to: string): number {\n const result = gitExec(dir, `git log ${from}..${to} --oneline`);\n if (!result) return 0;\n return result.split('\\n').filter(l => l.trim()).length;\n}\n\nexport function gitStatus(dir: string): string {\n return gitExec(dir, 'git status --porcelain') ?? '';\n}\n\nexport function gitRoot(dir: string): string | null {\n return gitExec(dir, 'git rev-parse --show-toplevel');\n}\n\n// ── Worktree support ──\n\nexport function listWorktrees(dir: string): { path: string; branch: string; bare: boolean }[] {\n const raw = gitExec(dir, 'git worktree list --porcelain');\n if (!raw) return [];\n const trees: { path: string; branch: string; bare: boolean }[] = [];\n let current: { path: string; branch: string; bare: boolean } = { path: '', branch: '', bare: false };\n for (const line of raw.split('\\n')) {\n if (line.startsWith('worktree ')) {\n if (current.path) trees.push(current);\n current = { path: line.slice(9), branch: '', bare: false };\n } else if (line.startsWith('branch ')) {\n current.branch = line.slice(7).replace('refs/heads/', '');\n } else if (line === 'bare') {\n current.bare = true;\n }\n }\n if (current.path) trees.push(current);\n return trees;\n}\n\n/**\n * Create a git worktree for parallel copilot work.\n * Returns the worktree path or null on failure.\n */\nexport function createWorktree(repoDir: string, branch: string): string | null {\n const safeBranch = branch.replace(/[^a-zA-Z0-9._/-]/g, '-');\n const worktreePath = resolve(repoDir, '..', `${resolve(repoDir).split('/').pop()}-wt-${safeBranch}`);\n\n if (existsSync(worktreePath)) {\n return worktreePath; // already exists\n }\n\n // Create branch if it doesn't exist, then add worktree\n const branchExists = gitExec(repoDir, `git rev-parse --verify ${safeBranch}`) !== null;\n const cmd = branchExists\n ? `git worktree add \"${worktreePath}\" ${safeBranch}`\n : `git worktree add -b ${safeBranch} \"${worktreePath}\"`;\n\n if (gitExec(repoDir, cmd) !== null) {\n return worktreePath;\n }\n return null;\n}\n\n/**\n * Remove a worktree (prune).\n */\nexport function removeWorktree(repoDir: string, worktreePath: string): boolean {\n const result = gitExec(repoDir, `git worktree remove \"${worktreePath}\" --force`);\n return result !== null;\n}\n\n/**\n * Clean up all copilot-agent worktrees.\n */\nexport function cleanupWorktrees(repoDir: string): number {\n const trees = listWorktrees(repoDir);\n let cleaned = 0;\n for (const t of trees) {\n if (t.path.includes('-wt-')) {\n if (removeWorktree(repoDir, t.path)) cleaned++;\n }\n }\n gitExec(repoDir, 'git worktree prune');\n return cleaned;\n}\n","import type { Command } from 'commander';\nimport { detectProjectType, detectProjectName, detectMainBranch } from '../lib/detect.js';\nimport { getTasksForProject } from '../lib/tasks.js';\nimport { runCopilotTask, assertCopilot } from '../lib/process.js';\nimport { withLock } from '../lib/lock.js';\nimport { isGitRepo, gitCurrentBranch, gitStatus, gitStash, gitCheckout, gitCreateBranch, gitCountCommits, createWorktree, removeWorktree } from '../lib/git.js';\nimport { log, ok, warn, fail, info, notify } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, GREEN, RESET, YELLOW } from '../lib/colors.js';\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run [dir]')\n .description('Discover and fix issues in a project')\n .option('-s, --steps <n>', 'Max autopilot continues per task', '30')\n .option('-t, --max-tasks <n>', 'Max number of tasks to run', '5')\n .option('-p, --max-premium <n>', 'Max total premium requests', '50')\n .option('--dry-run', 'Show tasks without executing')\n .option('--worktree', 'Use git worktree for parallel execution (default: wait for idle)')\n .action(async (dir: string | undefined, opts) => {\n try {\n await runCommand(dir ?? process.cwd(), {\n steps: parseInt(opts.steps, 10),\n maxTasks: parseInt(opts.maxTasks, 10),\n maxPremium: parseInt(opts.maxPremium, 10),\n dryRun: opts.dryRun ?? false,\n useWorktree: opts.worktree ?? false,\n });\n } catch (err) {\n fail(`Run error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface RunOptions {\n steps: number;\n maxTasks: number;\n maxPremium: number;\n dryRun: boolean;\n useWorktree: boolean;\n}\n\nasync function runCommand(dir: string, opts: RunOptions): Promise<void> {\n assertCopilot();\n\n const projectType = detectProjectType(dir);\n const name = detectProjectName(dir);\n const mainBranch = isGitRepo(dir) ? detectMainBranch(dir) : null;\n\n info(`Project: ${CYAN}${name}${RESET} (${projectType})`);\n if (mainBranch) info(`Main branch: ${mainBranch}`);\n\n const tasks = getTasksForProject(projectType).slice(0, opts.maxTasks);\n\n if (tasks.length === 0) {\n warn('No tasks found for this project type.');\n return;\n }\n\n log(`Found ${tasks.length} tasks:`);\n for (const t of tasks) {\n log(` ${DIM}•${RESET} ${t.title}`);\n }\n\n if (opts.dryRun) {\n log(`${DIM}(dry-run — not executing)${RESET}`);\n return;\n }\n\n const originalBranch = isGitRepo(dir) ? gitCurrentBranch(dir) : null;\n let completed = 0;\n let premiumTotal = 0;\n\n for (const task of tasks) {\n if (premiumTotal >= opts.maxPremium) {\n warn(`Premium request limit reached (${premiumTotal}/${opts.maxPremium}).`);\n break;\n }\n\n log(`\\n${'═'.repeat(60)}`);\n log(`${BOLD}${CYAN}Task: ${task.title}${RESET}`);\n log(`${'═'.repeat(60)}`);\n\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 6);\n const branchName = `agent/fix-${completed + 1}-${timestamp}-${random}`;\n\n if (mainBranch && isGitRepo(dir)) {\n if (gitStatus(dir)) gitStash(dir);\n gitCheckout(dir, mainBranch);\n if (!gitCreateBranch(dir, branchName)) {\n warn(`Could not create branch ${branchName}, continuing on current.`);\n }\n }\n\n info(`Running: ${task.title}…`);\n\n let taskDir = dir;\n let worktreeCreated = false;\n\n if (opts.useWorktree && isGitRepo(dir)) {\n try {\n taskDir = createWorktree(dir, branchName, mainBranch ?? undefined);\n worktreeCreated = true;\n info(`Created worktree: ${taskDir}`);\n } catch (err) {\n warn(`Worktree creation failed, falling back to main dir: ${err}`);\n taskDir = dir;\n }\n }\n\n const result = await withLock('copilot-run', () =>\n runCopilotTask(task.prompt, opts.steps, taskDir, opts.useWorktree),\n );\n\n const commitRef = worktreeCreated ? taskDir : dir;\n const commits = mainBranch ? gitCountCommits(commitRef, mainBranch, 'HEAD') : 0;\n premiumTotal += result.premium;\n completed++;\n ok(`${task.title} — ${commits} commit(s), ${result.premium} premium`);\n\n if (worktreeCreated) {\n try {\n removeWorktree(dir, taskDir);\n } catch (err) {\n warn(`Worktree cleanup failed: ${err}`);\n }\n }\n\n if (!worktreeCreated && originalBranch && isGitRepo(dir)) {\n gitCheckout(dir, mainBranch ?? originalBranch);\n }\n }\n\n log(`\\n${BOLD}═══ Run Summary ═══${RESET}`);\n log(`Completed ${completed}/${tasks.length} tasks. Total premium: ${premiumTotal}`);\n notify(`Completed ${completed} tasks`, name);\n}\n","import type { Command } from 'commander';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { detectProjectType, detectProjectName, detectMainBranch } from '../lib/detect.js';\nimport { getTasksForProject } from '../lib/tasks.js';\nimport { runCopilotTask, assertCopilot, findPidForSession, findCopilotProcesses, waitForExit, waitForCopilotInDir, runCopilotResume } from '../lib/process.js';\nimport { withLock } from '../lib/lock.js';\nimport { isGitRepo, gitCurrentBranch, gitStash, gitCheckout, gitCreateBranch, gitCountCommits, createWorktree, removeWorktree } from '../lib/git.js';\nimport { findLatestIncomplete, validateSession, hasTaskComplete, getSessionCwd } from '../lib/session.js';\nimport { log, ok, warn, fail, info, setLogFile, notify } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, RESET } from '../lib/colors.js';\n\nexport function registerOvernightCommand(program: Command): void {\n program\n .command('overnight [dir]')\n .description('Run tasks continuously until a deadline')\n .option('-u, --until <HH>', 'Stop at this hour (24h format)', '07')\n .option('-s, --steps <n>', 'Max autopilot continues per task', '50')\n .option('-c, --cooldown <n>', 'Seconds between tasks', '15')\n .option('-p, --max-premium <n>', 'Max premium requests budget', '300')\n .option('--dry-run', 'Show plan without executing')\n .option('--worktree', 'Use git worktree for parallel execution (default: wait for idle)')\n .action(async (dir: string | undefined, opts) => {\n try {\n await overnightCommand(dir ?? process.cwd(), {\n until: parseInt(opts.until, 10),\n steps: parseInt(opts.steps, 10),\n cooldown: parseInt(opts.cooldown, 10),\n maxPremium: parseInt(opts.maxPremium, 10),\n dryRun: opts.dryRun ?? false,\n useWorktree: opts.worktree ?? false,\n });\n } catch (err) {\n fail(`Overnight error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface OvernightOptions {\n until: number;\n steps: number;\n cooldown: number;\n maxPremium: number;\n dryRun: boolean;\n useWorktree: boolean;\n}\n\nfunction isPastDeadline(untilHour: number): boolean {\n const hour = new Date().getHours();\n return hour >= untilHour && hour < 20;\n}\n\nasync function overnightCommand(dir: string, opts: OvernightOptions): Promise<void> {\n assertCopilot();\n\n const ts = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);\n const logPath = join(homedir(), '.copilot', 'auto-resume-logs', `overnight-${ts}.log`);\n setLogFile(logPath);\n\n const name = detectProjectName(dir);\n const projectType = detectProjectType(dir);\n const mainBranch = isGitRepo(dir) ? detectMainBranch(dir) : null;\n\n info(`Overnight runner for ${CYAN}${name}${RESET} (${projectType})`);\n info(`Deadline: ${String(opts.until).padStart(2, '0')}:00`);\n info(`Max premium: ${opts.maxPremium}, Steps: ${opts.steps}`);\n info(`Log: ${logPath}`);\n\n const tasks = getTasksForProject(projectType);\n\n if (opts.dryRun) {\n log(`\\nWould run ${tasks.length} tasks:`);\n for (const t of tasks) log(` ${DIM}•${RESET} ${t.title}`);\n return;\n }\n\n // Phase 1: Resume existing incomplete session\n const existingSession = findLatestIncomplete();\n if (existingSession && validateSession(existingSession)) {\n info(`Found incomplete session: ${existingSession}`);\n const pid = findPidForSession(existingSession);\n if (pid) {\n info(`Waiting for running copilot (PID ${pid})...`);\n await waitForExit(pid);\n }\n\n if (!hasTaskComplete(existingSession) && !isPastDeadline(opts.until)) {\n info('Resuming incomplete session...');\n const cwd = getSessionCwd(existingSession) || dir;\n await runCopilotResume(\n existingSession,\n opts.steps,\n 'Continue remaining work. Complete the task.',\n cwd,\n );\n }\n }\n\n // Phase 2: Loop tasks until deadline\n const originalBranch = isGitRepo(dir) ? gitCurrentBranch(dir) : null;\n let taskIdx = 0;\n let totalPremium = 0;\n let totalCommits = 0;\n\n while (!isPastDeadline(opts.until) && taskIdx < tasks.length) {\n if (totalPremium >= opts.maxPremium) {\n warn(`Premium budget exhausted: ${totalPremium}/${opts.maxPremium}`);\n break;\n }\n\n const task = tasks[taskIdx % tasks.length];\n taskIdx++;\n\n log(`\\n${'═'.repeat(60)}`);\n log(`${BOLD}${CYAN}[${new Date().toLocaleTimeString()}] Task ${taskIdx}: ${task.title}${RESET}`);\n log(`${DIM}Premium: ${totalPremium}/${opts.maxPremium}${RESET}`);\n log(`${'═'.repeat(60)}`);\n\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 6);\n const branchName = `agent/overnight-${taskIdx}-${timestamp}-${random}`;\n\n if (mainBranch && isGitRepo(dir)) {\n gitStash(dir);\n gitCheckout(dir, mainBranch);\n gitCreateBranch(dir, branchName);\n }\n\n info(`Running: ${task.title}…`);\n\n let taskDir = dir;\n let worktreeCreated = false;\n\n if (opts.useWorktree && isGitRepo(dir)) {\n try {\n taskDir = createWorktree(dir, branchName, mainBranch ?? undefined);\n worktreeCreated = true;\n info(`Created worktree: ${taskDir}`);\n } catch (err) {\n warn(`Worktree creation failed, falling back to main dir: ${err}`);\n taskDir = dir;\n }\n }\n\n try {\n const result = await withLock('copilot-overnight', () =>\n runCopilotTask(task.prompt, opts.steps, taskDir, opts.useWorktree),\n );\n\n const commitRef = worktreeCreated ? taskDir : dir;\n const commits = mainBranch ? gitCountCommits(commitRef, mainBranch, 'HEAD') : 0;\n totalPremium += result.premium;\n totalCommits += commits;\n\n if (commits > 0) {\n ok(`${commits} commit(s) on ${branchName}`);\n } else {\n log(`${DIM}No commits on ${branchName}${RESET}`);\n }\n } catch (err) {\n fail(`Task failed: ${err}`);\n }\n\n // Cleanup worktree if we created one\n if (worktreeCreated) {\n try {\n removeWorktree(dir, taskDir);\n info(`Removed worktree: ${taskDir}`);\n } catch (err) {\n warn(`Worktree cleanup failed: ${err}`);\n }\n }\n\n if (!worktreeCreated && mainBranch && isGitRepo(dir)) {\n gitCheckout(dir, mainBranch);\n }\n\n if (!isPastDeadline(opts.until)) {\n info(`Cooldown ${opts.cooldown}s…`);\n await sleep(opts.cooldown * 1000);\n }\n }\n\n if (originalBranch && isGitRepo(dir)) {\n gitCheckout(dir, originalBranch);\n }\n\n const summary = `Overnight done — ${taskIdx} tasks, ${totalCommits} commits, ${totalPremium} premium.`;\n ok(summary);\n notify(summary, name);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(r => setTimeout(r, ms));\n}\n","import type { Command } from 'commander';\nimport { existsSync, copyFileSync, mkdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { homedir } from 'node:os';\nimport { detectProjectType, detectProjectName } from '../lib/detect.js';\nimport { runCopilotTask, assertCopilot } from '../lib/process.js';\nimport { withLock } from '../lib/lock.js';\nimport { log, ok, warn, fail, info, notify } from '../lib/logger.js';\nimport { CYAN, RESET } from '../lib/colors.js';\n\nexport function registerResearchCommand(program: Command): void {\n program\n .command('research [project]')\n .description('Research improvements or a specific topic')\n .option('-s, --steps <n>', 'Max autopilot continues', '50')\n .action(async (project: string | undefined, opts) => {\n try {\n await researchCommand(project ?? process.cwd(), {\n steps: parseInt(opts.steps, 10),\n });\n } catch (err) {\n fail(`Research error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\ninterface ResearchOptions {\n steps: number;\n}\n\nfunction buildResearchPrompt(projectType: string, projectName: string): string {\n return `You are a senior software architect. Analyze this ${projectType} project \"${projectName}\" thoroughly.\n\nResearch and produce a file called RESEARCH-PROPOSALS.md with:\n\n1. **Architecture Assessment** — Current architecture, patterns used, strengths and weaknesses\n2. **Code Quality Report** — Common issues, anti-patterns, technical debt areas\n3. **Security Audit** — Potential vulnerabilities, dependency risks, configuration issues\n4. **Performance Analysis** — Bottlenecks, optimization opportunities, resource usage\n5. **Testing Gap Analysis** — Untested areas, test quality, coverage recommendations\n6. **Improvement Proposals** — Prioritized list of actionable improvements with effort estimates\n\nFor each proposal, include:\n- Priority (P0/P1/P2)\n- Estimated effort (hours)\n- Impact description\n- Suggested implementation approach\n\nWrite RESEARCH-PROPOSALS.md in the project root.`;\n}\n\nasync function researchCommand(dir: string, opts: ResearchOptions): Promise<void> {\n assertCopilot();\n\n const projectDir = resolve(dir);\n const projectType = detectProjectType(projectDir);\n const projectName = detectProjectName(projectDir);\n\n info(`Researching: ${CYAN}${projectName}${RESET} (${projectType})`);\n\n const prompt = buildResearchPrompt(projectType, projectName);\n\n const result = await withLock('copilot-research', () =>\n runCopilotTask(prompt, opts.steps, projectDir),\n );\n\n log(`Copilot exited with code ${result.exitCode}`);\n\n // Check for output file\n const proposalsFile = join(projectDir, 'RESEARCH-PROPOSALS.md');\n if (existsSync(proposalsFile)) {\n ok('RESEARCH-PROPOSALS.md generated.');\n\n // Backup to ~/.copilot/research-reports/\n const backupDir = join(homedir(), '.copilot', 'research-reports');\n mkdirSync(backupDir, { recursive: true });\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const backupFile = join(backupDir, `${projectName}-${timestamp}.md`);\n copyFileSync(proposalsFile, backupFile);\n ok(`Backup saved: ${backupFile}`);\n } else {\n warn('RESEARCH-PROPOSALS.md was not generated. Check copilot output.');\n }\n\n notify('Research complete', projectName);\n}\n","import type { Command } from 'commander';\nimport { resolve } from 'node:path';\nimport {\n listSessions,\n getSessionReport,\n type SessionReport,\n} from '../lib/session.js';\nimport { log, warn, fail } from '../lib/logger.js';\nimport { BOLD, CYAN, DIM, GREEN, YELLOW, RED, RESET } from '../lib/colors.js';\n\nexport function registerReportCommand(program: Command): void {\n program\n .command('report [session-id]')\n .description('Show what copilot did — timeline, tools, commits, files changed')\n .option('-l, --limit <n>', 'Number of recent sessions to report (when no ID given)', '1')\n .option('--project <dir>', 'Filter sessions by project directory')\n .option('--json', 'Output raw JSON')\n .action((sessionId: string | undefined, opts) => {\n try {\n if (sessionId) {\n reportSingle(sessionId, opts.json ?? false);\n } else {\n reportRecent(parseInt(opts.limit, 10), opts.project, opts.json ?? false);\n }\n } catch (err) {\n fail(`Report error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n });\n}\n\nfunction reportRecent(limit: number, projectDir?: string, json = false): void {\n let sessions = listSessions(limit * 3); // fetch extra to filter\n if (projectDir) {\n const target = resolve(projectDir);\n sessions = sessions.filter(s => s.cwd && resolve(s.cwd) === target);\n }\n sessions = sessions.slice(0, limit);\n\n if (sessions.length === 0) {\n warn('No sessions found.');\n return;\n }\n\n for (const s of sessions) {\n reportSingle(s.id, json);\n }\n}\n\nfunction reportSingle(sid: string, json = false): void {\n const report = getSessionReport(sid);\n if (!report) {\n warn(`Session ${sid} not found or invalid.`);\n return;\n }\n\n if (json) {\n log(JSON.stringify(report, null, 2));\n return;\n }\n\n renderReport(report);\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m`;\n const h = Math.floor(ms / 3_600_000);\n const m = Math.round((ms % 3_600_000) / 60_000);\n return `${h}h ${m}m`;\n}\n\nfunction formatTime(iso: string): string {\n if (!iso) return '—';\n const d = new Date(iso);\n return d.toLocaleString('en-GB', {\n month: 'short',\n day: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n });\n}\n\nfunction bar(value: number, max: number, width = 20): string {\n const filled = Math.round((value / Math.max(max, 1)) * width);\n return '█'.repeat(filled) + '░'.repeat(width - filled);\n}\n\nfunction renderReport(r: SessionReport): void {\n const status = r.complete\n ? `${GREEN}✔ Completed${RESET}`\n : `${YELLOW}⏸ Interrupted${RESET}`;\n\n const projectName = r.cwd.split('/').pop() ?? r.cwd;\n\n log('');\n log(`${BOLD}╔${'═'.repeat(62)}╗${RESET}`);\n log(`${BOLD}║${RESET} 📋 Session Report: ${CYAN}${r.id.slice(0, 8)}…${RESET}${' '.repeat(62 - 28 - r.id.slice(0, 8).length)}${BOLD}║${RESET}`);\n log(`${BOLD}╚${'═'.repeat(62)}╝${RESET}`);\n\n // Overview\n log('');\n log(`${BOLD} Overview${RESET}`);\n log(` ${'─'.repeat(58)}`);\n log(` Project: ${CYAN}${projectName}${RESET} ${DIM}${r.cwd}${RESET}`);\n log(` Status: ${status}`);\n log(` Duration: ${BOLD}${formatDuration(r.durationMs)}${RESET} ${DIM}(${formatTime(r.startTime)} → ${formatTime(r.endTime)})${RESET}`);\n log(` Summary: ${r.summary || DIM + '(none)' + RESET}`);\n\n // Stats\n log('');\n log(`${BOLD} Activity${RESET}`);\n log(` ${'─'.repeat(58)}`);\n log(` User messages: ${BOLD}${r.userMessages}${RESET}`);\n log(` Assistant turns: ${BOLD}${r.assistantTurns}${RESET}`);\n log(` Output tokens: ${BOLD}${r.outputTokens.toLocaleString()}${RESET}`);\n log(` Premium requests: ${BOLD}${r.premiumRequests}${RESET}`);\n log(` Tool calls: ${BOLD}${Object.values(r.toolUsage).reduce((a, b) => a + b, 0)}${RESET}`);\n\n // Tools breakdown\n const toolEntries = Object.entries(r.toolUsage).sort((a, b) => b[1] - a[1]);\n if (toolEntries.length > 0) {\n const maxCount = toolEntries[0][1];\n log('');\n log(`${BOLD} Tools Used${RESET}`);\n log(` ${'─'.repeat(58)}`);\n for (const [tool, count] of toolEntries.slice(0, 10)) {\n const barStr = bar(count, maxCount, 15);\n log(` ${DIM}${barStr}${RESET} ${String(count).padStart(5)} ${tool}`);\n }\n if (toolEntries.length > 10) {\n log(` ${DIM} … and ${toolEntries.length - 10} more tools${RESET}`);\n }\n }\n\n // Git commits\n if (r.gitCommits.length > 0) {\n log('');\n log(`${BOLD} Git Commits (${r.gitCommits.length})${RESET}`);\n log(` ${'─'.repeat(58)}`);\n for (const msg of r.gitCommits) {\n log(` ${GREEN}●${RESET} ${msg.slice(0, 70)}${msg.length > 70 ? '…' : ''}`);\n }\n }\n\n // Files created\n if (r.filesCreated.length > 0) {\n log('');\n log(`${BOLD} Files Created (${r.filesCreated.length})${RESET}`);\n log(` ${'─'.repeat(58)}`);\n for (const f of r.filesCreated.slice(0, 15)) {\n const short = f.includes(projectName) ? f.split(projectName + '/')[1] ?? f : f;\n log(` ${GREEN}+${RESET} ${short}`);\n }\n if (r.filesCreated.length > 15) {\n log(` ${DIM} … and ${r.filesCreated.length - 15} more${RESET}`);\n }\n }\n\n // Files edited\n if (r.filesEdited.length > 0) {\n log('');\n log(`${BOLD} Files Edited (${r.filesEdited.length})${RESET}`);\n log(` ${'─'.repeat(58)}`);\n for (const f of r.filesEdited.slice(0, 15)) {\n const short = f.includes(projectName) ? f.split(projectName + '/')[1] ?? f : f;\n log(` ${YELLOW}~${RESET} ${short}`);\n }\n if (r.filesEdited.length > 15) {\n log(` ${DIM} … and ${r.filesEdited.length - 15} more${RESET}`);\n }\n }\n\n // Task completions\n if (r.taskCompletions.length > 0) {\n log('');\n log(`${BOLD} Tasks Completed (${r.taskCompletions.length})${RESET}`);\n log(` ${'─'.repeat(58)}`);\n for (const t of r.taskCompletions) {\n const lines = t.split('\\n');\n const first = lines[0].slice(0, 70);\n log(` ${GREEN}✔${RESET} ${first}${first.length < lines[0].length ? '…' : ''}`);\n }\n }\n\n // Errors\n if (r.errors.length > 0) {\n log('');\n log(`${BOLD} Errors (${r.errors.length})${RESET}`);\n log(` ${'─'.repeat(58)}`);\n for (const e of r.errors.slice(0, 5)) {\n log(` ${RED}✖${RESET} ${e.slice(0, 70)}`);\n }\n if (r.errors.length > 5) {\n log(` ${DIM} … and ${r.errors.length - 5} more${RESET}`);\n }\n }\n\n log('');\n}\n"],"mappings":";AAAA,SAAS,eAAe;;;ACAxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,MAAM,eAAe;AAC9B,SAAS,eAAe;AAiCxB,IAAM,cAAc,KAAK,QAAQ,GAAG,YAAY,eAAe;AAMxD,SAAS,gBAAgB,KAAsB;AACpD,QAAM,SAAS,KAAK,aAAa,KAAK,cAAc;AACpD,MAAI;AACF,WAAO,WAAW,MAAM,KAAK,SAAS,MAAM,EAAE,OAAO;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,aAAa,QAAQ,IAAe;AAClD,MAAI,CAAC,WAAW,WAAW,EAAG,QAAO,CAAC;AAEtC,QAAM,UAAU,YAAY,aAAa,EAAE,eAAe,KAAK,CAAC,EAC7D,OAAO,OAAK,EAAE,YAAY,CAAC;AAE9B,QAAM,OAAqD,CAAC;AAC5D,aAAW,SAAS,SAAS;AAC3B,UAAM,UAAU,KAAK,aAAa,MAAM,IAAI;AAC5C,QAAI,CAAC,WAAW,KAAK,SAAS,cAAc,CAAC,EAAG;AAChD,QAAI;AACF,YAAM,OAAO,SAAS,OAAO;AAC7B,WAAK,KAAK,EAAE,IAAI,MAAM,MAAM,KAAK,SAAS,OAAO,KAAK,QAAQ,CAAC;AAAA,IACjE,QAAQ;AAAA,IAAa;AAAA,EACvB;AAEA,OAAK,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ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;AAAA,IAC3D;AAAA,EACF;AAEA,MAAI,EAAE;AACR;;;Ad/LA,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,eAAe,EACpB,QAAQ,OAAO,EACf,YAAY,wFAAmF;AAElG,sBAAsB,OAAO;AAC7B,qBAAqB,OAAO;AAC5B,mBAAmB,OAAO;AAC1B,yBAAyB,OAAO;AAChC,wBAAwB,OAAO;AAC/B,sBAAsB,OAAO;AAE7B,QAAQ,MAAM;","names":["execSync","resolve","execSync","resolve","program","program","sleep","existsSync","readFileSync","readdirSync","join","resolve","execSync","mkdirSync","readFileSync","join","homedir","existsSync","join","resolve","execSync","resolve","existsSync","program","join","homedir","program","join","homedir","sleep","existsSync","mkdirSync","join","resolve","homedir","program","resolve","join","existsSync","homedir","mkdirSync","resolve","program","resolve"]}
|