architecture-harness 0.29.1 → 0.29.3
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/package.json +1 -1
- package/src/cli/comment-watch.mjs +114 -19
- package/src/cli/comment-watch.test.mjs +349 -12
- package/src/cli/fleet-assign.mjs +1 -1
- package/src/cli/fleet-assign.test.mjs +9 -0
- package/src/cli/fleet-github.mjs +2 -1
- package/src/cli/fleet-load.mjs +1 -1
- package/src/cli/fleet-load.test.mjs +37 -0
- package/src/cli/fleet-message.mjs +1 -1
- package/src/cli/fleet-message.test.mjs +1 -1
- package/src/cli/fleet-node.mjs +14 -7
- package/src/cli/fleet-node.test.mjs +74 -6
- package/src/cli/fleet-state.mjs +1 -1
- package/src/cli/fleet-talk.mjs +42 -21
- package/src/cli/fleet-talk.test.mjs +158 -9
- package/src/cli/fleet.mjs +1 -1
- package/src/cli/watch.mjs +3 -2
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Trigger: surface GitHub comments and keep their acknowledgments in a session ledger.
|
|
3
3
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import { fileURLToPath } from "node:url";
|
|
7
8
|
import { load } from "../config.mjs";
|
|
@@ -10,7 +11,7 @@ import { checkoutRootOf } from "./checkout-root.mjs";
|
|
|
10
11
|
import { commonDirOf } from "./ledger.mjs";
|
|
11
12
|
import { originOf } from "./git-read.mjs";
|
|
12
13
|
import { ghCalls, ghCommand, ghMerges } from "./gh-merge-command.mjs";
|
|
13
|
-
import { expandHome, parsePages
|
|
14
|
+
import { expandHome, parsePages } from "./gh-run.mjs";
|
|
14
15
|
import { commandWords } from "./shell-command.mjs";
|
|
15
16
|
|
|
16
17
|
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
@@ -81,7 +82,12 @@ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
|
|
|
81
82
|
};
|
|
82
83
|
const command = call.tool_input?.command ?? "";
|
|
83
84
|
for (const { words, env } of ghCalls(command, parse)) {
|
|
84
|
-
const
|
|
85
|
+
const parsed = { ...ghCommand(words), env };
|
|
86
|
+
const { group, verb, args, repo } = parsed;
|
|
87
|
+
if (group === "api") {
|
|
88
|
+
const match = /^repos\/([^/]+\/[^/]+)\/(issues|pulls)\/(\d+)(?:\/|$)/.exec(apiRequest(parsed)?.endpoint ?? "");
|
|
89
|
+
if (match) add(match[1], Number(match[3]), match[2] === "pulls" ? "pr" : "issue");
|
|
90
|
+
}
|
|
85
91
|
if (!["issue", "pr"].includes(group)) continue;
|
|
86
92
|
const found = fields(args, call.cwd ?? process.cwd(), group === "pr" && verb === "review");
|
|
87
93
|
const repository = found.repo ?? repo ?? env.GH_REPO ?? origin;
|
|
@@ -102,6 +108,11 @@ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
|
|
|
102
108
|
return [...items.values()];
|
|
103
109
|
}
|
|
104
110
|
|
|
111
|
+
// Ledger: a named command reactivates a retired item without invalidating active watches.
|
|
112
|
+
function watch(state, item) {
|
|
113
|
+
state.append({ ...item, retired: false, ...(state.items.get(itemKey(item))?.retired ? { updatedAt: null } : {}) });
|
|
114
|
+
}
|
|
115
|
+
|
|
105
116
|
// Resource: append records so simultaneous hooks preserve each other's watches and acknowledgments.
|
|
106
117
|
function ledger(root, session) {
|
|
107
118
|
if (!session) return null;
|
|
@@ -122,12 +133,16 @@ function ledger(root, session) {
|
|
|
122
133
|
if (record.reviewDone) { reviews.delete(record.reviewDone); continue; }
|
|
123
134
|
if (record.own) { for (const url of record.own) own.add(url); continue; }
|
|
124
135
|
if (record.next) { next = record.next; continue; }
|
|
136
|
+
if (typeof record.retired === "string") { const item = items.get(record.retired); if (item) item.retired = true; continue; }
|
|
125
137
|
const key = itemKey(record);
|
|
126
|
-
const item = items.get(key) ?? { repo: record.repo, number: record.number, seen: new Set(), pending: new Map(), prs: new Set() };
|
|
138
|
+
const item = items.get(key) ?? { repo: record.repo, number: record.number, seen: new Set(), shown: new Set(), pending: new Map(), prs: new Set() };
|
|
127
139
|
if (record.kind) item.kind = record.kind;
|
|
140
|
+
if (record.retired === false) item.retired = false;
|
|
141
|
+
if (record.updatedAt !== undefined) item.updatedAt = record.updatedAt;
|
|
128
142
|
for (const pr of record.prs ?? []) item.prs.add(pr);
|
|
129
143
|
for (const pending of record.pending ?? []) item.pending.set(pending.stamp, pending);
|
|
130
144
|
for (const stamp of record.seen ?? []) item.seen.add(stamp);
|
|
145
|
+
for (const stamp of record.shown ?? []) item.shown.add(stamp);
|
|
131
146
|
items.set(key, item);
|
|
132
147
|
} catch { /* A torn record leaves earlier acknowledgments intact. */ }
|
|
133
148
|
}
|
|
@@ -138,6 +153,20 @@ function ledger(root, session) {
|
|
|
138
153
|
} };
|
|
139
154
|
}
|
|
140
155
|
|
|
156
|
+
const rateLimited = (error) => /rate.?limit|RATE_LIMITED/i.test(String(error));
|
|
157
|
+
const failureReason = (error) => rateLimited(error) ? "rate limit" : ["deadline", "pages", "response"].includes(error.message) ? error.message : "gh";
|
|
158
|
+
|
|
159
|
+
// Resource: retain only a safe failure category from gh stderr.
|
|
160
|
+
function runCommentGh(args, { cwd, env, timeoutMs }) {
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
execFile("gh", args, { cwd, env: { ...process.env, ...env }, encoding: "utf8", windowsHide: true,
|
|
163
|
+
timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
164
|
+
if (error) reject(new Error(rateLimited(stderr) ? "rate limit" : error.killed ? "deadline" : "gh"));
|
|
165
|
+
else resolve(stdout);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
141
170
|
// Resource: bound all gh processes in one invocation to a shared deadline.
|
|
142
171
|
function github(root, config, deadline, run) {
|
|
143
172
|
return async (repo, args) => {
|
|
@@ -166,6 +195,17 @@ async function comments(item, gh) {
|
|
|
166
195
|
return (await Promise.all(endpoints.map(list))).flat();
|
|
167
196
|
}
|
|
168
197
|
|
|
198
|
+
// Fragment: ask for every watched item's metadata in one request per repository.
|
|
199
|
+
async function itemMetadata(repo, items, gh) {
|
|
200
|
+
const [owner, name] = repo.split("/");
|
|
201
|
+
const fields = items.map(item => `item_${item.number}: issueOrPullRequest(number: ${item.number}) { __typename ... on Issue { state updatedAt } ... on PullRequest { state updatedAt } }`).join(" ");
|
|
202
|
+
const result = await gh(repo, ["api", "graphql", "-f", `owner=${owner}`, "-f", `name=${name}`,
|
|
203
|
+
"-f", `query=query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`]);
|
|
204
|
+
if (result.errors?.length) throw new Error(result.errors.some(error => rateLimited(`${error.type} ${error.message}`)) ? "rate limit" : "response");
|
|
205
|
+
if (!result.data?.repository) throw new Error("response");
|
|
206
|
+
return result.data.repository;
|
|
207
|
+
}
|
|
208
|
+
|
|
169
209
|
async function unseen(item, gh, state) {
|
|
170
210
|
const rows = await comments(item, gh);
|
|
171
211
|
for (const marker of state.reviews.values()) {
|
|
@@ -194,8 +234,10 @@ const context = (event, text) => ({ hookSpecificOutput: { hookEventName: event,
|
|
|
194
234
|
// Ledger: retain truncated previews so a full read can acknowledge them from any hook.
|
|
195
235
|
function recordPreview(state, item, fresh, acknowledge = false) {
|
|
196
236
|
const seen = acknowledge ? fresh.filter(({ row }) => !truncated(row)).map(({ stamp }) => stamp) : [];
|
|
197
|
-
const
|
|
198
|
-
|
|
237
|
+
const shown = fresh.filter(({ row }) => truncated(row)).map(({ stamp }) => stamp);
|
|
238
|
+
const pending = fresh.filter(({ row }) => truncated(row) || !acknowledge)
|
|
239
|
+
.map(({ row, stamp }) => ({ stamp, id: row.id, endpoint: row.endpoint, url: row.url, ...(!truncated(row) ? { row } : {}) }));
|
|
240
|
+
if (seen.length || pending.length) state.append({ repo: item.repo, number: item.number, seen, shown, pending });
|
|
199
241
|
}
|
|
200
242
|
|
|
201
243
|
// Ledger: acknowledge only pending comments covered by a successful full read.
|
|
@@ -221,8 +263,10 @@ function apiRequest(command) {
|
|
|
221
263
|
// API flags may precede the endpoint; keep their names with their values.
|
|
222
264
|
const apiWords = command.rest;
|
|
223
265
|
let method;
|
|
266
|
+
let hostname = command.env?.GH_HOST ?? "github.com";
|
|
224
267
|
let write = false;
|
|
225
268
|
let endpoint;
|
|
269
|
+
let endpointHost;
|
|
226
270
|
const values = new Set(["--method", "--field", "--raw-field", "--input", "--header", "--hostname", "--jq", "--template", "--cache", "--preview"]);
|
|
227
271
|
for (let i = 0; i < apiWords.length; i++) {
|
|
228
272
|
const word = apiWords[i];
|
|
@@ -230,6 +274,7 @@ function apiRequest(command) {
|
|
|
230
274
|
if (long && values.has(long[1])) {
|
|
231
275
|
const value = long[2] ?? apiWords[++i];
|
|
232
276
|
if (long[1] === "--method") method = value;
|
|
277
|
+
if (long[1] === "--hostname") hostname = value;
|
|
233
278
|
if (["--field", "--raw-field", "--input"].includes(long[1])) write = true;
|
|
234
279
|
continue;
|
|
235
280
|
}
|
|
@@ -242,8 +287,13 @@ function apiRequest(command) {
|
|
|
242
287
|
}
|
|
243
288
|
continue;
|
|
244
289
|
}
|
|
245
|
-
if (/^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word))
|
|
290
|
+
if (!endpoint && /^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word)) {
|
|
291
|
+
endpointHost = word.startsWith("https://api.github.com/") ? "github.com" : undefined;
|
|
292
|
+
endpoint = word.replace(/^https:\/\/api.github.com\//, "").replace(/^\//, "").split("?")[0].replace(/^repos\/([^/]+\/[^/]+)/, match => match.toLowerCase());
|
|
293
|
+
}
|
|
246
294
|
}
|
|
295
|
+
// Watch identities and comment requests currently cover GitHub.com only.
|
|
296
|
+
if ((endpointHost ?? hostname)?.toLowerCase() !== "github.com") return null;
|
|
247
297
|
return { endpoint, method: method ?? (write ? "POST" : "GET") };
|
|
248
298
|
}
|
|
249
299
|
|
|
@@ -259,7 +309,7 @@ function createdKeys(response, endpoint) {
|
|
|
259
309
|
...createdKeys(response.stdout ?? response.output ?? response.content ?? response.text, endpoint)].filter(Boolean);
|
|
260
310
|
}
|
|
261
311
|
|
|
262
|
-
export async function commentWatch(call, { gh: run =
|
|
312
|
+
export async function commentWatch(call, { gh: run = runCommentGh, merges: mergeTargets } = {}) {
|
|
263
313
|
const root = checkoutRootOf(call.cwd ?? process.cwd());
|
|
264
314
|
if (!root || !call.session_id) return null;
|
|
265
315
|
const event = call.hook_event_name;
|
|
@@ -277,9 +327,9 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
|
|
|
277
327
|
if (call.tool_response?.is_error || call.tool_response?.exit_code > 0) return null;
|
|
278
328
|
const watched = watchedItems(call, origin, parse);
|
|
279
329
|
const prs = [...state.items.values(), ...watched].filter(item => item.kind === "pr");
|
|
280
|
-
for (const item of watched) state
|
|
330
|
+
for (const item of watched) watch(state, { ...item, prs: prs.filter(pr => pr.repo === item.repo).map(itemKey) });
|
|
281
331
|
for (const { words, env } of ghCalls(call.tool_input?.command ?? "", parse)) {
|
|
282
|
-
const command = ghCommand(words);
|
|
332
|
+
const command = { ...ghCommand(words), env };
|
|
283
333
|
const request = apiRequest(command);
|
|
284
334
|
if (request?.method === "POST" && /^repos\/[^/]+\/[^/]+\/(?:issues(?:\/\d+\/comments)?|pulls(?:\/\d+\/(?:comments|reviews))?)$/.test(request.endpoint ?? "")) {
|
|
285
335
|
state.append({ own: createdKeys(call.tool_response, request.endpoint) });
|
|
@@ -297,8 +347,8 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
|
|
|
297
347
|
const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body"]);
|
|
298
348
|
number = pr.number;
|
|
299
349
|
const key = itemKey({ repo, number });
|
|
300
|
-
state
|
|
301
|
-
references(pr.body ?? "", repo, (repo, number) => state
|
|
350
|
+
watch(state, { repo, number, kind: "pr" });
|
|
351
|
+
references(pr.body ?? "", repo, (repo, number) => watch(state, { repo, number, kind: "issue", prs: [key] }), true);
|
|
302
352
|
}
|
|
303
353
|
if (Number.isSafeInteger(number) && ["create", "comment", "review"].includes(command.verb)) {
|
|
304
354
|
const resource = command.verb === "review" ? `pulls/${number}/reviews` : `issues/${number}/comments`;
|
|
@@ -320,16 +370,61 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
|
|
|
320
370
|
}
|
|
321
371
|
if (event === "UserPromptSubmit" || event === "Stop") {
|
|
322
372
|
const lines = [];
|
|
323
|
-
const
|
|
373
|
+
if (event === "UserPromptSubmit") for (const item of state.items.values()) {
|
|
374
|
+
if (!item.retired) continue;
|
|
375
|
+
const pending = [...item.pending.values()].filter(pending => pending.row && !item.seen.has(pending.stamp)).map(({ row, stamp }) => ({ row, stamp }));
|
|
376
|
+
lines.push(...pending.map(({ row }) => describe(item, row)));
|
|
377
|
+
recordPreview(state, item, pending, true);
|
|
378
|
+
}
|
|
379
|
+
const items = [...state.items.values()].filter(item => !item.retired);
|
|
324
380
|
const start = Math.max(0, items.findIndex(item => itemKey(item) === state.next));
|
|
325
|
-
|
|
326
|
-
|
|
381
|
+
const ordered = [...items.slice(start), ...items.slice(0, start)];
|
|
382
|
+
const repos = new Map();
|
|
383
|
+
for (const item of ordered) {
|
|
384
|
+
const repo = item.repo.toLowerCase();
|
|
385
|
+
if (!repos.has(repo)) repos.set(repo, []);
|
|
386
|
+
repos.get(repo).push(item);
|
|
387
|
+
}
|
|
388
|
+
let failed = 0;
|
|
389
|
+
let checked = 0;
|
|
390
|
+
const reasons = new Set();
|
|
391
|
+
let stopped = false;
|
|
392
|
+
const metadataByRepo = new Map();
|
|
393
|
+
const stopAfter = (item) => {
|
|
394
|
+
stopped = true;
|
|
395
|
+
state.append({ next: itemKey(ordered[(ordered.indexOf(item) + 1) % ordered.length]) });
|
|
396
|
+
};
|
|
397
|
+
for (const item of ordered) {
|
|
398
|
+
const repo = item.repo.toLowerCase();
|
|
399
|
+
if (!metadataByRepo.has(repo)) {
|
|
400
|
+
try {
|
|
401
|
+
metadataByRepo.set(repo, { data: await itemMetadata(item.repo, repos.get(repo), gh) });
|
|
402
|
+
} catch (error) {
|
|
403
|
+
metadataByRepo.set(repo, { error });
|
|
404
|
+
}
|
|
405
|
+
}
|
|
327
406
|
try {
|
|
328
|
-
const
|
|
329
|
-
|
|
407
|
+
const { data: metadata, error } = metadataByRepo.get(repo);
|
|
408
|
+
if (error) throw error;
|
|
409
|
+
const info = metadata[`item_${item.number}`];
|
|
410
|
+
if (!info || !["OPEN", "CLOSED", "MERGED"].includes(info.state) || typeof info.updatedAt !== "string" || !info.updatedAt) throw new Error("response");
|
|
411
|
+
if (info.__typename === "PullRequest") item.kind = "pr";
|
|
412
|
+
const changed = info.updatedAt !== item.updatedAt;
|
|
413
|
+
const fresh = changed ? await unseen(item, gh, state)
|
|
414
|
+
: [...item.pending.values()].filter(pending => pending.row && !item.seen.has(pending.stamp)).map(({ row, stamp }) => ({ row, stamp }));
|
|
415
|
+
lines.push(...fresh.filter(({ stamp }) => !item.shown.has(stamp)).map(({ row }) => describe(item, row)));
|
|
330
416
|
recordPreview(state, item, fresh, event === "UserPromptSubmit");
|
|
331
|
-
|
|
332
|
-
|
|
417
|
+
if (changed) state.append({ repo: item.repo, number: item.number, kind: item.kind, updatedAt: info.updatedAt });
|
|
418
|
+
if (["CLOSED", "MERGED"].includes(info.state)) state.append({ retired: itemKey(item) });
|
|
419
|
+
} catch (error) {
|
|
420
|
+
reasons.add(failureReason(error));
|
|
421
|
+
if (rateLimited(error) || error.message === "deadline") { stopAfter(item); break; }
|
|
422
|
+
failed++;
|
|
423
|
+
}
|
|
424
|
+
checked++;
|
|
425
|
+
}
|
|
426
|
+
if (stopped) failed += items.length - checked;
|
|
427
|
+
if (failed) lines.push(`Comment watch: ${failed} items could not be checked (${[...reasons].join(", ")}); retry on the next prompt.`);
|
|
333
428
|
return lines.length ? (event === "Stop" ? { systemMessage: lines.join("\n") } : context(event, lines.join("\n"))) : null;
|
|
334
429
|
}
|
|
335
430
|
if (event === "PreToolUse") {
|
|
@@ -364,7 +459,7 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
|
|
|
364
459
|
}
|
|
365
460
|
add(repo, pr.number, "pr");
|
|
366
461
|
await Promise.all([...targets.values()].map(async target => {
|
|
367
|
-
state
|
|
462
|
+
watch(state, target);
|
|
368
463
|
const item = { ...state.items.get(itemKey(target)), ...target };
|
|
369
464
|
try {
|
|
370
465
|
const fresh = await unseen(item, gh, state);
|