@staix/agent-hub 0.41.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +2 -1
- package/docs/adding-an-ai-tool.md +2 -0
- package/docs/addons/claude-mem.md +1 -1
- package/docs/agent-notes/tasks.md +1 -1
- package/docs/agent-notes/tests.md +1 -1
- package/docs/design/adapters.md +3 -0
- package/docs/design/bus.md +2 -0
- package/docs/design/task-board.md +6 -0
- package/docs/dogfood.md +6 -2
- package/docs/memory.md +8 -6
- package/docs/operations.md +65 -5
- package/docs/quickstart.md +18 -2
- package/docs/sdlc.md +1 -1
- package/docs/security.md +3 -3
- package/docs/verification/2026-11-16-0.42.0.md +48 -0
- package/docs/verification/2026-11-18-0.43.0.md +56 -0
- package/docs/verified.json +23 -23
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +316 -107
- package/plugins/agent-hub/server.js +316 -107
- package/src/adapters/claude-implementer.ts +11 -1
- package/src/adapters/claude-print-child.ts +4 -1
- package/src/adapters/conformance/fakes/acp-server.ts +2 -1
- package/src/adapters/conformance/fakes/app-server.ts +1 -1
- package/src/adapters/local-worker.ts +7 -3
- package/src/adapters/reviewer-print.ts +3 -1
- package/src/cli/agent-attribution.ts +6 -0
- package/src/cli/help.ts +8 -8
- package/src/cli/identity.ts +10 -2
- package/src/cli/main.ts +58 -5
- package/src/cli/memory.ts +21 -6
- package/src/cli/upgrade-output.ts +43 -2
- package/src/cli/upgrade-stopped.ts +162 -0
- package/src/cli/upgrade-wait.ts +37 -0
- package/src/hub/board.ts +4 -2
- package/src/hub/config-apply.ts +1 -0
- package/src/hub/daemon.ts +75 -13
- package/src/hub/envelope.ts +1 -0
- package/src/hub/handoff.ts +14 -0
- package/src/hub/questions.ts +7 -0
- package/src/hub/recovery-store.ts +39 -0
- package/src/hub/research-record.ts +2 -1
- package/src/hub/runtime-capture-prune.ts +114 -3
- package/src/hub/runtime-prune-health.ts +6 -2
- package/src/hub/sdlc-metrics.ts +2 -2
- package/src/hub/settings.ts +2 -0
- package/src/hub/task-sweep.ts +6 -2
- package/src/hub/tasks.ts +8 -3
- package/src/hub/turn-attribution.ts +46 -0
- package/templates/AGENTS.block.md +1 -1
|
@@ -9,6 +9,7 @@ import { childEnv } from "./child-process.ts";
|
|
|
9
9
|
import { hubHome, realPath } from "./project.ts";
|
|
10
10
|
import { readProjectRuntimeReference, projectRuntimeFile } from "./project-runtime-state.ts";
|
|
11
11
|
import { Registry, REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
|
|
12
|
+
import { anyRecoveryHold, retireOperation } from "./recovery-store.ts";
|
|
12
13
|
|
|
13
14
|
export interface RuntimeCapturePrunePlan { remove: string[]; kept: string[]; deferred?: string }
|
|
14
15
|
export interface RuntimeCapturePruneResult { removed: string[]; kept: string[]; quarantined?: string[]; deferred?: string }
|
|
@@ -24,6 +25,13 @@ const MAX_INVENTORY_BYTES = 16 * 1024 * 1024;
|
|
|
24
25
|
// ponytail: larger inventories defer; upgrade to indexed/batched reference inventory, never larger lock/busy limits.
|
|
25
26
|
const MAX_PROJECTS = 128, MAX_RECEIPTS = 128, MAX_CAPTURE_ENTRIES = 512, MAX_REFERENCE_FILES = 512;
|
|
26
27
|
const LOCK_METADATA_MS = 250;
|
|
28
|
+
/** #1541: finished receipts the hub keeps (newest first), and the extra newest-per-selected-runtime ones; both stay far below MAX_RECEIPTS. */
|
|
29
|
+
export const RETAINED_TERMINAL_RECEIPTS = 32, RETAINED_SELECTED_RECEIPTS = 64;
|
|
30
|
+
// ponytail: one pass retires at most this many receipts and reads at most this many directory entries; a larger backlog drains over later passes.
|
|
31
|
+
const MAX_RETIRED_PER_PASS = 256, MAX_RECEIPT_SCAN_ENTRIES = 4096, MAX_RECEIPT_BYTES = 1024 * 1024, MAX_RECEIPT_SCAN_BYTES = 64 * 1024 * 1024;
|
|
32
|
+
const RUNNER_DB = /^[a-f0-9-]{36}\.json\.runner\.db$/;
|
|
33
|
+
/** What a deferral for the receipt ceiling starts with; doctor keys on it to add the retention rule. */
|
|
34
|
+
export const RECEIPT_CEILING_REASON = `recovery receipts exceed the ${MAX_RECEIPTS} receipt safety ceiling`;
|
|
27
35
|
export const RUNTIME_PRUNE_MAX_BATCH = 3;
|
|
28
36
|
export const RUNTIME_PRUNE_INTERVAL_MS = 60 * 60 * 1000;
|
|
29
37
|
const RUNTIME_PRUNE_ADMISSION_BUSY_TIMEOUT_MS = 1;
|
|
@@ -166,14 +174,15 @@ function observeReferences(home: string, registry: Registry): Observation {
|
|
|
166
174
|
observeDatabase(locks, observation, db => { if (db.query("SELECT 1 FROM project_locks LIMIT 1").get()) fail("project recovery coordination is present"); });
|
|
167
175
|
}
|
|
168
176
|
let receipts = 0;
|
|
169
|
-
|
|
177
|
+
const rows = entries(recovery, observation);
|
|
178
|
+
for (const entry of rows) {
|
|
170
179
|
if (!entry.name.endsWith(".json")) continue;
|
|
171
|
-
if (++receipts > MAX_RECEIPTS) fail(
|
|
180
|
+
if (++receipts > MAX_RECEIPTS) fail(receiptCeilingRefusal(recovery, rows));
|
|
172
181
|
if (OPERATION.exec(entry.name)?.[0] !== entry.name || !entry.isFile() || entry.isSymbolicLink()) fail("recovery receipt inventory is invalid");
|
|
173
182
|
const record = metadata(join(recovery, entry.name), observation);
|
|
174
183
|
if (!object(record) || ![1, 2, 3].includes(record.schema as number) || `${record.id}.json` !== entry.name
|
|
175
184
|
|| !["pending", "running", "blocked", "completed", "cancelled"].includes(record.phase as string)) fail("recovery receipt inventory is invalid");
|
|
176
|
-
if (record.phase !== "completed" && record.phase !== "cancelled") fail(
|
|
185
|
+
if (record.phase !== "completed" && record.phase !== "cancelled") fail(`a retained recovery operation is not terminal: run ahub recovery status ${record.id}, then resume or abort it`);
|
|
177
186
|
if (!object(record.plan) || !Array.isArray(record.plan.projects) || !Array.isArray(record.projects)
|
|
178
187
|
|| record.plan.projects.length !== record.projects.length || !["restart", "upgrade"].includes(record.plan.kind as string)
|
|
179
188
|
|| typeof record.plan.sourceDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.plan.sourceDigest)) fail("retained recovery runtime references are incomplete");
|
|
@@ -191,6 +200,21 @@ function observeReferences(home: string, registry: Registry): Observation {
|
|
|
191
200
|
}
|
|
192
201
|
return observation;
|
|
193
202
|
}
|
|
203
|
+
/** AC4: the cause and a supported command. Only open receipts can hold the count above the ceiling, so name the first one found. */
|
|
204
|
+
function receiptCeilingRefusal(recovery: string, rows: Dirent[]): string {
|
|
205
|
+
const scratch: Observation = { files: new Map(), lists: new Map(), projects: "", roots: new Set(), bytes: 0 };
|
|
206
|
+
let first: string | undefined;
|
|
207
|
+
for (const row of rows) {
|
|
208
|
+
if (!row.name.endsWith(".json") || !OPERATION.test(row.name)) continue;
|
|
209
|
+
try {
|
|
210
|
+
const record = metadata(join(recovery, row.name), scratch);
|
|
211
|
+
if (object(record) && record.phase !== "completed" && record.phase !== "cancelled") { first = row.name.slice(0, -".json".length); break; }
|
|
212
|
+
} catch { /* an unreadable receipt is reported by the generic refusal below */ }
|
|
213
|
+
}
|
|
214
|
+
const next = first ? `run ahub recovery status ${first}, then ahub recovery resume ${first} or ahub recovery abort ${first}`
|
|
215
|
+
: "no open receipt was found, so the next maintenance pass (after a hub start, at most hourly) removes the finished ones; ahub recovery status <operation-id> shows one the hub keeps";
|
|
216
|
+
return `${RECEIPT_CEILING_REASON}: the hub keeps open receipts and removes finished ones itself; ${next}`;
|
|
217
|
+
}
|
|
194
218
|
function validateObservation(registry: Registry, observation: Observation, budget: LockBudget): void {
|
|
195
219
|
tick(budget);
|
|
196
220
|
if (JSON.stringify(registry.list()) !== observation.projects) fail("project runtime registry changed before pruning");
|
|
@@ -269,6 +293,92 @@ function openRegistry(home: string): { home: string; registry: Registry } {
|
|
|
269
293
|
const deferred = (error: unknown): string => `runtime capture pruning deferred: ${error instanceof Error ? error.message : "inventory unavailable"}`;
|
|
270
294
|
function checkRetention(keepNewest: number): void { if (!Number.isSafeInteger(keepNewest) || keepNewest < 0) fail("runtime capture retention must be a nonnegative integer"); }
|
|
271
295
|
|
|
296
|
+
interface ReceiptRow { name: string; id: string; at: number; roots: string[] }
|
|
297
|
+
function receiptRoot(value: unknown): string | undefined {
|
|
298
|
+
if (typeof value !== "string" || !isAbsolute(value) || value.includes(String.fromCharCode(0))) return undefined;
|
|
299
|
+
try { return realPath(value); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; return resolve(value); }
|
|
300
|
+
}
|
|
301
|
+
function readReceipt(file: string, budget: { bytes: number }): unknown {
|
|
302
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
303
|
+
try {
|
|
304
|
+
const info = fstatSync(fd);
|
|
305
|
+
if (!info.isFile() || info.nlink !== 1 || info.size > MAX_RECEIPT_BYTES || budget.bytes + info.size > MAX_RECEIPT_SCAN_BYTES) return undefined;
|
|
306
|
+
const bytes = Buffer.alloc(info.size), count = readSync(fd, bytes, 0, info.size, 0);
|
|
307
|
+
if (count !== info.size) return undefined;
|
|
308
|
+
budget.bytes += count;
|
|
309
|
+
try { return JSON.parse(bytes.toString("utf8")); } catch { return undefined; }
|
|
310
|
+
} finally { closeSync(fd); }
|
|
311
|
+
}
|
|
312
|
+
const terminalReceipt = (record: unknown, name: string): record is Record<string, unknown> =>
|
|
313
|
+
object(record) && [1, 2, 3].includes(record.schema as number) && `${record.id}.json` === name && OPERATION.test(name) && (record.phase === "completed" || record.phase === "cancelled");
|
|
314
|
+
/** Runtime roots a registered project's runtime.json (or the live manager) selects, canonical; undefined when any of them cannot be read, which stops retention. */
|
|
315
|
+
function selectedRuntimeRoots(home: string, registry: Registry): string[] | undefined {
|
|
316
|
+
try {
|
|
317
|
+
const roots: string[] = [], projects = registry.list();
|
|
318
|
+
if (projects.length > MAX_PROJECTS) return undefined;
|
|
319
|
+
for (const project of projects) { const runtime = readProjectRuntimeReference(project); if (runtime) roots.push(realPath(runtime.root)); }
|
|
320
|
+
const manager = managerRuntimeRoot(home, { files: new Map(), lists: new Map(), projects: "", roots: new Set(), bytes: 0 });
|
|
321
|
+
if (manager) roots.push(manager);
|
|
322
|
+
return roots;
|
|
323
|
+
} catch { return undefined; }
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* #1541: the hub's own retention rule for finished recovery receipts. Keeps every receipt that is not terminal, the newest
|
|
327
|
+
* RETAINED_TERMINAL_RECEIPTS terminal ones, and the newest RETAINED_SELECTED_RECEIPTS terminal ones that name a runtime a
|
|
328
|
+
* registered project (or the live manager) still selects. The rest leave with their `.runner.db` through
|
|
329
|
+
* `retireOperation` (the exclusive runner claim, never check-then-unlink). The captures themselves stay protected by
|
|
330
|
+
* runtime.json, not by a receipt, so retention never releases one a project selects. Skips everything while any recovery hold exists.
|
|
331
|
+
*/
|
|
332
|
+
export function retireTerminalReceipts(home: string, registry: Registry, hooks: { betweenPair?: () => void } = {}): number {
|
|
333
|
+
const recovery = join(home, "recovery");
|
|
334
|
+
if (!directory(recovery) || anyRecoveryHold(home)) return 0;
|
|
335
|
+
const selected = selectedRuntimeRoots(home, registry);
|
|
336
|
+
if (!selected) return 0;
|
|
337
|
+
const names: string[] = [], handle = opendirSync(recovery);
|
|
338
|
+
try {
|
|
339
|
+
for (;;) {
|
|
340
|
+
const entry = handle.readSync(); if (!entry) break;
|
|
341
|
+
if (names.length >= MAX_RECEIPT_SCAN_ENTRIES) return 0;
|
|
342
|
+
if (entry.isFile() && (entry.name.endsWith(".json") || RUNNER_DB.test(entry.name))) names.push(entry.name);
|
|
343
|
+
}
|
|
344
|
+
} finally { handle.closeSync(); }
|
|
345
|
+
const budget = { bytes: 0 }, terminal: ReceiptRow[] = [], receipts = new Set<string>();
|
|
346
|
+
for (const name of names) {
|
|
347
|
+
if (!name.endsWith(".json")) continue;
|
|
348
|
+
receipts.add(name);
|
|
349
|
+
let record: unknown;
|
|
350
|
+
try { record = readReceipt(join(recovery, name), budget); } catch { continue; }
|
|
351
|
+
if (!terminalReceipt(record, name)) continue; // open, unreadable or unknown receipts always stay
|
|
352
|
+
const roots: string[] = [];
|
|
353
|
+
try {
|
|
354
|
+
for (const value of [record.sourceRoot, object(record.plan) ? record.plan.sourceRoot : undefined, record.targetRoot]) { const root = receiptRoot(value); if (root) roots.push(root); }
|
|
355
|
+
} catch { continue; }
|
|
356
|
+
const at = Number.isFinite(record.updatedAt) ? record.updatedAt as number : Number.isFinite(record.createdAt) ? record.createdAt as number : 0;
|
|
357
|
+
terminal.push({ name, id: record.id as string, at, roots });
|
|
358
|
+
}
|
|
359
|
+
terminal.sort((a, b) => b.at - a.at || b.id.localeCompare(a.id));
|
|
360
|
+
const keep = new Set(terminal.slice(0, RETAINED_TERMINAL_RECEIPTS).map(row => row.name));
|
|
361
|
+
let extra = 0;
|
|
362
|
+
for (const row of terminal) {
|
|
363
|
+
if (extra >= RETAINED_SELECTED_RECEIPTS) break;
|
|
364
|
+
if (keep.has(row.name) || !selected.some(root => row.roots.some(own => contains(root, own) || contains(own, root)))) continue;
|
|
365
|
+
keep.add(row.name); extra++;
|
|
366
|
+
}
|
|
367
|
+
let retired = 0;
|
|
368
|
+
for (const row of terminal) {
|
|
369
|
+
if (keep.has(row.name)) continue;
|
|
370
|
+
if (retired >= MAX_RETIRED_PER_PASS) break;
|
|
371
|
+
const outcome = retireOperation(row.id, home, record => terminalReceipt(record, row.name), hooks);
|
|
372
|
+
if (outcome === "retired") retired++;
|
|
373
|
+
}
|
|
374
|
+
// A runner db whose receipt is gone (an interrupted earlier pass) is settled through the same claim; a live claim keeps it.
|
|
375
|
+
for (const name of names) {
|
|
376
|
+
const receipt = name.replace(/\.runner\.db$/, "");
|
|
377
|
+
if (RUNNER_DB.test(name) && !receipts.has(receipt) && retired < MAX_RETIRED_PER_PASS && retireOperation(receipt.slice(0, -".json".length), home, () => false, hooks) === "retired") retired++;
|
|
378
|
+
}
|
|
379
|
+
return retired;
|
|
380
|
+
}
|
|
381
|
+
|
|
272
382
|
/** Metadata preview only; execution always refreshes reference observations before quarantining each candidate. */
|
|
273
383
|
export function planRuntimeCapturePrune(home = hubHome(), keepNewest = 3): RuntimeCapturePrunePlan {
|
|
274
384
|
let registry: Registry | undefined;
|
|
@@ -283,6 +393,7 @@ export function pruneRuntimeCaptures(home = hubHome(), keepNewest = 3): RuntimeC
|
|
|
283
393
|
const removed: string[] = [], quarantined: string[] = []; let kept: string[] = [], registry: Registry | undefined;
|
|
284
394
|
try {
|
|
285
395
|
checkRetention(keepNewest); const opened = openRegistry(home); registry = opened.registry; home = opened.home;
|
|
396
|
+
retireTerminalReceipts(home, registry);
|
|
286
397
|
const initial = lockedPlan(home, registry, observeReferences(home, registry), keepNewest); kept = initial.plan.kept;
|
|
287
398
|
// Reject unknown layouts across the small batch before moving any entry; no package contents are hashed here.
|
|
288
399
|
for (const root of initial.plan.remove) captureLayout(root);
|
|
@@ -4,12 +4,14 @@ import { isAbsolute, join, normalize } from "node:path";
|
|
|
4
4
|
import { processLiveness } from "../pi/process-signature.ts";
|
|
5
5
|
import { hubHome } from "./project.ts";
|
|
6
6
|
import { REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
|
|
7
|
-
import { RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
|
|
7
|
+
import { RETAINED_SELECTED_RECEIPTS, RETAINED_TERMINAL_RECEIPTS, RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
|
|
8
8
|
|
|
9
9
|
export interface RuntimePruneHealthCheck { ok: boolean | undefined; name: string; detail: string }
|
|
10
10
|
const MAX_LEDGER_BYTES = 1024 * 1024, MAX_OUTCOME_BYTES = 16 * 1024;
|
|
11
11
|
const MAX_SCAN_ENTRIES = 1024, MAX_QUARANTINES = 64, SCAN_MS = 250;
|
|
12
12
|
const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
|
|
13
|
+
/** #1541: the one retention rule, as docs/operations.md states it. */
|
|
14
|
+
export const RECEIPT_RETENTION_RULE = `Retention: maintenance keeps every open recovery receipt, the newest ${RETAINED_TERMINAL_RECEIPTS} finished ones and up to ${RETAINED_SELECTED_RECEIPTS} finished ones naming a runtime a project still selects, and removes older finished ones with their runner database itself`;
|
|
13
15
|
const columns = "slot,id,admitted_at,phase,pid,outcome";
|
|
14
16
|
const issue = (detail: string, ok: boolean | undefined = undefined): RuntimePruneHealthCheck => ({ ok, name: "runtime pruning", detail });
|
|
15
17
|
const info = (file: string): Stats | undefined => {
|
|
@@ -63,7 +65,9 @@ function admissionHealth(file: string): LedgerHealth {
|
|
|
63
65
|
|| outcome.quarantined.some(value => typeof value !== "string" || value.length > 4096 || isAbsolute(value) || normalize(value) !== value || value.split(/[\\/]/).some(part => part === ".."))
|
|
64
66
|
|| outcome.deferred !== undefined && (typeof outcome.deferred !== "string" || Buffer.byteLength(outcome.deferred) > 512)) throw new Error("invalid completed outcome");
|
|
65
67
|
if (outcome.deferred !== undefined || outcome.quarantined.length) {
|
|
66
|
-
|
|
68
|
+
// #1541: a deferral that already names a supported command (the receipt ceiling, an open operation) is not sent to the ledger.
|
|
69
|
+
const text = typeof outcome.deferred === "string" ? outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ") : undefined;
|
|
70
|
+
const detail = text !== undefined ? `maintenance deferred: ${text}${text.includes("ahub recovery") ? `. ${RECEIPT_RETENTION_RULE}` : `; inspect ${file}`}` : `maintenance retained quarantine paths; inspect ${file}`;
|
|
67
71
|
return { active: false, checks: [issue(detail, false)] };
|
|
68
72
|
}
|
|
69
73
|
return { checks: [], active: false };
|
package/src/hub/sdlc-metrics.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type BandTier = typeof BAND_TIERS[number];
|
|
|
14
14
|
export interface MetricTask {
|
|
15
15
|
id: number;
|
|
16
16
|
private?: boolean;
|
|
17
|
-
/** `evidenceOnly` marks a code-scope verdict with no open finding (#852): it is not a rework round. `requestHead` is the head a `done` asked review for (
|
|
17
|
+
/** `evidenceOnly` marks a code-scope verdict with no open finding (#852): it is not a rework round. `requestHead` is the head a `done` asked review for (requestHead, with historical fallbacks); `verdictHead` the head a verdict was bound to (reviewFindings.head). Compared for equality only, never printed. */
|
|
18
18
|
history: { at: number; event: string; requestHead?: string; verdictHead?: string; evidenceOnly?: true }[];
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -84,7 +84,7 @@ const VERDICTS = ["approved", "changes_requested"];
|
|
|
84
84
|
* Review rounds whose verdict was bound to a different head than the review was requested for: the head moved while the review ran.
|
|
85
85
|
* Known only for a round with both heads recorded; a task with no such round is unknown, never 0. (A `done` after an `approved` is not
|
|
86
86
|
* evidence: the board cannot produce one.)
|
|
87
|
-
* ponytail: the request head is
|
|
87
|
+
* ponytail: the request head is the commit recorded for the done while a verdict's head prefers the lifecycle receipt's
|
|
88
88
|
* `head`/`localHead` over `refs.commit` (`findingHead`), so a receipt head that differs from the commit can read as stale. Ceiling: a
|
|
89
89
|
* spurious stale round for a task whose receipt head and commit disagree; the upgrade is one shared head rule for both sides.
|
|
90
90
|
*/
|
package/src/hub/settings.ts
CHANGED
|
@@ -58,6 +58,7 @@ const perClass = (name: TaskClass): SettingDef[] => [
|
|
|
58
58
|
{ key: `routing.classes.${name}.pi_backend`, group: "Routing", label: `${name}: Pi backend`, type: "enum", values: ["dgx", "mlx"], store: "routing", applies: "live", risk: "raises", path: ["classes", name, "pi_backend"] },
|
|
59
59
|
];
|
|
60
60
|
export const SETTINGS: readonly SettingDef[] = [
|
|
61
|
+
{ key: "memory.sync_interval_min", group: "Switches", label: "Memory sync interval in minutes (0 disables)", type: "integer", min: 0, max: 1440, store: "config", applies: "live", risk: "raises", path: ["memory", "sync_interval_min"] },
|
|
61
62
|
...["enabled", "auto_reassign"].map((key): SettingDef => ({ key: `task_sweep.${key}`, group: "Switches", label: `Task sweep: ${key}`, type: "boolean", store: "config", applies: "live", risk: "raises", floor: false, path: ["task_sweep", key] })),
|
|
62
63
|
{ key: "task_sweep.no_writes_turns", group: "Switches", label: "Consecutive owner turns without writes (0 disables)", type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, store: "config", applies: "live", risk: "raises", path: ["task_sweep", "no_writes_turns"] },
|
|
63
64
|
...["interval_s", "unaccepted_min", "idle_min", "review_min", "ready_min", "ladder_min"].map((key): SettingDef => ({ key: `task_sweep.${key}`, group: "Switches", label: `Task sweep: ${key}`, type: "number", min: 1, max: 2_147_483_647 / (key === "interval_s" ? 1000 : 60_000), store: "config", applies: "live", risk: "raises", path: ["task_sweep", key] })),
|
|
@@ -193,6 +194,7 @@ export function checkSettingValue(def: SettingDef, raw: unknown, routes: readonl
|
|
|
193
194
|
if (def.store === "runtime") throw new Error(`${def.key} has no stored value to remove`);
|
|
194
195
|
return null;
|
|
195
196
|
}
|
|
197
|
+
if (def.key === "memory.sync_interval_min" && (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0 || raw > 1440)) throw new Error("memory.sync_interval_min must be 0 (off) or a whole number of minutes up to 1440");
|
|
196
198
|
if (def.type === "number-or-off" && raw === "off") return raw;
|
|
197
199
|
if (def.type === "integer" || def.type === "number" || def.type === "number-or-off") {
|
|
198
200
|
if (typeof raw !== "number" || !(def.type === "integer" ? Number.isSafeInteger(raw) : Number.isFinite(raw)) || raw < (def.min ?? 0) || raw > (def.max ?? Number.MAX_SAFE_INTEGER)) throw new Error(`${def.key} takes ${def.type === "integer" ? "an integer" : def.type === "number-or-off" ? "off or a finite number" : "a number"} from ${def.min ?? 0} to ${def.max ?? Number.MAX_SAFE_INTEGER}`);
|
package/src/hub/task-sweep.ts
CHANGED
|
@@ -50,7 +50,7 @@ export function taskSweepConfig(input: unknown): TaskSweepConfig {
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/** Pure time/kind ladder; Tasks decides whether the responsible peer is available. */
|
|
53
|
-
export function nextSweep(task: Task, config: TaskSweepConfig, now: number, ready = true): SweepRecord | undefined {
|
|
53
|
+
export function nextSweep(task: Task, config: TaskSweepConfig, now: number, ready = true, questionWait?: { open: boolean; settled?: number }): SweepRecord | undefined {
|
|
54
54
|
if (!config.enabled || !Number.isFinite(now)) return undefined;
|
|
55
55
|
// #1176: a person-run leg waits on the person, so no idle step ever escalates it to an agent.
|
|
56
56
|
if (task.needsPerson) return undefined;
|
|
@@ -61,7 +61,10 @@ export function nextSweep(task: Task, config: TaskSweepConfig, now: number, read
|
|
|
61
61
|
let activity = task.history.length - 1;
|
|
62
62
|
while (activity >= 0 && (task.history[activity]?.sweep || task.history[activity]?.event === "memory reference started")) activity--;
|
|
63
63
|
let at = task.history[activity]?.at ?? task.created;
|
|
64
|
+
let questionSettled: number | undefined;
|
|
64
65
|
if (kind === "idle-owner") {
|
|
66
|
+
if (questionWait?.open) return undefined;
|
|
67
|
+
if (questionWait?.settled !== undefined && questionWait.settled > at) { questionSettled = questionWait.settled; at = questionSettled; }
|
|
65
68
|
// #1454: a pending wait suspends the ladder; once it passes, the ladder restarts from `until`, not from the activity before it.
|
|
66
69
|
const wait = taskWait(task);
|
|
67
70
|
if (wait) {
|
|
@@ -71,7 +74,8 @@ export function nextSweep(task: Task, config: TaskSweepConfig, now: number, read
|
|
|
71
74
|
}
|
|
72
75
|
const threshold = kind === "ready-unassigned" ? config.ready_min ?? 60 : kind === "unaccepted-assignment" ? config.unaccepted_min : kind === "idle-owner" ? config.idle_min : config.review_min;
|
|
73
76
|
if (now - at < threshold * 60_000) return undefined;
|
|
74
|
-
|
|
77
|
+
let previous = task.history.flatMap((h) => h.sweep?.kind === kind && h.sweep.activity === activity ? [h.sweep] : []).at(-1);
|
|
78
|
+
if (questionSettled !== undefined && previous && previous.at <= questionSettled) previous = undefined;
|
|
75
79
|
if (previous && (previous.step === 3 || now - previous.at < config.ladder_min * 60_000)) return undefined;
|
|
76
80
|
return { kind, activity, step: previous ? (previous.step + 1) as 2 | 3 : 1, at: now };
|
|
77
81
|
}
|
package/src/hub/tasks.ts
CHANGED
|
@@ -167,6 +167,8 @@ export interface AuditView extends AuditSummary {
|
|
|
167
167
|
notUpdated?: string[];
|
|
168
168
|
}
|
|
169
169
|
export interface TasksDeps {
|
|
170
|
+
/** Timing-only owner question evidence for the idle-owner ladder. */
|
|
171
|
+
ownerQuestionWait?: (task: number, peer: PeerId) => { open: boolean; settled?: number } | undefined;
|
|
170
172
|
/** Private host-owned probe ledger and fixture ports. No configuration, wire or model-selected runner. */
|
|
171
173
|
guidanceProbes?: {
|
|
172
174
|
store: GuidanceProbeStore;
|
|
@@ -974,7 +976,8 @@ export class Tasks {
|
|
|
974
976
|
for (const task of this.d.board.list()) {
|
|
975
977
|
if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break;
|
|
976
978
|
if (!task.owner && this.personUnassigned(task)) continue;
|
|
977
|
-
const
|
|
979
|
+
const questionWait = task.state === "in_progress" && task.owner ? this.d.ownerQuestionWait?.(task.id, task.owner) : undefined;
|
|
980
|
+
const finding = nextSweep(task, config, now, this.waitsFor(task).length === 0 && !plannedStartPending(task, now), questionWait);
|
|
978
981
|
if (!finding || this.waitsFor(task).length || this.isChecking(task.id) || this.silentFor(task.id)) continue;
|
|
979
982
|
if (finding.kind === "ready-unassigned") {
|
|
980
983
|
this.d.board.update(task.id, HUB, "idle sweep", {}, undefined, { sweep: finding });
|
|
@@ -6775,7 +6778,7 @@ export class Tasks {
|
|
|
6775
6778
|
}
|
|
6776
6779
|
const rows = this.d.board.list();
|
|
6777
6780
|
const tasks: MetricTask[] = rows.map(task => ({ id: task.id, private: this.isPii(task), history: task.history.map(entry => ({ at: entry.at, event: entry.event,
|
|
6778
|
-
...(entry.reviewCost?.head ? { requestHead: entry.reviewCost.head } : {}), ...(entry.reviewFindings?.head ? { verdictHead: entry.reviewFindings.head } : {}), ...(entry.evidenceOnly ? { evidenceOnly: true as const } : {}) })) }));
|
|
6781
|
+
...(entry.event === "done" && (entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head) ? { requestHead: entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head } : {}), ...(entry.reviewFindings?.head ? { verdictHead: entry.reviewFindings.head } : {}), ...(entry.evidenceOnly ? { evidenceOnly: true as const } : {}) })) }));
|
|
6779
6782
|
const visibleIds = new Set(rows.filter(task => !this.isPii(task)).map(task => task.id));
|
|
6780
6783
|
const byKind: Record<string, number> = {};
|
|
6781
6784
|
for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1;
|
|
@@ -9138,6 +9141,8 @@ export class Tasks {
|
|
|
9138
9141
|
if (specInspection?.report?.head && !completedRefs.commit) completedRefs.commit = specInspection.report.head;
|
|
9139
9142
|
if (specInspection?.report && specInspection.repo && !completedRefs.repo) completedRefs.repo = specInspection.repo;
|
|
9140
9143
|
const storedRefs = { ...task.refs, ...completedRefs };
|
|
9144
|
+
const requestedHead = completedRefs.commit ?? admission?.head ?? specInspection?.report?.head;
|
|
9145
|
+
const requestHead = requestedHead && /^[a-f0-9]{40}$/.test(requestedHead) ? requestedHead : undefined;
|
|
9141
9146
|
if (specInspection) {
|
|
9142
9147
|
if (asyncCheckCompletion) {
|
|
9143
9148
|
if (this.refreshAsyncSpecInspection(specInspection, { ...task, refs: storedRefs }, by)) { this.requestSpecRefile(task); return task; }
|
|
@@ -9148,7 +9153,7 @@ export class Tasks {
|
|
|
9148
9153
|
const capacity = this.capacityBefore(task);
|
|
9149
9154
|
reviewObserverExcluded ||= this.reviewObserverTurn(by, task.id);
|
|
9150
9155
|
const quotaWaiting = selection?.reviewSelection?.quotaWait !== undefined;
|
|
9151
|
-
const next = this.d.board.update(task.id, by, "done", { codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), state: reviewer ? "in_review" : "approved", ...(selection || refresh?.state === "approved" ? { reviewer: quotaWaiting ? null : reviewer ?? USER } : {}), ...(task.sdlc ? { sdlc: { ...task.sdlc, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), reviewer ? "review" : "merge") } } : {}), refs: completedRefs }, checkOutput ? `${routedSummary ?? ""}\n${checkOutput}`.trim() : routedSummary, { ...(resolvedReviewComments?.length ? { resolvedReviewComments: this.reviewCommentResolve(by, task, resolvedReviewComments) } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(specInspection?.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}), ...(noWrites ? { noWrites: true as const } : {}), ...this.reviewMetadata(selection, { ...task, state: "in_review", refs: storedRefs }), ...(reviewCost ? { reviewCost } : {}), ...(records ? { deliverables: records } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
|
|
9156
|
+
const next = this.d.board.update(task.id, by, "done", { codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), state: reviewer ? "in_review" : "approved", ...(selection || refresh?.state === "approved" ? { reviewer: quotaWaiting ? null : reviewer ?? USER } : {}), ...(task.sdlc ? { sdlc: { ...task.sdlc, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), reviewer ? "review" : "merge") } } : {}), refs: completedRefs }, checkOutput ? `${routedSummary ?? ""}\n${checkOutput}`.trim() : routedSummary, { ...(resolvedReviewComments?.length ? { resolvedReviewComments: this.reviewCommentResolve(by, task, resolvedReviewComments) } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(specInspection?.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}), ...(noWrites ? { noWrites: true as const } : {}), ...this.reviewMetadata(selection, { ...task, state: "in_review", refs: storedRefs }), ...(reviewCost ? { reviewCost } : {}), ...(requestHead ? { requestHead } : {}), ...(records ? { deliverables: records } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
|
|
9152
9157
|
this.queueReviewWritten(next);
|
|
9153
9158
|
this.writePlannerNotices(next, capacity, next.state === "approved");
|
|
9154
9159
|
this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id); // a newer head or a move ends the old head's watcher (#785 P1b)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { HUB, USER, type Envelope } from "./envelope.ts";
|
|
2
|
+
|
|
3
|
+
export type TurnTrigger = "assign" | "review" | "message" | "manual" | "schedule";
|
|
4
|
+
export interface TurnAttribution { task?: number; attempt?: string; trigger?: TurnTrigger; private?: boolean; cloud?: boolean }
|
|
5
|
+
|
|
6
|
+
/** Hints are not authority: only emit a task when the host's turn context is unambiguous. */
|
|
7
|
+
export function turnAttribution(envs: readonly Envelope[], options: { task?: number; cloud?: boolean; scheduled?: (task: number) => boolean | undefined } = {}): TurnAttribution {
|
|
8
|
+
let invalidTask = false;
|
|
9
|
+
const refs = new Set(envs.flatMap(env => {
|
|
10
|
+
const value = env.refs?.task;
|
|
11
|
+
if (value === undefined) return [];
|
|
12
|
+
if (!/^[1-9][0-9]*$/.test(value)) { invalidTask = true; return []; }
|
|
13
|
+
const id = Number(value);
|
|
14
|
+
if (!Number.isSafeInteger(id)) { invalidTask = true; return []; }
|
|
15
|
+
return [id];
|
|
16
|
+
}));
|
|
17
|
+
const task = options.task === undefined || invalidTask ? undefined : refs.size === 1 ? [...refs][0] : refs.size === 0 ? options.task : undefined;
|
|
18
|
+
const validTask = task !== undefined && Number.isSafeInteger(task) && task > 0 && (options.task === undefined || task === options.task);
|
|
19
|
+
let scheduled: boolean | undefined;
|
|
20
|
+
if (validTask && options.scheduled) try { scheduled = options.scheduled(task); } catch { /* Unknown provenance yields no assignment trigger. */ }
|
|
21
|
+
let uncertainTrigger = false;
|
|
22
|
+
const triggers = new Set(envs.flatMap(env => {
|
|
23
|
+
if (env.from === HUB && env.kind === "review") return ["review" as const];
|
|
24
|
+
if (env.from === HUB && env.kind === "task" && env.refs?.taskOffer !== undefined) {
|
|
25
|
+
if (scheduled === undefined) { uncertainTrigger = true; return []; }
|
|
26
|
+
return [scheduled ? "schedule" as const : "assign" as const];
|
|
27
|
+
}
|
|
28
|
+
if (env.from === USER) return ["manual" as const];
|
|
29
|
+
if (env.kind === "chat" && env.from !== HUB) return ["message" as const];
|
|
30
|
+
return [];
|
|
31
|
+
}));
|
|
32
|
+
return { ...(validTask ? { task } : {}), ...(!uncertainTrigger && triggers.size === 1 ? { trigger: [...triggers][0]! } : {}),
|
|
33
|
+
...(envs.some(env => env.private) ? { private: true } : {}), ...(options.cloud ? { cloud: true } : {}) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Strip inherited/configured hints and add only validated host-provided values. */
|
|
37
|
+
export function applyTurnAttribution(source: NodeJS.ProcessEnv, context?: TurnAttribution): NodeJS.ProcessEnv {
|
|
38
|
+
const env = { ...source };
|
|
39
|
+
delete env.AGENTHUB_TASK_ID; delete env.AGENTHUB_ATTEMPT_ID; delete env.AGENTHUB_TRIGGER;
|
|
40
|
+
const hidden = context?.private === true && context.cloud === true;
|
|
41
|
+
const hasTask = !hidden && context?.task !== undefined && Number.isSafeInteger(context.task) && context.task > 0;
|
|
42
|
+
if (hasTask) env.AGENTHUB_TASK_ID = String(context!.task);
|
|
43
|
+
if (hasTask && typeof context?.attempt === "string" && /^ra-[0-9a-f]{12}$/.test(context.attempt)) env.AGENTHUB_ATTEMPT_ID = context.attempt;
|
|
44
|
+
if (context?.trigger && ["assign", "review", "message", "manual", "schedule"].includes(context.trigger)) env.AGENTHUB_TRIGGER = context.trigger;
|
|
45
|
+
return env;
|
|
46
|
+
}
|
|
@@ -6,7 +6,7 @@ This project runs agent-hub: other coding agents and the hub console user reach
|
|
|
6
6
|
- Receiving: Claude Code started with `ahub claude` gets hub messages as `<channel source="agent-hub">` tags and answers with `hub_send` (pass `reply_to` with the message id). Codex, headless Kimi, Qwen and Jcode, Pi and the local worker get them as prompts in which each message starts with a `[agent-hub message from` line, and the final answer of the turn is shared with the other agents. Any other session (a Claude session started otherwise, Antigravity `agy`, Kimi in its own TUI) is pull-only: read with `hub_inbox`, share with `hub_send`.
|
|
7
7
|
- Pull-only sessions: call `hub_inbox` when starting work, between steps of longer work (after each commit, test run or finished sub-step), and before reporting; a hub tool result says when important messages are waiting. `hub_inbox` also reads a channel session's missed pushes. In the agy TUI the hub tools can be missing on the first turn: if no `hub_*` tool is listed, say so, end the turn and use them from the next turn; never report the hub as unavailable from the first turn alone.
|
|
8
8
|
- Read the kind of each message. Only `hub` items with kind `presence` are shared memory for reference, not requests. Its `task`, `review`, and `budget` items are workflow events: check the task board and your assigned role, then use the appropriate hub tools within the user's authorized scope.
|
|
9
|
-
- What you share is a conclusion, never tool output, and every answer costs the other agents a turn. If a message needs no answer, do no work and do not acknowledge it. Unmarked answers are batched into digests. Start with `[IMPORTANT]` only when the others must see it now (a blocker, or a changed contract or path that invalidates their current work), addressed with `to`.
|
|
9
|
+
- What you share is a conclusion, never tool output, and every answer costs the other agents a turn. If a message needs no answer, do no work and do not acknowledge it. A peer whose final answer is shared (see Receiving) ends such a turn with exactly `[FYI]`, which sends nothing. Unmarked answers are batched into digests. Start with `[IMPORTANT]` only when the others must see it now (a blocker, or a changed contract or path that invalidates their current work), addressed with `to`.
|
|
10
10
|
- Do not use `[FYI]` for PR ready, done, submitted, ruling needed, blocker, or changed contract or path messages: each requires recipient action. Use `[FYI]` only for progress or information needing no action; it is recorded and costs nobody a turn. `hub_task_done` and `hub_review` already notify assigned recipients; no duplicate chat is needed.
|
|
11
11
|
- When the hub or a refusal gives a command for the person to run, pass it on exactly as printed, with every flag and the `cd` prefix. If a value is missing, read it first (`ahub queue show <id>` for a delivery) and fill it in; never give the person a shortened command or a `<placeholder>`.
|
|
12
12
|
- The task board is the record of who does what: `hub_task_propose`, `hub_task_accept` / `hub_task_decline`, `hub_task_done`, `hub_review`, `hub_task_list`. `.agenthub/config.json` `roles` says who plans, implements, verifies and reviews.
|