benignswarm 0.12.75 → 0.12.76
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/args.js +3 -3
- package/dist/capabilities.js +41 -0
- package/dist/client.js +7 -2
- package/dist/commands/agent.js +43 -1
- package/dist/commands/hook.js +247 -47
- package/dist/commands/machine.js +23 -1
- package/dist/commands/operator.js +5 -3
- package/dist/commands/watch.js +42 -13
- package/dist/commands/wu.js +65 -22
- package/dist/help.js +10 -8
- package/dist/output.js +1 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -2,9 +2,9 @@ import { parseArgs } from "node:util";
|
|
|
2
2
|
import { CliError } from "./errors.js";
|
|
3
3
|
// These options accept comma-separated collections, so repeating them should
|
|
4
4
|
// append another collection instead of discarding earlier values.
|
|
5
|
-
export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant"];
|
|
6
|
-
export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "for", "until", "reason", "at", "priority"];
|
|
7
|
-
export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel"];
|
|
5
|
+
export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires"];
|
|
6
|
+
export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text"];
|
|
7
|
+
export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel"];
|
|
8
8
|
export function parse(argv) {
|
|
9
9
|
const options = {};
|
|
10
10
|
for (const f of STRING_FLAGS)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
/** Run every declaration and preserve failures as results, so dispatch can explain a missing tool. */
|
|
6
|
+
export function probeCapabilities(definitions, projectDir) {
|
|
7
|
+
return definitions.map((definition) => {
|
|
8
|
+
let cwd = homedir();
|
|
9
|
+
let temporary = null;
|
|
10
|
+
try {
|
|
11
|
+
if (definition.scope === "worktree") {
|
|
12
|
+
temporary = mkdtempSync(join(tmpdir(), "bschat-capability-"));
|
|
13
|
+
const path = join(temporary, "worktree");
|
|
14
|
+
const added = spawnSync("git", ["worktree", "add", "--quiet", "--detach", path, "HEAD"], { cwd: projectDir, encoding: "utf8", timeout: 120_000 });
|
|
15
|
+
if (added.status !== 0)
|
|
16
|
+
throw new Error((added.stderr || added.stdout || "git worktree add failed").trim().split(/\r?\n/, 1)[0]);
|
|
17
|
+
const full = spawnSync("git", ["-C", path, "sparse-checkout", "disable"], { encoding: "utf8", timeout: 30_000 });
|
|
18
|
+
if (full.status !== 0)
|
|
19
|
+
throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
|
|
20
|
+
cwd = path;
|
|
21
|
+
}
|
|
22
|
+
const result = spawnSync("/bin/sh", ["-lc", definition.probe], { cwd, encoding: "utf8", timeout: 60_000, maxBuffer: 64 * 1024 });
|
|
23
|
+
const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim().split(/\r?\n/, 1)[0] ?? "";
|
|
24
|
+
const ok = result.status === 0 && !result.error;
|
|
25
|
+
return { name: definition.name, ok, version: ok ? (result.stdout.trim().split(/\r?\n/, 1)[0]?.slice(0, 200) || null) : null, error: ok ? null : (result.error?.message ?? (output || `probe exited ${result.status}`)).slice(0, 500) };
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
return { name: definition.name, ok: false, version: null, error: error.message.split(/\r?\n/, 1)[0] };
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
if (temporary) {
|
|
32
|
+
try {
|
|
33
|
+
spawnSync("git", ["worktree", "remove", "--force", join(temporary, "worktree")], { cwd: projectDir, encoding: "utf8", timeout: 30_000 });
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -8,11 +8,13 @@ export class Client {
|
|
|
8
8
|
key;
|
|
9
9
|
auto;
|
|
10
10
|
agentName;
|
|
11
|
-
|
|
11
|
+
machineIdentity;
|
|
12
|
+
constructor(url, key, auto, agentName, machineIdentity) {
|
|
12
13
|
this.url = url;
|
|
13
14
|
this.key = key;
|
|
14
15
|
this.auto = auto;
|
|
15
16
|
this.agentName = agentName;
|
|
17
|
+
this.machineIdentity = machineIdentity;
|
|
16
18
|
}
|
|
17
19
|
/**
|
|
18
20
|
* presence: send the X-Bschat-Auto header, which refreshes the agent's automatic status and
|
|
@@ -20,7 +22,8 @@ export class Client {
|
|
|
20
22
|
* by the hook or the watcher, which say nothing about whether the agent is alive.
|
|
21
23
|
*/
|
|
22
24
|
static forAgent(c, model, opts = {}) {
|
|
23
|
-
|
|
25
|
+
const auto = collectAuto({ model, machine: c.machine, effort: resolveEffort(opts.effort, process.env, c.vendor) });
|
|
26
|
+
return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null);
|
|
24
27
|
}
|
|
25
28
|
static forAdmin(c) {
|
|
26
29
|
return new Client(c.url, c.key, null);
|
|
@@ -32,6 +35,8 @@ export class Client {
|
|
|
32
35
|
const h = { authorization: `Bearer ${this.key}`, "user-agent": `bschat-cli/${CLI_VERSION}` };
|
|
33
36
|
if (this.auto)
|
|
34
37
|
h["x-bschat-auto"] = JSON.stringify(this.auto);
|
|
38
|
+
if (this.machineIdentity)
|
|
39
|
+
h["x-bschat-machine"] = this.machineIdentity;
|
|
35
40
|
return h;
|
|
36
41
|
}
|
|
37
42
|
/**
|
package/dist/commands/agent.js
CHANGED
|
@@ -213,6 +213,38 @@ export async function send(p, out) {
|
|
|
213
213
|
}
|
|
214
214
|
export async function read(p, out) {
|
|
215
215
|
const channel = p.positionals[1];
|
|
216
|
+
if (bool(p.flags, "pending")) {
|
|
217
|
+
if (channel)
|
|
218
|
+
throw new CliError("usage", "use either read <channel> or read --pending");
|
|
219
|
+
const { client, creds } = agentClient(p);
|
|
220
|
+
const ref = agentRef(creds);
|
|
221
|
+
const state = readState(ref);
|
|
222
|
+
const pending = state.pending_reads ?? [];
|
|
223
|
+
if (!pending.length) {
|
|
224
|
+
out.print("(no deferred channel reads)", { messages: [], pending: 0 });
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const channelRead = { ...(state.channel_read ?? {}) };
|
|
228
|
+
const messages = [];
|
|
229
|
+
for (const item of pending) {
|
|
230
|
+
let cursor = item.since;
|
|
231
|
+
let finalCursor = cursor;
|
|
232
|
+
for (;;) {
|
|
233
|
+
const qs = new URLSearchParams({ since: String(cursor), limit: "100" });
|
|
234
|
+
const result = await client.call("GET", `/projects/${item.project}/channels/${item.channel}/messages?${qs}`);
|
|
235
|
+
messages.push(...result.messages);
|
|
236
|
+
finalCursor = result.cursor;
|
|
237
|
+
const last = result.messages.length ? result.messages[result.messages.length - 1].seq : undefined;
|
|
238
|
+
if (last === undefined || last <= cursor || last >= result.cursor)
|
|
239
|
+
break;
|
|
240
|
+
cursor = last;
|
|
241
|
+
}
|
|
242
|
+
channelRead[`${item.project}/${item.channel}`] = finalCursor;
|
|
243
|
+
}
|
|
244
|
+
writeState(ref, { ...state, pending_reads: undefined, channel_read: channelRead });
|
|
245
|
+
out.print(`${messages.length ? messages.map(fmtMessage).join("\n") : "(no messages)"}\nRead ${pending.length} deferred channel${pending.length === 1 ? "" : "s"}.`, { messages, pending: pending.length });
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
216
248
|
if (!channel)
|
|
217
249
|
throw new CliError("usage", "read <channel> [--since seq] [--limit n] [--follow]");
|
|
218
250
|
const { client, creds } = agentClient(p);
|
|
@@ -229,7 +261,17 @@ export async function read(p, out) {
|
|
|
229
261
|
const r = await client.call("GET", `/projects/${project}/channels/${channel}/messages?${qs}`);
|
|
230
262
|
const text = r.messages.length ? r.messages.map(fmtMessage).join("\n") : "(no messages)";
|
|
231
263
|
const st = readState(agentRef(creds));
|
|
232
|
-
|
|
264
|
+
const pendingReads = (st.pending_reads ?? []).flatMap((item) => {
|
|
265
|
+
if (item.project !== project || item.channel !== channel || since === undefined || Number(since) > item.since)
|
|
266
|
+
return [item];
|
|
267
|
+
const lastShown = r.messages.length ? Number(r.messages[r.messages.length - 1].seq) : undefined;
|
|
268
|
+
if (lastShown === undefined)
|
|
269
|
+
return r.cursor <= item.since ? [] : [item];
|
|
270
|
+
if (lastShown >= r.cursor)
|
|
271
|
+
return [];
|
|
272
|
+
return lastShown > item.since ? [{ ...item, since: lastShown }] : [item];
|
|
273
|
+
});
|
|
274
|
+
writeState(agentRef(creds), { ...st, channel_read: { ...(st.channel_read ?? {}), [`${project}/${channel}`]: r.cursor }, pending_reads: pendingReads.length ? pendingReads : undefined });
|
|
233
275
|
out.print(`${text}\ncursor: ${r.cursor}`, r);
|
|
234
276
|
}
|
|
235
277
|
function follow(client, path, out) {
|
package/dist/commands/hook.js
CHANGED
|
@@ -21,6 +21,113 @@ function readStdinJson() {
|
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
23
|
const THROTTLE_MS = 20_000;
|
|
24
|
+
const utf8Bytes = (text) => new TextEncoder().encode(text).byteLength;
|
|
25
|
+
const DELIVERY_BUDGET_BYTES = 4000;
|
|
26
|
+
/** Preserve operator messages, then shorten lower-priority content to counted pointers until the complete payload fits. */
|
|
27
|
+
export function budgetDelivery(input) {
|
|
28
|
+
const protectedDirect = input.protectedDirect ?? [];
|
|
29
|
+
const budget = input.budget ?? DELIVERY_BUDGET_BYTES;
|
|
30
|
+
let header = input.header;
|
|
31
|
+
let footer = [...input.footer];
|
|
32
|
+
let itemLabel = "Assigned list items (details: bschat item show <id>):";
|
|
33
|
+
const compose = (direct, items, followed, digest, deferredDirect) => [
|
|
34
|
+
...(input.prefix ?? []), header, ...protectedDirect, ...direct,
|
|
35
|
+
...(deferredDirect ? [deferredDirect] : []),
|
|
36
|
+
...(items.length ? [itemLabel, ...items] : []),
|
|
37
|
+
...(followed ? [followed] : []), ...(digest ? [digest] : []), ...footer, ...(input.suffix ?? []),
|
|
38
|
+
].filter(Boolean).join("\n");
|
|
39
|
+
let direct = input.direct;
|
|
40
|
+
let items = input.items;
|
|
41
|
+
let followed = input.followed.length ? ["Followed channels:", ...input.followed].join("\n") : "";
|
|
42
|
+
let digest = input.digest.length ? `Unread elsewhere: ${input.digest.join("; ")}` : "";
|
|
43
|
+
let deferredDirect = "";
|
|
44
|
+
let text = compose(direct, items, followed, digest, deferredDirect);
|
|
45
|
+
if (utf8Bytes(text) > budget) {
|
|
46
|
+
followed = input.followed.length ? `${input.followed.length} followed-channel messages deferred; read with ${input.readCommand}.` : "";
|
|
47
|
+
digest = input.digest.length ? `${input.digest.length} unread channel summaries deferred; use bschat inbox --unread, then bschat read <channel> --since <seq>.` : "";
|
|
48
|
+
text = compose(direct, items, followed, digest, deferredDirect);
|
|
49
|
+
}
|
|
50
|
+
let itemBytes = items.join("\n");
|
|
51
|
+
if (utf8Bytes(text) > budget && items.length) {
|
|
52
|
+
itemBytes = `${items.length} assigned list item${items.length === 1 ? "" : "s"} deferred; use ${input.itemPointer ?? "bschat inbox --unread, then bschat item show <id>"}.`;
|
|
53
|
+
items = [itemBytes];
|
|
54
|
+
text = compose(direct, items, followed, digest, deferredDirect);
|
|
55
|
+
}
|
|
56
|
+
if (utf8Bytes(text) > budget && direct.length) {
|
|
57
|
+
deferredDirect = `${direct.length} addressed message${direct.length === 1 ? "" : "s"} deferred; read with ${input.directPointer ?? "bschat inbox --unread"}.`;
|
|
58
|
+
direct = [];
|
|
59
|
+
text = compose(direct, items, followed, digest, deferredDirect);
|
|
60
|
+
}
|
|
61
|
+
// A large rules prefix leaves only a small allowance for the envelope. Apply the remaining
|
|
62
|
+
// bytes to every category: keep the full rules, protected operator content and one valid
|
|
63
|
+
// retrieval pointer per deferred kind, while removing labels and prose that duplicate them.
|
|
64
|
+
if (utf8Bytes(text) > budget) {
|
|
65
|
+
footer = [];
|
|
66
|
+
header = "";
|
|
67
|
+
itemLabel = "";
|
|
68
|
+
if (items.length && input.items.length) {
|
|
69
|
+
itemBytes = `${input.items.length} items; ${input.itemPointer ?? "bschat inbox --unread"}`;
|
|
70
|
+
items = [itemBytes];
|
|
71
|
+
}
|
|
72
|
+
if (followed)
|
|
73
|
+
followed = `${input.followed.length} followed messages; ${input.followedPointer ?? input.readCommand}`;
|
|
74
|
+
if (digest)
|
|
75
|
+
digest = `${input.digest.length} unread channels; ${input.digestPointer ?? "bschat inbox --unread"}`;
|
|
76
|
+
if (deferredDirect)
|
|
77
|
+
deferredDirect = `${input.direct.length} messages; ${input.directPointer ?? "bschat inbox --unread"}`;
|
|
78
|
+
text = compose(direct, items, followed, digest, deferredDirect);
|
|
79
|
+
}
|
|
80
|
+
if (utf8Bytes(text) > budget && followed && digest && input.followedPointer === input.digestPointer) {
|
|
81
|
+
followed = `${input.followed.length} followed`;
|
|
82
|
+
digest = `${input.digest.length} unread; ${input.digestPointer}`;
|
|
83
|
+
text = compose(direct, items, followed, digest, deferredDirect);
|
|
84
|
+
}
|
|
85
|
+
if (utf8Bytes(text) > budget && deferredDirect && items.length && input.directPointer === input.itemPointer) {
|
|
86
|
+
itemBytes = `${input.items.length} items`;
|
|
87
|
+
items = [itemBytes];
|
|
88
|
+
text = compose(direct, items, followed, digest, deferredDirect);
|
|
89
|
+
}
|
|
90
|
+
const by_kind = {
|
|
91
|
+
direct: utf8Bytes([...protectedDirect, ...direct, ...(deferredDirect ? [deferredDirect] : [])].join("\n")),
|
|
92
|
+
items: utf8Bytes(itemBytes),
|
|
93
|
+
followed: utf8Bytes(followed),
|
|
94
|
+
digest: utf8Bytes(digest),
|
|
95
|
+
};
|
|
96
|
+
return { text, bytes: utf8Bytes(text), by_kind };
|
|
97
|
+
}
|
|
98
|
+
/** Re-render an update with its complete wrapper/rules included in the same byte budget. */
|
|
99
|
+
export function formatUpdates(u, prefix = [], suffix = []) {
|
|
100
|
+
const commandLines = suffix.filter((line) => /^\s+bschat read\b.*--since\b/.test(line));
|
|
101
|
+
const compactSuffix = commandLines.length > 8
|
|
102
|
+
? [...suffix.filter((line) => !/^\s+bschat read\b.*--since\b/.test(line)), ` ${commandLines.length} channel reads deferred; run bschat read --pending`]
|
|
103
|
+
: suffix;
|
|
104
|
+
const result = budgetDelivery({ ...u.parts, prefix, suffix: compactSuffix });
|
|
105
|
+
return { ...u, text: result.text, delivery: { bytes: result.bytes, by_kind: result.by_kind } };
|
|
106
|
+
}
|
|
107
|
+
/** Budget standalone rules too, and defer their acknowledgement until the selected text is emitted. */
|
|
108
|
+
export function formatHookDelivery(u, standing) {
|
|
109
|
+
let text;
|
|
110
|
+
let by_kind;
|
|
111
|
+
const budget = u?.parts.budget ?? DELIVERY_BUDGET_BYTES;
|
|
112
|
+
if (u) {
|
|
113
|
+
let formatted = formatUpdates(u, standing ? [standing.text] : []);
|
|
114
|
+
if (formatted.delivery.bytes > budget && standing && standing.text !== standing.deferredText) {
|
|
115
|
+
formatted = formatUpdates(u, [standing.deferredText]);
|
|
116
|
+
}
|
|
117
|
+
text = formatted.text;
|
|
118
|
+
by_kind = formatted.delivery.by_kind;
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
const render = (ruleText) => budgetDelivery({ header: "", direct: [], items: [], followed: [], digest: [], footer: [], readCommand: "bschat process", prefix: standing ? [ruleText] : [], budget });
|
|
122
|
+
let rendered = render(standing?.text ?? "");
|
|
123
|
+
if (rendered.bytes > budget && standing && standing.text !== standing.deferredText)
|
|
124
|
+
rendered = render(standing.deferredText);
|
|
125
|
+
text = rendered.text;
|
|
126
|
+
by_kind = rendered.by_kind;
|
|
127
|
+
}
|
|
128
|
+
const acknowledge = !!standing?.acknowledge && text.includes(standing.text) && standing.text !== standing.deferredText;
|
|
129
|
+
return { text, by_kind, acknowledge };
|
|
130
|
+
}
|
|
24
131
|
/**
|
|
25
132
|
* Collects everything new for an identity and advances its cursors. Returns null when nothing
|
|
26
133
|
* is new. Shared by the harness hook and `bschat watch`. Never throws for server/network
|
|
@@ -60,12 +167,17 @@ export async function gatherUpdates(name, opts) {
|
|
|
60
167
|
const channelRead = { ...(state.channel_read ?? {}) };
|
|
61
168
|
const follows = new Set(state.follows ?? []);
|
|
62
169
|
const digest = [];
|
|
170
|
+
const digestCommands = [];
|
|
171
|
+
const digestReads = new Map();
|
|
63
172
|
const followed = [];
|
|
64
173
|
const readCommands = [];
|
|
174
|
+
const pendingReads = new Map();
|
|
65
175
|
try {
|
|
66
176
|
const projects = creds.project ? [creds.project] : ((await client.call("GET", "/me")).projects ?? []).map((x) => x.name);
|
|
67
177
|
for (const project of projects) {
|
|
68
|
-
const
|
|
178
|
+
const since = Object.fromEntries(Object.entries(channelRead).filter(([k]) => k.startsWith(`${project}/`)).map(([k, v]) => [k.slice(project.length + 1), v]));
|
|
179
|
+
const sinceQuery = Object.keys(since).length ? `?since=${encodeURIComponent(JSON.stringify(since))}` : "";
|
|
180
|
+
const { cursors } = await client.call("GET", `/projects/${project}/channels/cursors${sinceQuery}`);
|
|
69
181
|
for (const ch of cursors) {
|
|
70
182
|
const key = `${project}/${ch.name}`;
|
|
71
183
|
const last = channelRead[key];
|
|
@@ -73,7 +185,7 @@ export async function gatherUpdates(name, opts) {
|
|
|
73
185
|
channelRead[key] = ch.cursor;
|
|
74
186
|
continue;
|
|
75
187
|
}
|
|
76
|
-
const unread = ch.cursor - last;
|
|
188
|
+
const unread = ch.unread ?? (ch.cursor - last);
|
|
77
189
|
if (unread <= 0)
|
|
78
190
|
continue;
|
|
79
191
|
// Only followed channels earn a read command in a wake-up. Unfollowed traffic is one digest
|
|
@@ -81,6 +193,7 @@ export async function gatherUpdates(name, opts) {
|
|
|
81
193
|
// that was never for it.
|
|
82
194
|
if (follows.has(key)) {
|
|
83
195
|
readCommands.push(`bschat read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`);
|
|
196
|
+
pendingReads.set(key, { project, channel: ch.name, since: last });
|
|
84
197
|
const r = await client.call("GET", `/projects/${project}/channels/${ch.name}/messages?since=${last}&limit=5`);
|
|
85
198
|
const seen = new Set(messages.map((m) => m.id));
|
|
86
199
|
const others = r.messages.filter((m) => m.agent_name !== creds.agent && !seen.has(m.id));
|
|
@@ -92,7 +205,10 @@ export async function gatherUpdates(name, opts) {
|
|
|
92
205
|
channelRead[key] = shown;
|
|
93
206
|
}
|
|
94
207
|
else {
|
|
95
|
-
|
|
208
|
+
const readCommand = `bschat read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`;
|
|
209
|
+
digestCommands.push(readCommand);
|
|
210
|
+
digestReads.set(key, { project, channel: ch.name, since: last });
|
|
211
|
+
digest.push(`#${ch.name}${creds.project ? "" : ` [${project}]`}: ${unread} unread (${readCommand})`);
|
|
96
212
|
}
|
|
97
213
|
}
|
|
98
214
|
}
|
|
@@ -101,13 +217,24 @@ export async function gatherUpdates(name, opts) {
|
|
|
101
217
|
process.stderr.write(`bschat: channels: ${e.message}\n`);
|
|
102
218
|
}
|
|
103
219
|
next.channel_read = channelRead;
|
|
220
|
+
const deferredReads = readCommands.length > 8 ? [...pendingReads.values()].slice(8) : [];
|
|
221
|
+
const pendingBacklog = [...pendingReads.values(), ...digestReads.values()];
|
|
222
|
+
if (pendingBacklog.length) {
|
|
223
|
+
const combined = new Map((state.pending_reads ?? []).map((item) => [`${item.project}/${item.channel}`, item]));
|
|
224
|
+
for (const item of pendingBacklog) {
|
|
225
|
+
const key = `${item.project}/${item.channel}`;
|
|
226
|
+
const previous = combined.get(key);
|
|
227
|
+
combined.set(key, previous ? { ...item, since: Math.min(previous.since, item.since) } : item);
|
|
228
|
+
}
|
|
229
|
+
next.pending_reads = [...combined.values()];
|
|
230
|
+
}
|
|
104
231
|
if (opts.dryRun) {
|
|
105
232
|
// Persist only the baselines of channels never seen before; everything else stays unread.
|
|
106
233
|
const merged = { ...(state.channel_read ?? {}) };
|
|
107
234
|
for (const [k, v] of Object.entries(channelRead))
|
|
108
235
|
if (merged[k] === undefined)
|
|
109
236
|
merged[k] = v;
|
|
110
|
-
writeState(name, { ...state, channel_read: merged });
|
|
237
|
+
writeState(name, { ...state, channel_read: merged, ...(next.pending_reads ? { pending_reads: next.pending_reads } : {}) });
|
|
111
238
|
}
|
|
112
239
|
else {
|
|
113
240
|
writeState(name, next);
|
|
@@ -115,6 +242,8 @@ export async function gatherUpdates(name, opts) {
|
|
|
115
242
|
if (!messages.length && !items.length && !digest.length && !followed.length)
|
|
116
243
|
return null;
|
|
117
244
|
const lines = messages.map((m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`);
|
|
245
|
+
const protectedDirect = messages.flatMap((m, i) => m.role_name === "human" ? [lines[i]] : []);
|
|
246
|
+
const directLines = messages.flatMap((m, i) => m.role_name === "human" ? [] : [lines[i]]);
|
|
118
247
|
const itemLines = items.map((i) => ` list "${i.list}"${i.project && !creds.project ? ` [${i.project}]` : ""}: [${i.status}] ${i.title} (item ${i.id}, by ${i.updated_by})`);
|
|
119
248
|
const head = [
|
|
120
249
|
messages.length ? `${messages.length} message${messages.length === 1 ? "" : "s"} for you` : null,
|
|
@@ -130,21 +259,42 @@ export async function gatherUpdates(name, opts) {
|
|
|
130
259
|
footer.push(`Nobody addressed you. Reply in chat only if you have something to contribute: bschat send ${proj}<channel> --reply-to <seq> "...".`);
|
|
131
260
|
if (messages.length || followed.length)
|
|
132
261
|
footer.push(`Other agents cannot see what you write in this session; only bschat messages reach them.`);
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
].
|
|
262
|
+
const header = opts.delivery === "watch"
|
|
263
|
+
? `[bschat] Delivered by your BenignSwarm watcher, not typed by the user. ${head} (${name}):`
|
|
264
|
+
: `[bschat] ${head} (${name}) on BenignSwarm:`;
|
|
265
|
+
const budget = opts.delivery === "watch" ? 3500 : opts.continuation ? 3900 : DELIVERY_BUDGET_BYTES;
|
|
266
|
+
// The inbox cursor was advanced when gathering these items. A single explicit time cursor
|
|
267
|
+
// retrieves every deferred addressed message across channels and keeps the pointer within
|
|
268
|
+
// the budget even when the messages span many channels.
|
|
269
|
+
const firstDeferred = messages.filter((m) => m.role_name !== "human").map((m) => m.created_at).sort()[0];
|
|
270
|
+
const firstItemDeferred = items.map((item) => item.updated_at).filter((at) => !!at).sort()[0];
|
|
271
|
+
const firstInboxDeferred = [firstDeferred, firstItemDeferred].filter((at) => !!at).sort()[0];
|
|
272
|
+
const inboxPointer = firstInboxDeferred ? `bschat inbox --after ${new Date(Date.parse(firstInboxDeferred) - 1).toISOString()}` : "bschat inbox --unread";
|
|
273
|
+
const directPointer = firstDeferred ? inboxPointer : "bschat inbox --unread";
|
|
274
|
+
const itemPointer = firstItemDeferred ? inboxPointer : "bschat inbox --unread";
|
|
275
|
+
const followedPointer = pendingReads.size ? "bschat read --pending" : readCommands.join("; ") || "bschat read --pending";
|
|
276
|
+
const parts = { header, protectedDirect, direct: directLines, directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "bschat read --pending" : "bschat inbox --unread", items: itemLines, followed, digest, footer, readCommand: `bschat read <channel> --since <seq>`, budget };
|
|
277
|
+
const delivery = budgetDelivery(parts);
|
|
143
278
|
const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
|
|
144
|
-
const
|
|
279
|
+
const visibleReadCommands = readCommands.slice(0, 8);
|
|
280
|
+
if (deferredReads.length)
|
|
281
|
+
visibleReadCommands.push("bschat read --pending");
|
|
282
|
+
const cmds = [...(messages.length || items.length ? ["bschat inbox --unread"] : []), ...visibleReadCommands];
|
|
145
283
|
const direct = items.length > 0 || messages.some((m) => m.role_name === "human" || !!m.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(m.body));
|
|
146
284
|
const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
|
|
147
|
-
return { text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length }, latestOperatorAt: operator, readCommands: cmds, tier };
|
|
285
|
+
return { text: delivery.text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length }, latestOperatorAt: operator, readCommands: cmds, tier, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
|
|
286
|
+
}
|
|
287
|
+
export async function reportDelivery(name, text, kinds, source = "hook") {
|
|
288
|
+
try {
|
|
289
|
+
const client = Client.forAgent(loadAgent(name), undefined, { presence: false });
|
|
290
|
+
await client.call("POST", "/agents/me/heartbeat", {
|
|
291
|
+
active_at: new Date().toISOString(), source: `bschat-${source}-delivery`, activity: null,
|
|
292
|
+
delivery: { bytes: utf8Bytes(text), by_kind: { ...kinds, rules: Math.max(0, utf8Bytes(text) - Object.values(kinds).reduce((a, b) => a + b, 0)) } },
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
catch (e) {
|
|
296
|
+
process.stderr.write(`bschat: delivery metric failed: ${e.message}\n`);
|
|
297
|
+
}
|
|
148
298
|
}
|
|
149
299
|
/**
|
|
150
300
|
* Harness hook entry point. Prints new items in the format the harness expects for injecting
|
|
@@ -199,44 +349,79 @@ export async function hook(p) {
|
|
|
199
349
|
}
|
|
200
350
|
}
|
|
201
351
|
const u = await gatherUpdates(name, { force: !!p.flags.force, model: str(p.flags, "model") });
|
|
202
|
-
const
|
|
352
|
+
const formatted = formatHookDelivery(u, standing);
|
|
353
|
+
const text = formatted.text;
|
|
203
354
|
if (!text)
|
|
204
355
|
return;
|
|
356
|
+
await reportDelivery(name, text, formatted.by_kind);
|
|
205
357
|
if (harness === "claude-code") {
|
|
206
358
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n");
|
|
207
359
|
}
|
|
208
360
|
else {
|
|
209
361
|
process.stdout.write(text + "\n");
|
|
210
362
|
}
|
|
363
|
+
await acknowledgeStanding(name, standing, formatted.acknowledge);
|
|
211
364
|
}
|
|
212
365
|
/**
|
|
213
366
|
* The role and process the agent must hold after a new session or a compaction, when it has not
|
|
214
367
|
* seen this process version (or always after a compaction). Records that it was shown.
|
|
215
368
|
*/
|
|
216
369
|
async function standingRules(name, compacted) {
|
|
217
|
-
let standing = null;
|
|
218
370
|
try {
|
|
219
371
|
const creds = loadAgent(name);
|
|
220
|
-
const
|
|
221
|
-
const me = await client.call("GET", "/me");
|
|
372
|
+
const me = await Client.forAgent(creds, undefined, { presence: false }).call("GET", "/me");
|
|
222
373
|
const proc = me.process;
|
|
223
|
-
if (proc
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
|
|
230
|
-
].filter(Boolean);
|
|
231
|
-
standing = lines.join("\n");
|
|
232
|
-
if (creds.project && proc.version > 0)
|
|
233
|
-
await client.call("POST", `/projects/${creds.project}/process/ack`, { version: proc.version });
|
|
234
|
-
}
|
|
374
|
+
if (!proc)
|
|
375
|
+
return null;
|
|
376
|
+
const roleIdentity = me.role ? `Your role: ${me.role.name}.` : `You hold no role in ${me.project?.name ?? "this project"}.`;
|
|
377
|
+
const roleLine = me.role ? `${roleIdentity} ${me.role.description}` : roleIdentity;
|
|
378
|
+
const rendered = renderStandingRules(proc, roleLine, compacted, roleIdentity);
|
|
379
|
+
return { ...rendered, version: proc.version, project: creds.project };
|
|
235
380
|
}
|
|
236
381
|
catch (e) {
|
|
237
382
|
process.stderr.write(`bschat: could not fetch role/process: ${e.message}\n`);
|
|
383
|
+
return null;
|
|
238
384
|
}
|
|
239
|
-
|
|
385
|
+
}
|
|
386
|
+
async function acknowledgeStanding(name, standing, emittedFullRules) {
|
|
387
|
+
if (!standing || !emittedFullRules || !standing.acknowledge || !standing.project || standing.version <= 0)
|
|
388
|
+
return;
|
|
389
|
+
try {
|
|
390
|
+
const creds = loadAgent(name);
|
|
391
|
+
await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
|
|
392
|
+
}
|
|
393
|
+
catch (e) {
|
|
394
|
+
process.stderr.write(`bschat: could not acknowledge process rules: ${e.message}\n`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
|
|
398
|
+
const shortRole = roleIdentity ?? (/^Your role: [^.]+\./.exec(roleLine)?.[0] ?? roleLine.slice(0, 300));
|
|
399
|
+
const deferredText = `[bschat] Process v${proc.version}. ${shortRole}\nRole details: bschat me\nRead the current rules: bschat process`;
|
|
400
|
+
const fit = (text, acknowledge) => utf8Bytes(text) > DELIVERY_BUDGET_BYTES
|
|
401
|
+
? { text: deferredText, acknowledge: false, deferredText }
|
|
402
|
+
: { text, acknowledge, deferredText };
|
|
403
|
+
if (compacted)
|
|
404
|
+
return fit(`${roleLine}\nRead the current rules: bschat process`, false);
|
|
405
|
+
if (proc.seen_version === proc.version)
|
|
406
|
+
return fit(`[bschat] Process v${proc.version}. ${roleLine}`, false);
|
|
407
|
+
if (proc.seen_version !== null) {
|
|
408
|
+
const changed = (proc.changes_since_seen ?? []).map((line) => `- ${line}`);
|
|
409
|
+
const rulesChanged = proc.rules_changed_since_seen === true || (proc.changes_since_seen ?? []).some((line) => /^(working agreements|charter) (edited|added|removed)$/.test(line));
|
|
410
|
+
return fit([
|
|
411
|
+
`[bschat] Process v${proc.version}. ${roleLine}`,
|
|
412
|
+
`Changed since you read v${proc.seen_version}:`,
|
|
413
|
+
...(changed.length ? changed : ["- Details: bschat process"]),
|
|
414
|
+
rulesChanged && proc.agreements ? `Current working agreements:\n${proc.agreements}` : null,
|
|
415
|
+
rulesChanged && proc.charter ? `Current charter:\n${proc.charter}` : null,
|
|
416
|
+
].filter(Boolean).join("\n"), true);
|
|
417
|
+
}
|
|
418
|
+
const lines = [
|
|
419
|
+
`[bschat] Your standing role and process.`, roleLine,
|
|
420
|
+
`Process v${proc.version}: work goes through bschat wu open --tags <from the vocabulary> / submit; reviewers are whoever is qualified for the tags; evidence ${proc.definition.require_evidence_to_submit ? "required" : "optional"} before review; max ${proc.definition.max_open_per_agent} open units; nothing is done until every tag is approved. Details: bschat process.`,
|
|
421
|
+
proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
|
|
422
|
+
proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
|
|
423
|
+
].filter(Boolean);
|
|
424
|
+
return fit(lines.join("\n"), true);
|
|
240
425
|
}
|
|
241
426
|
/**
|
|
242
427
|
* Antigravity's hooks (.agents/hooks.json, written by join): SessionStart and PreInvocation inject
|
|
@@ -293,18 +478,26 @@ async function antigravityHook(p) {
|
|
|
293
478
|
if (input?.fullyIdle !== true)
|
|
294
479
|
return out({});
|
|
295
480
|
// Only something addressed to it keeps it going; chatter waits for its next turn.
|
|
296
|
-
const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true });
|
|
481
|
+
const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true, continuation: true });
|
|
297
482
|
if (!peek || (peek.tier !== "direct" && peek.tier !== "role"))
|
|
298
483
|
return out({});
|
|
299
|
-
const u = await gatherUpdates(name, { force: true, delivery: "hook" });
|
|
300
|
-
|
|
484
|
+
const u = await gatherUpdates(name, { force: true, delivery: "hook", continuation: true });
|
|
485
|
+
if (!u)
|
|
486
|
+
return out({});
|
|
487
|
+
const formatted = formatUpdates(u, [], ["Handle these, then carry on with what you were doing."]);
|
|
488
|
+
const reason = formatted.text;
|
|
489
|
+
await reportDelivery(name, reason, formatted.delivery.by_kind);
|
|
490
|
+
return out({ decision: "continue", reason });
|
|
301
491
|
}
|
|
302
492
|
if (event !== "SessionStart" && event !== "PreInvocation")
|
|
303
493
|
return out({});
|
|
304
|
-
const standing = event === "SessionStart" ? await standingRules(name,
|
|
494
|
+
const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
|
|
305
495
|
const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
|
|
306
|
-
const
|
|
307
|
-
|
|
496
|
+
const formatted = formatHookDelivery(u, standing);
|
|
497
|
+
if (formatted.text)
|
|
498
|
+
await reportDelivery(name, formatted.text, formatted.by_kind);
|
|
499
|
+
out(formatted.text ? { injectSteps: [{ systemMessage: { systemMessage: formatted.text } }] } : {});
|
|
500
|
+
await acknowledgeStanding(name, standing, formatted.acknowledge);
|
|
308
501
|
}
|
|
309
502
|
/**
|
|
310
503
|
* Codex's hooks (~/.codex/hooks.json, written by `bschat codex hooks`; Claude Code's format):
|
|
@@ -359,21 +552,28 @@ async function codexHook(p) {
|
|
|
359
552
|
return;
|
|
360
553
|
if (event === "Stop") {
|
|
361
554
|
// Only something addressed to it keeps it going; chatter waits for its next turn.
|
|
362
|
-
const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true });
|
|
555
|
+
const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true, continuation: true });
|
|
363
556
|
if (!peek || (peek.tier !== "direct" && peek.tier !== "role"))
|
|
364
557
|
return;
|
|
365
|
-
const u = await gatherUpdates(name, { force: true, delivery: "hook" });
|
|
366
|
-
if (u)
|
|
367
|
-
|
|
558
|
+
const u = await gatherUpdates(name, { force: true, delivery: "hook", continuation: true });
|
|
559
|
+
if (u) {
|
|
560
|
+
const formatted = formatUpdates(u, [], ["Handle these, then carry on with what you were doing."]);
|
|
561
|
+
const reason = formatted.text;
|
|
562
|
+
await reportDelivery(name, reason, formatted.delivery.by_kind);
|
|
563
|
+
process.stdout.write(JSON.stringify({ decision: "block", reason }) + "\n");
|
|
564
|
+
}
|
|
368
565
|
return;
|
|
369
566
|
}
|
|
370
567
|
if (event !== "SessionStart" && event !== "UserPromptSubmit")
|
|
371
568
|
return;
|
|
372
|
-
const standing = event === "SessionStart" ? await standingRules(name,
|
|
569
|
+
const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
|
|
373
570
|
const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
|
|
374
|
-
const
|
|
375
|
-
if (text)
|
|
376
|
-
|
|
571
|
+
const formatted = formatHookDelivery(u, standing);
|
|
572
|
+
if (formatted.text)
|
|
573
|
+
await reportDelivery(name, formatted.text, formatted.by_kind);
|
|
574
|
+
if (formatted.text)
|
|
575
|
+
context(formatted.text);
|
|
576
|
+
await acknowledgeStanding(name, standing, formatted.acknowledge);
|
|
377
577
|
}
|
|
378
578
|
/** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
|
|
379
579
|
function noteSession(name, harness, transcript, sessionId) {
|
package/dist/commands/machine.js
CHANGED
|
@@ -13,6 +13,7 @@ import { TURN_HARNESSES, claudeFacts, claudeSandbox, probeFor, sessionProcesses
|
|
|
13
13
|
import { readState, writeState } from "../state.js";
|
|
14
14
|
import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
15
15
|
import { CLI_VERSION } from "../version.js";
|
|
16
|
+
import { probeCapabilities } from "../capabilities.js";
|
|
16
17
|
export const machineFile = () => join(configRoot(), "machine.json");
|
|
17
18
|
export function loadMachine() {
|
|
18
19
|
const f = machineFile();
|
|
@@ -60,11 +61,14 @@ export function startArgs(s, thread, writable = []) {
|
|
|
60
61
|
];
|
|
61
62
|
}
|
|
62
63
|
const KEY_CHECK_MS = 10 * 60_000;
|
|
64
|
+
const CAPABILITY_PROBE_MS = 60 * 60_000;
|
|
65
|
+
const lastCapabilityProbe = new Map();
|
|
63
66
|
/** One pass: make what runs here match what the operator declared, then report. */
|
|
64
67
|
export async function reconcile(m, log) {
|
|
65
68
|
const client = Client.raw(m.url, m.key);
|
|
66
69
|
const me = await client.call("GET", "/machines/me");
|
|
67
70
|
const desired = me.sessions;
|
|
71
|
+
const projects = me.projects ?? [];
|
|
68
72
|
const workdir = me.machine?.workdir ?? null;
|
|
69
73
|
const writable = me.machine?.writable ?? [];
|
|
70
74
|
// The maintenance window, for the watchers: they start no new turns while it drains or runs.
|
|
@@ -171,7 +175,25 @@ export async function reconcile(m, log) {
|
|
|
171
175
|
// The daemon's own confirmation that it is holding turns back, and how many are still running.
|
|
172
176
|
maintenance: maintenanceReport(drainingUntil(), out),
|
|
173
177
|
};
|
|
174
|
-
|
|
178
|
+
const capabilities = {};
|
|
179
|
+
const probedProjects = [];
|
|
180
|
+
for (const project of projects) {
|
|
181
|
+
const signature = JSON.stringify(project.capabilities);
|
|
182
|
+
const last = lastCapabilityProbe.get(project.id);
|
|
183
|
+
if (last?.signature === signature && Date.now() - last.at < CAPABILITY_PROBE_MS)
|
|
184
|
+
continue;
|
|
185
|
+
const projectDir = desired.find((s) => s.project_id === project.id && s.dir)?.dir ?? homedir();
|
|
186
|
+
if (!project.capabilities.length)
|
|
187
|
+
continue;
|
|
188
|
+
capabilities[project.id] = probeCapabilities(project.capabilities, projectDir);
|
|
189
|
+
probedProjects.push(project.id);
|
|
190
|
+
log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
|
|
191
|
+
}
|
|
192
|
+
await client.call("POST", "/machines/me/report", { report, sessions: out, capabilities });
|
|
193
|
+
for (const projectId of probedProjects) {
|
|
194
|
+
const declaration = projects.find((p) => p.id === projectId);
|
|
195
|
+
lastCapabilityProbe.set(projectId, { at: Date.now(), signature: JSON.stringify(declaration.capabilities) });
|
|
196
|
+
}
|
|
175
197
|
return { sessions: out, report };
|
|
176
198
|
}
|
|
177
199
|
const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
|
|
@@ -54,6 +54,7 @@ export function editVocabulary(vocab, op, tag, f) {
|
|
|
54
54
|
...(f.evidence !== undefined ? { require_evidence: f.evidence } : {}),
|
|
55
55
|
...(f.rebased !== undefined ? { require_rebased: f.rebased } : {}),
|
|
56
56
|
...(f.expert !== undefined ? { expert_role: f.expert === "none" || f.expert === "" ? null : f.expert } : {}),
|
|
57
|
+
...(f.requires !== undefined ? { requires: f.requires.length ? f.requires : undefined } : {}),
|
|
57
58
|
};
|
|
58
59
|
if (op === "add" && !next.meaning.trim())
|
|
59
60
|
throw new CliError("usage", `a tag needs a meaning, the sentence workers decide by: --meaning ".."`);
|
|
@@ -126,10 +127,11 @@ function describeProcess(r) {
|
|
|
126
127
|
` timing: review SLA ${d.review_sla_minutes} min, takeover ${d.escalate_after_minutes} min, ${d.max_open_per_agent} open / ${d.max_in_progress_per_agent} in progress per agent`,
|
|
127
128
|
` requires: scope ${d.require_scope ? "yes" : "no"}, evidence to submit ${d.require_evidence_to_submit ? "yes" : "no"}; default approver ${d.default_approver_role ?? "none"}; assigners ${d.assigners.join(", ") || "none"}`,
|
|
128
129
|
` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}`,
|
|
130
|
+
` capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
|
|
129
131
|
` steward: ${d.steward.enabled ? "on" : "off"}, quiet ${d.steward.quiet_minutes} min, summary every ${d.steward.summary_minutes} min, ask the operator after ${d.steward.churn_rounds ? `${d.steward.churn_rounds} rounds on one goal` : "(never)"}`,
|
|
130
132
|
` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (bschat-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
|
|
131
133
|
v.length ? `Tags:` : `No tag vocabulary: every unit goes to the default approver.`,
|
|
132
|
-
...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}`),
|
|
134
|
+
...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}${t.requires?.length ? ` · requires ${t.requires.join(", ")}` : ""}`),
|
|
133
135
|
].join("\n");
|
|
134
136
|
}
|
|
135
137
|
export async function processAdmin(action, rest, p, out) {
|
|
@@ -183,9 +185,9 @@ export async function processAdmin(action, rest, p, out) {
|
|
|
183
185
|
case "tag": {
|
|
184
186
|
const [, op, tag] = rest;
|
|
185
187
|
if (!["add", "edit", "remove"].includes(op) || !tag)
|
|
186
|
-
throw new CliError("usage", 'admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role <role>|none]');
|
|
188
|
+
throw new CliError("usage", 'admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role <role>|none] [--requires name,name]');
|
|
187
189
|
const r = await get();
|
|
188
|
-
const vocabulary = editVocabulary(r.vocabulary, op, tag, { meaning: str(p.flags, "meaning"), evidence: yesNo(str(p.flags, "require-evidence"), "require-evidence"), rebased: yesNo(str(p.flags, "require-rebased"), "require-rebased"), expert: str(p.flags, "expert-role") });
|
|
190
|
+
const vocabulary = editVocabulary(r.vocabulary, op, tag, { meaning: str(p.flags, "meaning"), evidence: yesNo(str(p.flags, "require-evidence"), "require-evidence"), rebased: yesNo(str(p.flags, "require-rebased"), "require-rebased"), expert: str(p.flags, "expert-role"), requires: tagList(str(p.flags, "requires")) });
|
|
189
191
|
return publish({ vocabulary }, `tag #${tag.replace(/^#/, "")} ${op === "add" ? "added" : op === "edit" ? "edited" : "removed"}`);
|
|
190
192
|
}
|
|
191
193
|
case "timing":
|
package/dist/commands/watch.js
CHANGED
|
@@ -17,8 +17,14 @@ import { scanProject, unitWorktrees } from "./worktrees.js";
|
|
|
17
17
|
import { formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
|
|
18
18
|
import { CliError } from "../errors.js";
|
|
19
19
|
import { acquireWatchLock } from "../lock.js";
|
|
20
|
-
import { gatherUpdates } from "./hook.js";
|
|
20
|
+
import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
|
|
21
21
|
import { readState, writeState } from "../state.js";
|
|
22
|
+
import { probeCapabilities } from "../capabilities.js";
|
|
23
|
+
/** Reports host probes without refreshing the agent's presence; the host identity is still explicit. */
|
|
24
|
+
export async function reportWatcherCapabilities(creds, project, definitions, cwd = process.cwd()) {
|
|
25
|
+
const results = probeCapabilities(definitions, cwd);
|
|
26
|
+
await Client.forAgent(creds, undefined, { presence: false, machineIdentity: true }).call("POST", `/projects/${project}/agents/me/capabilities`, { results });
|
|
27
|
+
}
|
|
22
28
|
/**
|
|
23
29
|
* Event bridge for harnesses that can be woken from outside (Codex: `codex queue --thread <id>`).
|
|
24
30
|
*
|
|
@@ -109,6 +115,7 @@ export async function watch(p, out) {
|
|
|
109
115
|
// scan on start and then hourly reports worktrees nobody is touching, which agent calls never would.
|
|
110
116
|
const scanCreds = loadAgent(name);
|
|
111
117
|
let lastScan = 0;
|
|
118
|
+
let lastCapabilities = 0;
|
|
112
119
|
// A watcher holding a pending wake-up makes no server call, so a revoked key (the agent moved to
|
|
113
120
|
// another machine) went unnoticed: fabricbios codex-coordinator's kept running on the Mac. Check
|
|
114
121
|
// the key on its own clock.
|
|
@@ -154,6 +161,22 @@ export async function watch(p, out) {
|
|
|
154
161
|
log(`worktree scan skipped: ${e.message}`);
|
|
155
162
|
}
|
|
156
163
|
}
|
|
164
|
+
if (scanCreds.project && Date.now() - lastCapabilities > 3_600_000) {
|
|
165
|
+
try {
|
|
166
|
+
const client = Client.forAgent(scanCreds, undefined, { presence: false });
|
|
167
|
+
const processInfo = await client.call("GET", `/projects/${scanCreds.project}/process`);
|
|
168
|
+
const definitions = (processInfo.process?.definition?.capabilities ?? []);
|
|
169
|
+
if (definitions.length) {
|
|
170
|
+
await reportWatcherCapabilities(scanCreds, scanCreds.project, definitions, process.cwd());
|
|
171
|
+
log(`capabilities: probed ${definitions.length} project requirements`);
|
|
172
|
+
}
|
|
173
|
+
lastCapabilities = Date.now();
|
|
174
|
+
}
|
|
175
|
+
catch (e) {
|
|
176
|
+
lastCapabilities = Date.now();
|
|
177
|
+
log(`capability probe/report failed: ${e.message}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
157
180
|
if (!once && Date.now() - lastKeyCheck > KEY_CHECK_MS) {
|
|
158
181
|
lastKeyCheck = Date.now();
|
|
159
182
|
try {
|
|
@@ -196,6 +219,9 @@ export async function watch(p, out) {
|
|
|
196
219
|
else {
|
|
197
220
|
process.stdout.write(u.text + "\n");
|
|
198
221
|
}
|
|
222
|
+
// Full mode delivers the update payload directly instead of using the wake path, so
|
|
223
|
+
// record the same actual payload bytes and kinds through the hook's existing metric call.
|
|
224
|
+
await reportDelivery(name, u.text, u.delivery.by_kind, "watch");
|
|
199
225
|
}
|
|
200
226
|
else if (once) {
|
|
201
227
|
log("nothing new");
|
|
@@ -277,8 +303,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
|
|
|
277
303
|
}
|
|
278
304
|
const seq = (st.watch_seq ?? 0) + 1;
|
|
279
305
|
const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
|
|
280
|
-
const
|
|
281
|
-
const wake = [
|
|
306
|
+
const wakePrefix = [
|
|
282
307
|
...(turnSink
|
|
283
308
|
? [`[bschat] Turn #${seq}, started by your BenignSwarm watcher because you were idle; not typed by the user. It is already acknowledged.`]
|
|
284
309
|
: [
|
|
@@ -287,17 +312,19 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
|
|
|
287
312
|
]),
|
|
288
313
|
operatorNew ? `A human operator wrote to you directly.` : null,
|
|
289
314
|
processNews ? processLine(lag) : null,
|
|
290
|
-
|
|
315
|
+
].filter(Boolean);
|
|
316
|
+
const wakeSuffix = [
|
|
291
317
|
...(u ? [`Run these, in order, to read it all:`, ...u.readCommands.map((c) => ` ${c}`)] : []),
|
|
292
318
|
`Reply in chat with bschat send, not here. Your role and the project's process: bschat me, bschat process.`,
|
|
293
|
-
]
|
|
319
|
+
];
|
|
320
|
+
const payload = u ? formatUpdates(u, wakePrefix, wakeSuffix) : null;
|
|
321
|
+
const wake = payload?.text ?? [...wakePrefix, "Nothing else is new.", ...wakeSuffix].join("\n");
|
|
294
322
|
const total = u ? u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest : 0;
|
|
295
|
-
//
|
|
296
|
-
//
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink)))
|
|
323
|
+
// Both command templates receive this same bounded text, with the acknowledgement first.
|
|
324
|
+
// `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
|
|
325
|
+
// the acknowledgement, operator note, process pointer, read commands, and delivery body.
|
|
326
|
+
const line = wake;
|
|
327
|
+
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind)))
|
|
301
328
|
return;
|
|
302
329
|
writeState(name, {
|
|
303
330
|
...readState(name),
|
|
@@ -310,7 +337,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
|
|
|
310
337
|
});
|
|
311
338
|
}
|
|
312
339
|
/** Runs the wake command (or prints the wake-up without one). False when the command failed: nothing was delivered. */
|
|
313
|
-
async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink) {
|
|
340
|
+
async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}) {
|
|
314
341
|
if (!exec) {
|
|
315
342
|
process.stdout.write(wake + "\n");
|
|
316
343
|
return true;
|
|
@@ -336,7 +363,9 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
|
|
|
336
363
|
// Tell the server a wake-up was queued, so it can tell a busy agent from a broken wake path
|
|
337
364
|
// (no harness activity long after). A failure here is logged; the agent was woken regardless.
|
|
338
365
|
try {
|
|
339
|
-
|
|
366
|
+
const bytes = new TextEncoder().encode(wake).byteLength;
|
|
367
|
+
const categorized = Object.values(kinds).reduce((a, b) => a + b, 0);
|
|
368
|
+
await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("POST", "/agents/me/wake", { queued_at: new Date().toISOString(), reason: summary.slice(0, 300), tier, seq, delivery: { bytes, by_kind: { ...kinds, watcher: Math.max(0, bytes - categorized) } } });
|
|
340
369
|
}
|
|
341
370
|
catch (e) {
|
|
342
371
|
log(`could not report the wake-up to the server: ${e.message}`);
|
package/dist/commands/wu.js
CHANGED
|
@@ -79,7 +79,7 @@ export async function wu(p, out) {
|
|
|
79
79
|
const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
|
|
80
80
|
const approvals = u.approvals.map((a) => a.name).join(", ");
|
|
81
81
|
return [
|
|
82
|
-
`WU #${u.number} [${u.status}] ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}`,
|
|
82
|
+
`WU #${u.number} [${u.status}] ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
|
|
83
83
|
` owner ${u.owner_name || "unassigned (queued)"}${reviewers ? ` · reviewers ${reviewers}` : ""}${approvals ? ` · approved by ${approvals}` : ""}${u.uncovered?.length ? ` · awaiting ${u.uncovered.map((t) => `#${t}`).join(" ")}` : ""}`,
|
|
84
84
|
u.operator_hold ? ` ON HOLD by ${u.operator_hold.by}: ${u.operator_hold.note} (no verdict and no merge until the owner resubmits or it is released)` : null,
|
|
85
85
|
u.question ? ` QUESTION for ${u.question.level === "expert" ? `a ${u.question.roles.join(" or ")}` : "the operator"} (asked by ${u.question.asked_by}${u.question.passed_by ? `, passed up by ${u.question.passed_by}` : ""}): ${u.question.text}` : null,
|
|
@@ -97,7 +97,7 @@ export async function wu(p, out) {
|
|
|
97
97
|
throw new CliError("usage", 'wu open "<title>" --scope "<what it covers and does not>" [--tags a,b] [--evidence id]');
|
|
98
98
|
// The unit exists first (it needs its number for the branch name), then its worktree is made
|
|
99
99
|
// and recorded exactly as `wu start` would; --here keeps the current checkout.
|
|
100
|
-
const r = await client.call("POST", base, { title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), evidence: list("evidence"), ...branchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null });
|
|
100
|
+
const r = await client.call("POST", base, { title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), requires: list("requires"), evidence: list("evidence"), ...branchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null });
|
|
101
101
|
const n = r.unit.number;
|
|
102
102
|
const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
|
|
103
103
|
const where = branchAndHead(path);
|
|
@@ -112,7 +112,7 @@ export async function wu(p, out) {
|
|
|
112
112
|
if (!title || !to)
|
|
113
113
|
throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--tags a,b] [--evidence id] [--replay-of <n>]');
|
|
114
114
|
const replay = str(p.flags, "replay-of");
|
|
115
|
-
const r = await client.call("POST", `${base}/assign`, { to, title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), evidence: list("evidence"), replay_of: replay ? Number(replay) : null, branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold });
|
|
115
|
+
const r = await client.call("POST", `${base}/assign`, { to, title, scope: str(p.flags, "scope") ?? "", tags: list("tags"), requires: list("requires"), evidence: list("evidence"), replay_of: replay ? Number(replay) : null, branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: !!p.flags.force });
|
|
116
116
|
out.print(`${fmt(r.unit)}\n${r.unit.status === "queued" && r.unit.preferred_name ? `Reserved for ${r.unit.preferred_name}, who is busy: theirs when free, open to any qualified worker after the takeover window (--hold keeps it assigned to them).` : r.unit.status === "queued" ? `Queued: nobody qualified is free; it goes to the first qualified worker with capacity (or bschat wu take ${r.unit.number} --to <agent>).` : `Assigned to ${r.unit.owner_name}; they start it with bschat wu start ${r.unit.number}.`}`, r);
|
|
117
117
|
return;
|
|
118
118
|
}
|
|
@@ -135,11 +135,26 @@ export async function wu(p, out) {
|
|
|
135
135
|
case "start": {
|
|
136
136
|
const n = num();
|
|
137
137
|
const unit = (await client.call("GET", `${base}/${n}`)).unit;
|
|
138
|
+
// Ask the server to refuse queued work before prepareWorktree can create a branch or checkout.
|
|
139
|
+
// This also gives the refusal the canonical take instruction from the server.
|
|
140
|
+
await preflightQueuedStart(client, base, n, unit);
|
|
138
141
|
const def = await processDef();
|
|
139
142
|
const target = unit.target ?? def.merge.target_branch;
|
|
140
|
-
const
|
|
143
|
+
const prepared = prepareWorktree(n, unit, def, p, await checkoutExclude());
|
|
144
|
+
const { path, branch, mode } = prepared;
|
|
141
145
|
const where = branchAndHead(path);
|
|
142
|
-
|
|
146
|
+
let r;
|
|
147
|
+
try {
|
|
148
|
+
r = await client.call("POST", `${base}/${n}/start`, { branch: branch ?? where.branch, head: where.head, worktree: path, mode });
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (prepared.created) {
|
|
152
|
+
const removed = removeWorktreeIfClean(path);
|
|
153
|
+
if (removed.removed && prepared.branchCreated && branch)
|
|
154
|
+
spawnSync("git", ["branch", "-D", branch], { cwd: process.cwd(), encoding: "utf8" });
|
|
155
|
+
}
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
143
158
|
out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from ${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: bschat wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
|
|
144
159
|
return;
|
|
145
160
|
}
|
|
@@ -417,6 +432,11 @@ export async function wu(p, out) {
|
|
|
417
432
|
throw new CliError("usage", "wu open|assign|start [--branch b|--here]|decline|submit|approve|changes|classify|tags|done [--keep-worktree]|abandon|note|ask|rule|propose|show|list");
|
|
418
433
|
}
|
|
419
434
|
}
|
|
435
|
+
/** Queued units have no owner; ask the API to reject before any local worktree is made. */
|
|
436
|
+
export async function preflightQueuedStart(client, base, n, unit) {
|
|
437
|
+
if (unit.status === "queued")
|
|
438
|
+
await client.call("POST", `${base}/${n}/start`, {});
|
|
439
|
+
}
|
|
420
440
|
/** The project's process: the tag vocabulary, who reviews what, requirements, and the working agreements. */
|
|
421
441
|
export async function processCmd(p, out) {
|
|
422
442
|
const name = resolveAgentName(str(p.flags, "as"));
|
|
@@ -432,8 +452,9 @@ export async function processCmd(p, out) {
|
|
|
432
452
|
const whoReviews = (tag) => roles.filter((x) => x.reviews.includes("*") || x.reviews.includes(tag)).map((x) => x.name);
|
|
433
453
|
const lines = [
|
|
434
454
|
`Process v${r.process.version}${r.process.version === 0 ? " (defaults; the operator has not published one)" : ""}`,
|
|
455
|
+
`Machine capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
|
|
435
456
|
vocab.length ? `Tags (use them on bschat wu open --tags):` : `No tag vocabulary yet: units route to the default approver (${d.default_approver_role ?? "none"}).`,
|
|
436
|
-
...vocab.map((t) => ` #${t.name}: ${t.meaning || "(no meaning written)"}${t.require_evidence ? " · requires evidence" : ""}${t.require_rebased ? " · requires a rebased branch" : ""} · reviewed by ${whoReviews(t.name).join(", ") || "NOBODY (the operator must qualify a role)"}`),
|
|
457
|
+
...vocab.map((t) => ` #${t.name}: ${t.meaning || "(no meaning written)"}${t.require_evidence ? " · requires evidence" : ""}${t.require_rebased ? " · requires a rebased branch" : ""}${t.requires?.length ? ` · requires capabilities ${t.requires.join(", ")}` : ""} · reviewed by ${whoReviews(t.name).join(", ") || "NOBODY (the operator must qualify a role)"}`),
|
|
437
458
|
`Untagged units are approved by ${d.default_approver_role ?? "nobody (set a default approver)"}.${d.classification === "classifier" ? ` A ${d.classifier_role} confirms tags before review.` : ""}`,
|
|
438
459
|
`A unit needs a title${d.require_scope ? ", a scope statement" : ""}${d.require_evidence_to_submit ? ", evidence before review" : ""}. Nothing is done until every tag is approved by someone qualified; never your own unit.`,
|
|
439
460
|
`Review SLA ${d.review_sla_minutes} min; after ${d.escalate_after_minutes} min another qualified reviewer takes over. Max ${d.max_open_per_agent} open units per agent. Announcements in #${d.channel}.`,
|
|
@@ -485,7 +506,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
|
|
|
485
506
|
}
|
|
486
507
|
}
|
|
487
508
|
if (p.flags.here)
|
|
488
|
-
return { mode: "here", path: process.cwd(), branch: branchAndHead().branch };
|
|
509
|
+
return { mode: "here", path: process.cwd(), branch: branchAndHead().branch, created: false, branchCreated: false };
|
|
489
510
|
const name = repoName();
|
|
490
511
|
const parent = repoParent();
|
|
491
512
|
if (!name || !parent)
|
|
@@ -494,16 +515,19 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
|
|
|
494
515
|
if (pinned) {
|
|
495
516
|
const existing = worktreeForBranch(pinned);
|
|
496
517
|
const path = existing ?? resolve(parent, `${name}-wu${n}`);
|
|
518
|
+
// ensureWorktree creates local branches when they do not exist; remember that too so a
|
|
519
|
+
// subsequent server refusal can remove every artifact made by this start attempt.
|
|
520
|
+
let branchCreated = !existing && fullSha(pinned) === null;
|
|
497
521
|
// Continuing someone else's branch from another machine: take origin's copy of it when we have none.
|
|
498
522
|
if (!existing && remoteFirst && fullSha(pinned) === null && fetchRef(pinned)) {
|
|
499
523
|
const r = spawnSync("git", ["branch", "--track", pinned, `origin/${pinned}`], { cwd: process.cwd(), encoding: "utf8" });
|
|
500
524
|
if (r.status !== 0)
|
|
501
525
|
throw new CliError("no_branch", `cannot create ${pinned} from origin: ${(r.stderr || r.stdout).trim()}`);
|
|
526
|
+
branchCreated = true;
|
|
502
527
|
log(`created ${pinned} from origin/${pinned}`);
|
|
503
528
|
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
return { mode: "branch", path, branch: pinned };
|
|
529
|
+
const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude) : { created: false };
|
|
530
|
+
return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
|
|
507
531
|
}
|
|
508
532
|
const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
|
|
509
533
|
const branch = `wu/${n}-${slug}`;
|
|
@@ -515,8 +539,9 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
|
|
|
515
539
|
throw new CliError("no_base", `cannot find ${baseRef} as of ${unit.replay.created_at} for the replay`, `git fetch origin ${target} then try again`);
|
|
516
540
|
baseRef = at;
|
|
517
541
|
}
|
|
518
|
-
|
|
519
|
-
|
|
542
|
+
const branchCreated = fullSha(branch) === null;
|
|
543
|
+
const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude);
|
|
544
|
+
return { mode: "fresh", path, branch, created: result.created, branchCreated };
|
|
520
545
|
}
|
|
521
546
|
/** Select the replay commit from the same target ref used to create its worktree. */
|
|
522
547
|
export function replayBaseRef(baseRef, createdAt, cwd = process.cwd()) {
|
|
@@ -538,7 +563,7 @@ export async function milestones(p, out) {
|
|
|
538
563
|
*/
|
|
539
564
|
export async function milestonesWith(client, project, sub, p, out) {
|
|
540
565
|
if (sub === "export") {
|
|
541
|
-
const list = (await client.call("GET", `/projects/${project}/milestones`)).milestones.map((m) => ({ key: m.key, title: m.title, exit: m.exit, ...(m.source ? { source: m.source } : {}), depends_on: m.depends_on, ...(m.priority !== null && m.priority !== undefined ? { priority: m.priority } : {}) }));
|
|
566
|
+
const list = (await client.call("GET", `/projects/${project}/milestones`)).milestones.map((m) => ({ key: m.key, title: m.title, exit: m.exit, ...(m.source ? { source: m.source } : {}), depends_on: m.dependencies ?? m.depends_on, ...(m.priority !== null && m.priority !== undefined ? { priority: m.priority } : {}) }));
|
|
542
567
|
const text = JSON.stringify(list, null, 2) + "\n";
|
|
543
568
|
const file = str(p.flags, "out");
|
|
544
569
|
if (file) {
|
|
@@ -596,20 +621,21 @@ export async function milestoneWith(client, project, sub, key, p, out) {
|
|
|
596
621
|
throw new CliError("not_found", `no milestone ${key}; use milestone add ${key} --title "..."`);
|
|
597
622
|
const title = str(p.flags, "title") ?? existing?.title;
|
|
598
623
|
if (!title)
|
|
599
|
-
throw new CliError("usage", 'milestone add <key> --title "..." [--exit "what done means"] [--source "docs/plan.md#section"] [--depends-on a,b] [--priority n|none] (no exit and no dependencies = a container for ongoing work)');
|
|
600
|
-
const deps = str(p.flags, "depends-on") !== undefined ? (str(p.flags, "depends-on") ?? "").split(",").map((s) => s.trim()).filter(Boolean) : existing?.depends_on ?? [];
|
|
624
|
+
throw new CliError("usage", 'milestone add <key> --title "..." [--exit "what done means"] [--source "docs/plan.md#section"] [--depends-on a,b] [--informs c,d] [--priority n|none] (no exit and no dependencies = a container for ongoing work)');
|
|
625
|
+
const deps = str(p.flags, "depends-on") !== undefined ? (str(p.flags, "depends-on") ?? "").split(",").map((s) => s.trim()).filter(Boolean) : existing?.dependencies?.filter((d) => d.kind === "blocks").map((d) => d.key) ?? existing?.depends_on ?? [];
|
|
626
|
+
const informs = str(p.flags, "informs") !== undefined ? (str(p.flags, "informs") ?? "").split(",").map((s) => s.trim()).filter(Boolean) : existing?.dependencies?.filter((d) => d.kind === "informs").map((d) => d.key) ?? [];
|
|
627
|
+
const dependencies = [...deps.map((key) => ({ key, kind: "blocks" })), ...informs.map((key) => ({ key, kind: "informs" }))];
|
|
601
628
|
const exit = str(p.flags, "exit") ?? existing?.exit ?? "";
|
|
602
629
|
const source = str(p.flags, "source") ?? existing?.source ?? "";
|
|
603
|
-
// --priority <n> (higher first) or none; the steward asks for units only on the highest-priority ready slices.
|
|
604
630
|
const pr = str(p.flags, "priority");
|
|
605
631
|
if (pr !== undefined && pr !== "none" && !/^-?\d+$/.test(pr))
|
|
606
632
|
throw new CliError("usage", "--priority takes a whole number (higher first) or none");
|
|
607
633
|
const priority = pr === undefined ? existing?.priority ?? null : pr === "none" ? null : Number(pr);
|
|
608
|
-
const next = cur.map((m) => ({ key: m.key, title: m.title, exit: m.exit, source: m.source ?? "", depends_on: m.depends_on, priority: m.priority ?? null }));
|
|
634
|
+
const next = cur.map((m) => ({ key: m.key, title: m.title, exit: m.exit, source: m.source ?? "", depends_on: m.dependencies ?? m.depends_on, priority: m.priority ?? null }));
|
|
609
635
|
if (existing)
|
|
610
|
-
Object.assign(next.find((m) => m.key === key), { title, exit, source, depends_on:
|
|
636
|
+
Object.assign(next.find((m) => m.key === key), { title, exit, source, depends_on: dependencies, priority });
|
|
611
637
|
else
|
|
612
|
-
next.push({ key, title, exit, source, depends_on:
|
|
638
|
+
next.push({ key, title, exit, source, depends_on: dependencies, priority });
|
|
613
639
|
const r = await client.call("PUT", `/projects/${project}/milestones`, { milestones: next });
|
|
614
640
|
const m = r.milestones.find((x) => x.key === key);
|
|
615
641
|
out.print(`${sub === "add" ? "Added" : "Updated"} milestone ${m.key}: ${m.title} [${m.ready ? "ready" : `waits on ${m.waiting_on.join(", ")}`}]${!m.exit && !m.depends_on.length ? " (container: never chased)" : ""}`, r);
|
|
@@ -626,7 +652,7 @@ export async function milestoneWith(client, project, sub, key, p, out) {
|
|
|
626
652
|
const note = str(p.flags, "note");
|
|
627
653
|
if (!note)
|
|
628
654
|
throw new CliError("usage", 'milestone close <key> --note "how the exit criterion was met" [--evidence id,id] [--abandon | --defer]');
|
|
629
|
-
const r = await client.call("POST",
|
|
655
|
+
const r = await client.call("POST", "/projects/" + project + "/milestones/" + key + "/close", { how: p.flags.abandon ? "abandoned" : p.flags.defer ? "deferred" : "done", note, waive_informs: str(p.flags, "waive-informs"), evidence: (str(p.flags, "evidence") ?? "").split(",").map((s) => s.trim()).filter(Boolean) });
|
|
630
656
|
out.print(`Milestone ${r.milestone.key} ${r.milestone.status}.`, r);
|
|
631
657
|
return;
|
|
632
658
|
}
|
|
@@ -637,7 +663,7 @@ export async function milestoneWith(client, project, sub, key, p, out) {
|
|
|
637
663
|
throw new CliError("usage", 'milestone verdict <key> --met --note "how the exit criterion is met" [--evidence id,id] or milestone verdict <key> --gaps "what is missing" [--units n,m] [--note ".."] (--units: the units that address the gaps, wherever they live; the slice is reviewed again when they close)');
|
|
638
664
|
const evidence = (str(p.flags, "evidence") ?? "").split(",").map((x) => x.trim().replace(/^evidence:/, "")).filter(Boolean);
|
|
639
665
|
const units = (str(p.flags, "units") ?? "").split(",").map((x) => Number(x.trim().replace(/^#/, ""))).filter((n) => Number.isInteger(n) && n > 0);
|
|
640
|
-
const r = await client.call("POST",
|
|
666
|
+
const r = await client.call("POST", "/projects/" + project + "/milestones/" + key + "/verdict", { met, note: str(p.flags, "note") ?? "", evidence, gaps: gaps ?? "", units, waive_informs: str(p.flags, "waive-informs") });
|
|
641
667
|
out.print(met ? `Milestone ${r.milestone.key} is done; dependent slices that are now ready were announced.` : `Milestone ${r.milestone.key} stays open; the assigners were told the gaps.`, r);
|
|
642
668
|
return;
|
|
643
669
|
}
|
|
@@ -721,7 +747,24 @@ export async function askOperator(p, out) {
|
|
|
721
747
|
const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
|
|
722
748
|
if (!project)
|
|
723
749
|
throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
|
|
724
|
-
const
|
|
750
|
+
const amend = str(p.flags, "amend");
|
|
751
|
+
if (amend) {
|
|
752
|
+
const text = (p.positionals.slice(1).join(" ") || str(p.flags, "question") || "").trim();
|
|
753
|
+
const body = {};
|
|
754
|
+
if (text)
|
|
755
|
+
body.text = text;
|
|
756
|
+
for (const [flag, field] of [["plain", "plain"], ["blocks", "blocks"], ["if-yes", "if_yes"], ["if-no", "if_no"], ["propose", "proposal"]]) {
|
|
757
|
+
const value = str(p.flags, flag);
|
|
758
|
+
if (value !== undefined)
|
|
759
|
+
body[field] = value;
|
|
760
|
+
}
|
|
761
|
+
if (!Object.keys(body).length)
|
|
762
|
+
throw new CliError("usage", "ask-operator --amend <id> [new question] [--plain ...] [--blocks ...] [--if-yes ...] [--if-no ...] [--propose ...]");
|
|
763
|
+
const result = await client.call("POST", "/projects/" + project + "/asks/" + amend + "/amend", body);
|
|
764
|
+
out.print("Amended your open ask " + amend + "; the operator was told.", result);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const text = (p.positionals.slice(1).join(" ") || str(p.flags, "text") || str(p.flags, "question") || "").trim();
|
|
725
768
|
const fields = { plain: str(p.flags, "plain") ?? "", blocks: str(p.flags, "blocks") ?? "", if_yes: str(p.flags, "if-yes") ?? "", if_no: str(p.flags, "if-no") ?? "" };
|
|
726
769
|
const missing = Object.entries({ "--plain": fields.plain, "--blocks": fields.blocks, "--if-yes": fields.if_yes, "--if-no": fields.if_no }).filter(([, v]) => !v.trim()).map(([k]) => k);
|
|
727
770
|
if (!text || missing.length)
|
package/dist/help.js
CHANGED
|
@@ -27,15 +27,15 @@ Agent commands
|
|
|
27
27
|
bschat back clear your away status early
|
|
28
28
|
bschat send <channel> <message...> [--reply-to <seq>] @name, @role:name, @role:* are resolved and validated
|
|
29
29
|
bschat send <channel> --body-file <f|-> multi-line / markdown message from a file or stdin (use this for anything long)
|
|
30
|
-
bschat read <channel> [--since <seq>] [--limit n] [--follow]
|
|
30
|
+
bschat read <channel> [--since <seq>] [--limit n] [--follow] | bschat read --pending
|
|
31
31
|
bschat inbox [--unread] [--after <iso-time>] [--limit n] mentions of you and replies to your messages
|
|
32
32
|
bschat follow <channel> | unfollow <channel> | following followed channels' new messages are injected by the hook;
|
|
33
33
|
other channels appear as a one-line unread digest
|
|
34
34
|
bschat process the project's process: tag vocabulary, who reviews what, requirements, agreements
|
|
35
|
-
bschat wu open "<title>" --scope "..." [--tags a,b] [--evidence id[,id...] ...] [--target <branch>] [--here] open a work unit in its own
|
|
35
|
+
bschat wu open "<title>" --scope "..." [--tags a,b] [--requires cap,cap] [--evidence id[,id...] ...] [--target <branch>] [--here] open a work unit in its own
|
|
36
36
|
worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
|
|
37
37
|
process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
|
|
38
|
-
bschat wu assign "<title>" --to <agent|auto|queue> --scope ".." [--tags a,b] [--replay-of n] hand out a unit (assigner roles);
|
|
38
|
+
bschat wu assign "<title>" --to <agent|auto|queue> --scope ".." [--tags a,b] [--requires cap,cap] [--force] [--replay-of n] hand out a unit (assigner roles);
|
|
39
39
|
auto queues it when nobody qualified is free; queue waits deliberately; naming a
|
|
40
40
|
busy worker reserves it for them (theirs when free, anyone's after the takeover
|
|
41
41
|
window); --hold keeps it assigned to them however long it takes
|
|
@@ -54,12 +54,12 @@ Agent commands
|
|
|
54
54
|
bschat milestones the plan's slices: ready or waiting on which, units done/total; wu open|assign --milestone <key>
|
|
55
55
|
bschat milestones set --file plan.json define or replace the plan (assigner roles or the operator): a JSON list of
|
|
56
56
|
{key, title, exit, depends_on}; existing keys keep their status; cycles are refused
|
|
57
|
-
bschat milestone add <key> --title ".." [--exit ".."] [--source "docs/plan.md#b0"] [--depends-on a,b] [--priority n] add one slice (assigner
|
|
57
|
+
bschat milestone add <key> --title ".." [--exit ".."] [--source "docs/plan.md#b0"] [--depends-on a,b] [--informs c,d] [--priority n] add one slice (assigner
|
|
58
58
|
roles or the operator); --source is where the full brief lives, read only when planning the slice;
|
|
59
59
|
no exit and no dependencies makes a container for ongoing work; milestone edit (or set) <key> amends
|
|
60
60
|
bschat milestone show <key> exit criterion, dependencies, counts; wu milestone <n> <key|none> moves a unit
|
|
61
|
-
bschat milestone close <key> --note ".." [--evidence a,b] [--abandon | --defer] the lead closes a slice against its exit criterion
|
|
62
|
-
bschat milestone verdict <key> --met --note ".." [--evidence a,b] | --gaps ".." [--units n,m] the closure reviewer judges the exit against the evidence; gap units re-trigger the review when they close
|
|
61
|
+
bschat milestone close <key> --note ".." [--evidence a,b] [--abandon | --defer] [--waive-informs ".."] the lead closes a slice against its exit criterion
|
|
62
|
+
bschat milestone verdict <key> --met --note ".." [--evidence a,b] | --gaps ".." [--units n,m] [--waive-informs ".."] the closure reviewer judges the exit against the evidence; gap units re-trigger the review when they close
|
|
63
63
|
bschat milestone gap-units <key> --units n,m name the units (on any slice) that address its last gaps verdict: stops the chase, re-reviews when they close
|
|
64
64
|
bschat milestone review <key> assigner or operator: request a closure review now (the steward does it when the last unit closes)
|
|
65
65
|
bschat lock <name> [--unit n] [--note ..] [--shared] take this machine's <name> (build slot, scratch) or queue; --shared for a project-wide resource (a test board)
|
|
@@ -82,6 +82,8 @@ Agent commands
|
|
|
82
82
|
bschat wu wait <n> --on <m> | --clear owner or assigner: this unit cannot move until #m closes; reminders pause meanwhile
|
|
83
83
|
bschat wu scope <n> --scope ".." --note ".." assigner or operator: amend what a unit covers; recorded and announced
|
|
84
84
|
bschat ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."]
|
|
85
|
+
bschat ask-operator --amend <id> ["new question"] [--plain ".."] [--blocks ".."] [--if-yes ".."] [--if-no ".."] [--propose ".."] amend your own open ask
|
|
86
|
+
bschat ask-operator refuses a second ask naming the same WU; use --amend <id>. Account needs group asks/questions by unit and can answer several together.
|
|
85
87
|
a decision only the operator can make, on their console banner and reported to them; never
|
|
86
88
|
ask in chat. --plain: one or two sentences for someone who has not read the thread;
|
|
87
89
|
--blocks: what's stuck; --if-yes/--if-no: what happens on each answer
|
|
@@ -196,14 +198,14 @@ bschat-admin login (approve it in your signed-in browser); the session lasts 30
|
|
|
196
198
|
bschat-admin keys [create | revoke <id>] list admin and agent keys; create shows a new admin key once
|
|
197
199
|
bschat-admin process show|export <project> [--out f] the process as agents are told it, or as an editable file
|
|
198
200
|
bschat-admin process set <project> --file process.json publish definition, vocabulary and agreements in one version
|
|
199
|
-
bschat-admin process tag add|edit|remove <project> <tag> [--meaning ..] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none]
|
|
201
|
+
bschat-admin process tag add|edit|remove <project> <tag> [--meaning ..] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name]
|
|
200
202
|
bschat-admin process timing <project> [--sla m] [--takeover m] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--require-cited-changes yes|no] [--default-approver r|none]
|
|
201
203
|
bschat-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no]
|
|
202
204
|
bschat-admin process assigners <project> role1,role2 | agreements <project> --file agreements.md
|
|
203
205
|
bschat-admin process charter <project> --file charter.md how the project weighs trade-offs; sent with every expert question
|
|
204
206
|
bschat-admin process steward <project> on|off [--quiet m] [--summary m] [--churn n] (--churn: ask the operator when a goal is sent back or handed over n times; 0 off)
|
|
205
207
|
bschat-admin milestones <project> [export [--out plan.json] | set --file plan.json] the plan's slices: list, the editable JSON, or replace it (keys keep their status)
|
|
206
|
-
bschat-admin milestone <project> add|edit <key> --title .. [--exit ..] [--source ..] [--depends-on a,b] one slice in, the rest untouched
|
|
208
|
+
bschat-admin milestone <project> add|edit <key> --title .. [--exit ..] [--source ..] [--depends-on a,b] [--informs c,d] one slice in, the rest untouched
|
|
207
209
|
bschat-admin milestone <project> show|review|reopen <key> | close <key> --note .. [--abandon|--defer] | verdict <key> --met|--gaps .. | gap-units <key> --units n,m
|
|
208
210
|
bschat-admin role edit <name> [--project p] --reviews a,b --works c --trials d which tags a role reviews, works and trials ("*" all, "" none)
|
|
209
211
|
bschat-admin needs decisions waiting on you (asks, unit questions, broken wake paths, alert failures)
|
package/dist/output.js
CHANGED
|
@@ -23,6 +23,7 @@ export function fmtStatus(s) {
|
|
|
23
23
|
s.blocked_on ? `blocked_on="${s.blocked_on}"` : null,
|
|
24
24
|
`model=${s.model ?? "-"}`,
|
|
25
25
|
s.machine ? `machine=${s.machine}` : null,
|
|
26
|
+
s.capabilities?.length ? `capabilities=${s.capabilities.map((c) => `${c.name}:${c.ready ? c.version ?? "ok" : c.error ?? "stale/unknown"}`).join(",")}` : null,
|
|
26
27
|
s.branch ? `branch=${s.branch}${s.dirty ? "*" : ""}@${s.head ?? "?"}` : null,
|
|
27
28
|
s.worktree ? `worktree=${s.worktree}` : null,
|
|
28
29
|
`seen=${s.last_seen}`,
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.76";
|