@staix/agent-hub 0.43.0 → 0.44.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 +21 -0
- package/README.md +1 -1
- package/docs/agent-notes/daemon.md +3 -3
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/tasks.md +2 -1
- package/docs/agent-notes/tests.md +1 -1
- package/docs/design/agent-hub-architecture.md +2 -0
- package/docs/design/supervision.md +13 -1
- package/docs/design/task-board.md +7 -1
- package/docs/dogfood.md +8 -2
- package/docs/events.md +4 -2
- package/docs/memory.md +3 -3
- package/docs/operations.md +37 -17
- package/docs/quickstart.md +8 -2
- package/docs/research.md +2 -0
- package/docs/sdlc.md +5 -2
- package/docs/security.md +2 -2
- package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
- package/docs/verification/2026-11-19-0.44.0.md +60 -0
- package/docs/verified.json +22 -22
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +183 -105
- package/plugins/agent-hub/server.js +202 -121
- package/src/cli/main.ts +1 -1
- package/src/cli/output.ts +2 -2
- package/src/cli/sdlc-output.ts +7 -1
- package/src/cli/upgrade.ts +9 -3
- package/src/hub/board.ts +14 -1
- package/src/hub/bus.ts +4 -0
- package/src/hub/claude-shell-wrapper.ts +2 -1
- package/src/hub/control-write-trace.ts +39 -2
- package/src/hub/daemon.ts +66 -24
- package/src/hub/facts.ts +30 -0
- package/src/hub/hub-tools.ts +1 -1
- package/src/hub/quota-events.ts +40 -0
- package/src/hub/recovery-store.ts +21 -3
- package/src/hub/report.ts +1 -1
- package/src/hub/research-quality.ts +5 -1
- package/src/hub/research-record.ts +3 -2
- package/src/hub/restart.ts +49 -2
- package/src/hub/runtime-capture-prune.ts +9 -1
- package/src/hub/runtime-prune-health.ts +5 -1
- package/src/hub/sdlc-merge.ts +7 -3
- package/src/hub/sdlc-metrics.ts +15 -6
- package/src/hub/sdlc.ts +18 -6
- package/src/hub/snapshots.ts +43 -0
- package/src/hub/supervision-rules.ts +2 -2
- package/src/hub/task-shell-command.ts +124 -0
- package/src/hub/tasks.ts +124 -20
- package/src/hub/worktree-shelf.ts +2 -1
- package/src/local/sandbox.ts +2 -1
- package/src/local/shell-environment.ts +6 -0
- package/src/memory/brief.ts +10 -1
package/src/cli/main.ts
CHANGED
|
@@ -600,7 +600,7 @@ async function taskOp(op: string, a: Record<string, unknown>, throwOnError = fal
|
|
|
600
600
|
if (!res.ok) {
|
|
601
601
|
if (throwOnError) throw new Error(res.error);
|
|
602
602
|
if(res.refusalAudited===true)operationalRefusalRecorded=true;
|
|
603
|
-
if(
|
|
603
|
+
if(operationalAuditReady ? res.authorityRefused!==false : res.authorityRefused===true)audit("refused"); // a domain error is not a refusal (#1547)
|
|
604
604
|
// #711: an agent shell refused something only the person may do is told why it counts as an agent. The refusal and the authority stay as they were.
|
|
605
605
|
const cause = agentShellCause(identity, String(res.error));
|
|
606
606
|
if (cause) console.error(`ahub: ${res.error}\n${cause}`), process.exit(1);
|
package/src/cli/output.ts
CHANGED
|
@@ -812,13 +812,13 @@ export function renderReport(report: Report | TaskReport, columns?: number, now
|
|
|
812
812
|
[span("messages"), span(r.messages.total, "number")], [span("overflow"), span(r.messages.overflow, "number")],
|
|
813
813
|
[span("undeliverable"), span(r.messages.undeliverable, "number")], [span("messages per task"), span(r.messages.perTask, "number")],
|
|
814
814
|
[span("overlap warnings"), span(r.overlaps.warnings, "number")], [span("task pairs"), span(r.overlaps.pairs, "number")],
|
|
815
|
-
[span("edit conflicts"), span(r.conflicts, "number")], [span("quota
|
|
815
|
+
[span("edit conflicts"), span(r.conflicts, "number")], [span("quota rows"), span(r.quota.readings, "number")], [span("hard rows"), span(r.quota.hard, "number")],
|
|
816
816
|
], columns));
|
|
817
817
|
}
|
|
818
818
|
let previous = "";
|
|
819
819
|
const section = (line: string) => byTask
|
|
820
820
|
? line.startsWith("task #") ? "Tasks" : line.startsWith("class ") ? "Classes" : line.startsWith("unattributed:") ? "Unattributed" : line.startsWith("before attribution:") ? "Before attribution" : previous
|
|
821
|
-
: line.startsWith("peer ") ? "Peers" : line.startsWith("usage ") ? "Usage" : line.startsWith("supervision ") ? "Supervision" : line.startsWith("conductor ") ? "Conductor" : line.startsWith("messages:") ? "Messages" : line.startsWith("overlap warnings:") ? "Coordination" : line.startsWith("task events:") ? "Tasks" : line.startsWith("quota
|
|
821
|
+
: line.startsWith("peer ") ? "Peers" : line.startsWith("usage ") ? "Usage" : line.startsWith("supervision ") ? "Supervision" : line.startsWith("conductor ") ? "Conductor" : line.startsWith("messages:") ? "Messages" : line.startsWith("overlap warnings:") ? "Coordination" : line.startsWith("task events:") ? "Tasks" : line.startsWith("quota rows:") ? "Quota" : line.startsWith("route ") ? "Routes" : "Report";
|
|
822
822
|
for (const sentence of formatted.slice(1)) {
|
|
823
823
|
const name = section(sentence);
|
|
824
824
|
if (name !== previous) {
|
package/src/cli/sdlc-output.ts
CHANGED
|
@@ -176,6 +176,9 @@ function taskBlock(row: any, columns: number | undefined, detail: boolean): Line
|
|
|
176
176
|
function lifecycleView(reply: any, columns: number | undefined, detail: boolean): Line[] {
|
|
177
177
|
const rows = list(reply?.rows);
|
|
178
178
|
const out: Line[] = [...heading(`SDLC lifecycle, mode ${reply?.mode ?? "unknown"}`, columns)];
|
|
179
|
+
if (reply?.securityScan && typeof reply.securityScan === "object") {
|
|
180
|
+
out.push(...pair("security scan", Object.entries(reply.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", "), columns, 14));
|
|
181
|
+
}
|
|
179
182
|
if (!rows.length) return [...out, [s("no task has lifecycle state yet", "muted")]];
|
|
180
183
|
if (!detail || rows.length > 1) {
|
|
181
184
|
out.push(...grid(["ID", "STAGE", "READY", "ACTOR", "PR"], rows.map(row => [s(`#${row.id}`, "taskRef"), s(row.stage ?? "unknown"), s(yes(row.ready), readyTone(row.ready)), s(row.actor ?? "-"), s(row.receipt?.pr ? `#${row.receipt.pr}` : "-")]), columns));
|
|
@@ -263,7 +266,7 @@ export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.n
|
|
|
263
266
|
// ---- sdlc metrics / costs -----------------------------------------------------------------------------------------
|
|
264
267
|
|
|
265
268
|
const SUMMARY_ROWS: [string, string, boolean][] = [
|
|
266
|
-
["acceptance_to_plan_ms", "acceptance to plan", true], ["acceptance_to_first_review_ms", "acceptance to first review", true], ["acceptance_to_merge_ms", "acceptance to merge", true],
|
|
269
|
+
["acceptance_to_plan_ms", "acceptance to plan", true], ["accepted_to_plan_ms", "task acceptance to plan", true], ["acceptance_to_first_review_ms", "acceptance to first review", true], ["acceptance_to_merge_ms", "acceptance to merge", true],
|
|
267
270
|
["rework_rounds", "rework rounds", false], ["same_head_ci_reruns", "same-head CI reruns", false], ["stale_head_re_reviews", "stale-head re-reviews", false],
|
|
268
271
|
["review_rounds_at_merge", "review rounds at merge", false], ["ci_runs_at_merge", "CI runs at merge", false], ["github_reviews_at_merge", "GitHub reviews at merge", false],
|
|
269
272
|
];
|
|
@@ -274,6 +277,9 @@ export function renderSdlcMetrics(result: unknown, columns?: number, now = Date.
|
|
|
274
277
|
const out: Line[] = [...heading("SDLC metrics", columns)];
|
|
275
278
|
out.push(...pair("window", m?.since === null || m?.since === undefined ? "all recorded history" : `since ${moment(m.since, now)}`, columns, 10),
|
|
276
279
|
...pair("tasks", `${m?.tasks ?? 0} counted${m?.withheldPrivate ? `, ${m.withheldPrivate} private withheld` : ""}`, columns, 10));
|
|
280
|
+
if (m?.securityScan && typeof m.securityScan === "object") {
|
|
281
|
+
out.push(...pair("security scan", Object.entries(m.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", "), columns, 14));
|
|
282
|
+
}
|
|
277
283
|
const metrics = m?.metrics ?? {};
|
|
278
284
|
const value = (n: unknown, time: boolean) => time ? span(n) : count(n);
|
|
279
285
|
out.push(blank, ...grid(["METRIC", "N", "UNKNOWN", "MEAN", "MEDIAN", "P90", "MAX"], SUMMARY_ROWS.map(([key, label, time]) => {
|
package/src/cli/upgrade.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { scheduleRuntimeCapturePrune } from "../hub/runtime-capture-prune.ts";
|
|
1
2
|
import { RecoveryLaunchError, type RecoveryLaunchFailure } from "./recovery-launch.ts";
|
|
2
3
|
import { nativeRestoreGroup } from "../adapters/definitions/native-identity-defaults.ts";
|
|
3
4
|
import { definitionOf } from "../adapters/registry.ts";
|
|
@@ -659,6 +660,11 @@ export function guardedRecoveryDriver(driver: RecoveryDriver, operation: () => R
|
|
|
659
660
|
};
|
|
660
661
|
}
|
|
661
662
|
|
|
663
|
+
/** #1546: a start that ran while this operation held its lock scheduled nothing; schedule runtime maintenance now that the lock is released. */
|
|
664
|
+
function pruneAfterRelease(home: string): void {
|
|
665
|
+
try { scheduleRuntimeCapturePrune(home); } catch { /* maintenance never changes a recovery outcome */ }
|
|
666
|
+
}
|
|
667
|
+
|
|
662
668
|
/** Resumable state machine. Driver actions are preceded by receipts and followed by live readback. */
|
|
663
669
|
export async function runRecovery(id: string, driver: RecoveryDriver, home = hubHome(), idleTimeoutMs = 600_000): Promise<RecoveryOperation> {
|
|
664
670
|
// Read once to validate the selector, then claim the runner before trusting any
|
|
@@ -920,7 +926,7 @@ export async function runRecovery(id: string, driver: RecoveryDriver, home = hub
|
|
|
920
926
|
if (scope === undefined && op.plan.kind === "upgrade" && !op.globalInstalled) {
|
|
921
927
|
step("install-global"); await driver.installGlobal(op); op.globalInstalled = true; save();
|
|
922
928
|
}
|
|
923
|
-
releaseRecoveryLock(id, home, scope); op.phase = "completed"; step("completed");
|
|
929
|
+
releaseRecoveryLock(id, home, scope); pruneAfterRelease(home); op.phase = "completed"; step("completed");
|
|
924
930
|
} catch (error) {
|
|
925
931
|
// #215: every runner error ends with the choices status shows, read from every open source, never only this one.
|
|
926
932
|
const presentationError = error instanceof RecoveryPresentationError ? error
|
|
@@ -1081,7 +1087,7 @@ export async function abortRecovery(id: string, driver: RecoveryDriver, home = h
|
|
|
1081
1087
|
}
|
|
1082
1088
|
delete op.error; delete op.failure; delete op.blockedReattachment; delete op.presentationCause;
|
|
1083
1089
|
op.phase = "cancelled"; op.step = "cancelled"; op.updatedAt = driver.now();
|
|
1084
|
-
writeOperation(id, op, home); releaseRecoveryLock(id, home, scope);
|
|
1090
|
+
writeOperation(id, op, home); releaseRecoveryLock(id, home, scope); pruneAfterRelease(home);
|
|
1085
1091
|
} catch (error) {
|
|
1086
1092
|
if (isDatabaseBusy(error)) throw new RecoveryDatabaseBusy();
|
|
1087
1093
|
throw error;
|
|
@@ -1223,7 +1229,7 @@ export async function disposeRecovery(id: string, choice: { fresh: string } | {
|
|
|
1223
1229
|
}
|
|
1224
1230
|
delete op.error; delete op.failure;
|
|
1225
1231
|
op.phase = "cancelled"; op.step = "disposed: stop-and-archive (abandoned, not completed)"; op.updatedAt = driver.now();
|
|
1226
|
-
writeOperation(id, op, home); releaseRecoveryLock(id, home, scope);
|
|
1232
|
+
writeOperation(id, op, home); releaseRecoveryLock(id, home, scope); pruneAfterRelease(home);
|
|
1227
1233
|
return op;
|
|
1228
1234
|
} finally { releaseRunner(); }
|
|
1229
1235
|
}
|
package/src/hub/board.ts
CHANGED
|
@@ -485,6 +485,7 @@ export interface Task extends PlanningFields {
|
|
|
485
485
|
|
|
486
486
|
/** Structured execution evidence, including legacy rows whose owner was later cleared. */
|
|
487
487
|
export function taskHasStarted(task: Pick<Task, "history">): boolean {
|
|
488
|
+
if (task.history.some(entry => entry.event === "check run passed" || entry.event === "check run failed")) return true;
|
|
488
489
|
return task.history.some(entry => ["accepted", "done", "done (checking)", "check passed", "check failed", "changes_requested", "approved", "reopened", "integration requested", "integrated"].includes(entry.event));
|
|
489
490
|
}
|
|
490
491
|
/** S9 return eligibility never erases the historical acceptance used by cancellation and undo. */
|
|
@@ -2590,6 +2591,18 @@ export class Board {
|
|
|
2590
2591
|
const rows = this.db.query(`SELECT id, at, total FROM security_scans WHERE repo=? AND sources=?${knownOnly ? " AND total IS NOT NULL" : ""} ORDER BY id DESC LIMIT ?`).all(repo.toLowerCase(), sources, Math.max(1, Math.min(1000, limit))) as { id: number; at: number; total: number | null }[];
|
|
2591
2592
|
return rows.reverse();
|
|
2592
2593
|
}
|
|
2594
|
+
/** The latest recorded per-source scan counts, with unreadable values kept unknown. */
|
|
2595
|
+
latestSecurityScanCounts(repo: string, sources: string): Record<string, number | null> | undefined {
|
|
2596
|
+
const row = this.db.query("SELECT counts FROM security_scans WHERE repo=? AND sources=? ORDER BY id DESC LIMIT 1").get(repo.toLowerCase(), sources) as { counts: string } | null;
|
|
2597
|
+
if (!row) return undefined;
|
|
2598
|
+
let counts: unknown;
|
|
2599
|
+
try { counts = JSON.parse(row.counts); } catch { counts = undefined; }
|
|
2600
|
+
const raw = counts && typeof counts === "object" && !Array.isArray(counts) ? counts as Record<string, unknown> : {};
|
|
2601
|
+
return Object.fromEntries(sources.split(",").filter(source => ["dependabot", "secret_scanning", "code_scanning"].includes(source)).map(source => {
|
|
2602
|
+
const value = raw[source];
|
|
2603
|
+
return [source, typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null];
|
|
2604
|
+
}));
|
|
2605
|
+
}
|
|
2593
2606
|
recordSecurityScan(row: { repo: string; sources: string; counts: Record<string, number | null>; total: number | null }): number {
|
|
2594
2607
|
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(row.repo) || !/^[a-z_,]{1,80}$/.test(row.sources) || (row.total !== null && (!Number.isSafeInteger(row.total) || row.total < 0))) throw new Error("invalid security scan row");
|
|
2595
2608
|
return Number(this.db.query("INSERT INTO security_scans(at, repo, sources, counts, total) VALUES(?,?,?,?,?)").run(Date.now(), row.repo.toLowerCase(), row.sources, JSON.stringify(row.counts), row.total).lastInsertRowid);
|
|
@@ -2785,7 +2798,7 @@ export class Board {
|
|
|
2785
2798
|
&& priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
|
|
2786
2799
|
const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
|
|
2787
2800
|
? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
|
|
2788
|
-
const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(
|
|
2801
|
+
const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(["done", "check run passed", "check run failed"].includes(event) && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed", "check run passed", "check run failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
|
|
2789
2802
|
this.taskWrite(() => {
|
|
2790
2803
|
if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
|
|
2791
2804
|
if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
|
package/src/hub/bus.ts
CHANGED
|
@@ -209,6 +209,8 @@ export class Bus {
|
|
|
209
209
|
* and is never corrected once the queue empties (measured: status.json kept `queued 4` on an empty queue).
|
|
210
210
|
*/
|
|
211
211
|
onQueues?: () => void;
|
|
212
|
+
/** Host-only registration observation; never changes delivery or peer state. */
|
|
213
|
+
onPeerAdded?: (peer: PeerId) => void;
|
|
212
214
|
/**
|
|
213
215
|
* #445 C2: a peer's answer to a delivery, offered BEFORE anything is built from it. The host returns true when the answer belongs to an invocation it
|
|
214
216
|
* took over: the bus then publishes nothing, stores nothing, emits no event and lets no tap, queue, digest or memory path see it. `answers` is what the
|
|
@@ -303,6 +305,7 @@ export class Bus {
|
|
|
303
305
|
}
|
|
304
306
|
|
|
305
307
|
add(peer: PeerAdapter): void {
|
|
308
|
+
const newAttachment = this.peers.get(peer.id) !== peer;
|
|
306
309
|
if (peer.remoteRoom !== undefined && (!parseRemotePeerId(peer.id) || typeof peer.remoteRoom !== "string" || !peer.remoteRoom || peer.remoteRoom.length > 256 || !remoteFingerprint(peer.remoteMember))) throw new Error("invalid remote peer binding");
|
|
307
310
|
const pendingRemote = peer.remoteRoom !== undefined && this.hasRemoteWork(peer.id);
|
|
308
311
|
if (peer.remoteRoom !== undefined && pendingRemote) {
|
|
@@ -458,6 +461,7 @@ export class Bus {
|
|
|
458
461
|
this.emit({ t: "state", peer: peer.id, state: this.stateOf(peer.id) });
|
|
459
462
|
void this.drain(peer.id);
|
|
460
463
|
};
|
|
464
|
+
if (newAttachment) try { this.onPeerAdded?.(peer.id); } catch { /* observers cannot undo a registered peer */ }
|
|
461
465
|
}
|
|
462
466
|
|
|
463
467
|
private persist(): void {
|
|
@@ -11,6 +11,7 @@ import { shellQuote } from "../cli/shell-quote.ts";
|
|
|
11
11
|
import { readProcessTable, stopOwnedProcess, trackGroup } from "./child-process.ts";
|
|
12
12
|
import { realPath } from "./project.ts";
|
|
13
13
|
import { sbplString } from "../local/deny.ts";
|
|
14
|
+
import { sandboxCommandEnvironment } from "../local/shell-environment.ts";
|
|
14
15
|
|
|
15
16
|
export interface ShellGrant {
|
|
16
17
|
peer: string; task: number; generation: string; root: string; branch: string;
|
|
@@ -233,7 +234,7 @@ export class HostShellWrapper {
|
|
|
233
234
|
try {
|
|
234
235
|
if (!unchanged(ticket) || !this.stable(ticket.root.path) || !this.sandboxStable(grant, ticket.root.path) || !same(grant.root, ticket.root, true) || !same(grant.executable, ticket.executable)) throw fail();
|
|
235
236
|
const temp = mkdtempSync(join(this.directory.path, "r-")); chmodSync(temp, 0o700); temporary = execution.temporary = stamp(temp, true);
|
|
236
|
-
const env = { ...grant.env, TMPDIR: `${temporary.path}/` };
|
|
237
|
+
const env = grant.sandbox ? sandboxCommandEnvironment(grant.env, temporary.path) : { ...grant.env, TMPDIR: `${temporary.path}/` };
|
|
237
238
|
// Identical own-temp allow suffix and data.readonly broad-write guard to sandboxedExec.
|
|
238
239
|
if (grant.sandbox?.readOnlyData && /\(allow file-write\* \(subpath /.test(grant.sandbox.profile)) throw fail();
|
|
239
240
|
const sandbox = grant.sandbox && `${grant.sandbox.profile}\n(allow file-read* ${grant.sandbox.readOnlyData ? "" : "file-write* "}process-exec (subpath ${sbplString(temporary.path)}))`;
|
|
@@ -24,6 +24,8 @@ const MAX_ACTIVE_SPANS = 256;
|
|
|
24
24
|
const MAX_RECENT_SPANS = 512;
|
|
25
25
|
const MAX_LOOP_SPANS = 8;
|
|
26
26
|
const MIN_SYNC_PREFIX_MS = 10;
|
|
27
|
+
/** Microtask hops one request may spend following its async spans after their first await, shared by all of them: bounds the loop work this telemetry adds (#1545). */
|
|
28
|
+
const MAX_REQUEST_HOPS = 16;
|
|
27
29
|
const MAX_EMITS_PER_MINUTE = 60;
|
|
28
30
|
const RATE_LIMIT_MS = 1_000;
|
|
29
31
|
const RATE_KEYS = ["slow", "loop"] as const;
|
|
@@ -51,6 +53,7 @@ interface RequestTrace {
|
|
|
51
53
|
phaseOrder: ControlWritePhase[];
|
|
52
54
|
settled: boolean;
|
|
53
55
|
privacySuppressed: boolean;
|
|
56
|
+
hopsLeft: number;
|
|
54
57
|
}
|
|
55
58
|
interface SpanTrace {
|
|
56
59
|
id?: number;
|
|
@@ -60,6 +63,8 @@ interface SpanTrace {
|
|
|
60
63
|
async: boolean;
|
|
61
64
|
finished: boolean;
|
|
62
65
|
prefixRecorded: boolean;
|
|
66
|
+
/** Loop turn the span began in (see turn): a span that finishes in the same turn never let the loop go idle. */
|
|
67
|
+
turn: number;
|
|
63
68
|
}
|
|
64
69
|
interface SpanInterval {
|
|
65
70
|
kind: ControlWriteKind;
|
|
@@ -135,6 +140,7 @@ export function controlWriteSpan<T>(phase: ControlWritePhase, fn: () => T): T {
|
|
|
135
140
|
if (!isThenable(result)) { request.telemetry.finishSpan(span); return result; }
|
|
136
141
|
span.async = true;
|
|
137
142
|
request.telemetry.recordSyncPrefix(span);
|
|
143
|
+
request.telemetry.followSpan(span);
|
|
138
144
|
return Promise.resolve(result).then(
|
|
139
145
|
value => { request.telemetry.finishSpan(span); return value; },
|
|
140
146
|
error => { request.telemetry.finishSpan(span); throw error; },
|
|
@@ -158,6 +164,10 @@ export class ControlWriteTelemetry {
|
|
|
158
164
|
private timer: ReturnType<typeof setInterval> | undefined;
|
|
159
165
|
private nextSampleAt: number | undefined;
|
|
160
166
|
private lastNow = 0;
|
|
167
|
+
private hops = 0;
|
|
168
|
+
/** Counts event-loop turns (one setImmediate marker, only while spans are being traced). */
|
|
169
|
+
private turn = 0;
|
|
170
|
+
private turnPending = false;
|
|
161
171
|
private stopped = false;
|
|
162
172
|
private completedRequests = 0;
|
|
163
173
|
private expiredRequests = 0;
|
|
@@ -198,7 +208,7 @@ export class ControlWriteTelemetry {
|
|
|
198
208
|
if (!inputVisible) return fn();
|
|
199
209
|
const request: RequestTrace = {
|
|
200
210
|
telemetry: this, metadata: safeMetadata, privacyCurrent,
|
|
201
|
-
startedAt: now, phases: new Map(), phaseOrder: [], settled: false, privacySuppressed: false,
|
|
211
|
+
startedAt: now, phases: new Map(), phaseOrder: [], settled: false, privacySuppressed: false, hopsLeft: MAX_REQUEST_HOPS,
|
|
202
212
|
logPrivacy: () => false,
|
|
203
213
|
};
|
|
204
214
|
request.logPrivacy = () => !request.privacySuppressed && this.privateNow(request.privacyCurrent);
|
|
@@ -298,7 +308,8 @@ export class ControlWriteTelemetry {
|
|
|
298
308
|
}
|
|
299
309
|
|
|
300
310
|
beginSpan(request: RequestTrace, phase: ControlWritePhase): SpanTrace {
|
|
301
|
-
|
|
311
|
+
if (!this.turnPending && !this.stopped) { this.turnPending = true; setImmediate(() => { this.turn++; this.turnPending = false; }).unref?.(); }
|
|
312
|
+
const span: SpanTrace = { request, phase, startedAt: this.readNow(), async: false, finished: false, prefixRecorded: false, turn: this.turn };
|
|
302
313
|
if (this.spans.size >= this.maxActiveSpans) { this.droppedSpans++; return span; }
|
|
303
314
|
span.id = this.nextSpanId++;
|
|
304
315
|
this.spans.set(span.id, span);
|
|
@@ -317,6 +328,9 @@ export class ControlWriteTelemetry {
|
|
|
317
328
|
if (!request.phaseOrder.includes(span.phase)) request.phaseOrder.push(span.phase);
|
|
318
329
|
request.phases.set(span.phase, prior + durationMs);
|
|
319
330
|
if (!span.async && !span.prefixRecorded) this.rememberSyncInterval(span, endedAt);
|
|
331
|
+
// An async span that began and settled inside one loop turn never yielded: every ms of it was loop-busy time, so it is a synchronous
|
|
332
|
+
// slice (microtask chains). A span that yielded is a wait; overlap with a blocked window alone is presence, never cause.
|
|
333
|
+
else if (span.async && span.turn === this.turn && endedAt - span.startedAt >= MIN_SYNC_PREFIX_MS) this.rememberSyncInterval(span, endedAt);
|
|
320
334
|
}
|
|
321
335
|
|
|
322
336
|
/** Preserve a long synchronous prelude inside an async function for the delayed loop probe. */
|
|
@@ -328,6 +342,29 @@ export class ControlWriteTelemetry {
|
|
|
328
342
|
this.rememberSyncInterval(span, endedAt);
|
|
329
343
|
}
|
|
330
344
|
|
|
345
|
+
/** Hops spent following spans: the measured extra work, bounded per request. */
|
|
346
|
+
followedHops(): number { return this.hops; }
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* After a span's first await, look at the next few microtask turns of its request (a shared budget of MAX_REQUEST_HOPS, so the added
|
|
350
|
+
* loop work is bounded per request however many spans it has). A gap between two hops is time a continuation ran synchronously and is
|
|
351
|
+
* remembered as a synchronous slice. A block after a real I/O await is out of reach: the budget is spent by then, and Bun has no
|
|
352
|
+
* per-continuation hook, so such a slice is only a lower bound.
|
|
353
|
+
*/
|
|
354
|
+
followSpan(span: SpanTrace): void {
|
|
355
|
+
let last = this.readNow();
|
|
356
|
+
const hop = (): void => {
|
|
357
|
+
const request = span.request;
|
|
358
|
+
if (span.finished || request.settled || this.stopped || request.hopsLeft <= 0) return;
|
|
359
|
+
request.hopsLeft--; this.hops++;
|
|
360
|
+
const now = this.readNow();
|
|
361
|
+
if (now - last >= MIN_SYNC_PREFIX_MS) this.rememberSyncInterval({ ...span, startedAt: last }, now);
|
|
362
|
+
last = now;
|
|
363
|
+
queueMicrotask(hop);
|
|
364
|
+
};
|
|
365
|
+
queueMicrotask(hop);
|
|
366
|
+
}
|
|
367
|
+
|
|
331
368
|
private rememberSyncInterval(span: SpanTrace, endedAt: number): void {
|
|
332
369
|
const request = span.request;
|
|
333
370
|
this.recent.push({ kind: request.metadata.kind, ...(request.metadata.task === undefined ? {} : { task: request.metadata.task }), phase: span.phase, startedAt: span.startedAt, endedAt, async: false, privacyCurrent: request.logPrivacy });
|
package/src/hub/daemon.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { QuotaEventFilter } from "./quota-events.ts";
|
|
1
2
|
import { piFailureText } from "./pi-failure.ts";
|
|
2
3
|
import { nativeReviewerQuota } from "../adapters/definitions/native-quota.ts";
|
|
3
4
|
import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
|
|
@@ -52,6 +53,7 @@ import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
|
|
|
52
53
|
import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
|
|
53
54
|
import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
|
|
54
55
|
import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-admission.ts";
|
|
56
|
+
import { MERGE_READBACK_INTERVAL_MS } from "./sdlc-merge.ts";
|
|
55
57
|
import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
|
|
56
58
|
import { fetchSpec, specAvailable, specRefs } from "./spec-read.ts";
|
|
57
59
|
import { isDenied, sbplString } from "../local/deny.ts";
|
|
@@ -246,8 +248,8 @@ import { Facts, FACTS_PREFIX, type FactScope } from "./facts.ts";
|
|
|
246
248
|
import { crashPlan, lossNotice, openCrashNotices, readSessions, removeSessions, writeSessions, type CrashNotice, type SessionsFile } from "./crash.ts";
|
|
247
249
|
import type { JournalDelivery } from "./delivery-journal.ts";
|
|
248
250
|
import { DEFAULT_LIMITS, Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
|
|
249
|
-
import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
|
|
250
|
-
import { archiveRestartSnapshot, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
|
|
251
|
+
import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, SnapshotCooldown, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
|
|
252
|
+
import { archiveRestartSnapshot, compactRestartBus, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
|
|
251
253
|
import { consumeRecoveryContinuity, readRecoveryContinuity, retireRecoveryContinuity } from "./recovery-continuity.ts";
|
|
252
254
|
import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf } from "../cli/terminal-recovery.ts";
|
|
253
255
|
import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
|
|
@@ -767,6 +769,8 @@ function mlxPinProblem(routing: Routing, project: boolean): string | undefined {
|
|
|
767
769
|
export interface DaemonOptions {
|
|
768
770
|
/** Host-only fixture override; production reads the active memory home's and execution repository's public Record policy. */
|
|
769
771
|
effectiveRecordPolicy?: (cwd: string) => { enabled: boolean; version: string } | undefined;
|
|
772
|
+
/** Host-only test trigger; production schedules its own unreferenced settlement interval. */
|
|
773
|
+
mergeReadbackTrigger?: (tick: () => void) => () => void;
|
|
770
774
|
/** Host-only numeric startup reader observation; never read from config or control input. Observer failure changes no replay state. */
|
|
771
775
|
startupSeedObserved?: (observation: { readPasses: number; readBytes: number }) => void;
|
|
772
776
|
/** Host-only test/embedding port; never read from project configuration or a tool. */
|
|
@@ -2108,20 +2112,22 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2108
2112
|
async function taskIntentBrief(task: import("../memory/brief.ts").BriefTask): Promise<import("../memory/brief.ts").IntentBriefContext> {
|
|
2109
2113
|
checkMemory();
|
|
2110
2114
|
const initial = task.id === undefined ? undefined : board.get(task.id), revision = configRevision;
|
|
2111
|
-
|
|
2115
|
+
let taskCurrent = false, contextPrivate = true;
|
|
2116
|
+
const refreshTask = () => {
|
|
2112
2117
|
const current = task.id === undefined ? undefined : board.get(task.id);
|
|
2113
|
-
|
|
2114
|
-
&& current.history.length === initial.history.length && current.owner === initial.owner && !tasks.isPii(current)
|
|
2115
|
-
|
|
2118
|
+
taskCurrent = !!initial && !!current && current.created === task.created && current.updated === initial.updated
|
|
2119
|
+
&& current.history.length === initial.history.length && current.owner === initial.owner && !tasks.isPii(current);
|
|
2120
|
+
contextPrivate = contextPii(initial?.owner ?? "");
|
|
2116
2121
|
};
|
|
2117
|
-
const
|
|
2122
|
+
const allowed = () => taskCurrent && !contextPrivate && !stopping && configRevision === revision && !turns.get(initial?.owner ?? "")?.private;
|
|
2123
|
+
const assertCurrent = () => { checkMemory(); refreshTask(); if (!allowed()) throw Error("memory brief context changed"); };
|
|
2118
2124
|
assertCurrent();
|
|
2119
2125
|
// Derived code neighbours are additional read-time selectors, never persisted memory or authority.
|
|
2120
2126
|
const starts = taskNodes(task).filter(node => node.startsWith("symbol:"));
|
|
2121
2127
|
let extra: string[] = [];
|
|
2122
2128
|
if (starts.length && tasks.memoryCodeEligible(initial!)) {
|
|
2123
2129
|
try {
|
|
2124
|
-
const prepared = await memoryCode(starts, allowed);
|
|
2130
|
+
const prepared = await memoryCode(starts, () => { refreshTask(); return allowed(); });
|
|
2125
2131
|
assertCurrent();
|
|
2126
2132
|
extra = currentMemoryCode(prepared).nodes.map(node => node.id).filter(node => node.startsWith("symbol:")).map(node => node.slice(7));
|
|
2127
2133
|
} catch { /* Optional code evidence never removes direct intent memory. */ }
|
|
@@ -2129,7 +2135,6 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2129
2135
|
assertCurrent();
|
|
2130
2136
|
const stale = staleness();
|
|
2131
2137
|
const policy = createStandalonePolicy({ denyPaths: config.local.deny, host: { screen: async value => {
|
|
2132
|
-
assertCurrent();
|
|
2133
2138
|
if (value && typeof value === "object" && "id" in value) {
|
|
2134
2139
|
const row = value as MemoryView;
|
|
2135
2140
|
return screenMemory([row]).length === 1 && tasks.publicMetadataText(JSON.stringify(row));
|
|
@@ -2845,7 +2850,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2845
2850
|
};
|
|
2846
2851
|
const currentCheck = (receipt: { task: number; owner: string; updated: number | string; generation: number | string; revision?: number }) => {
|
|
2847
2852
|
const task = board.get(receipt.task);
|
|
2848
|
-
return !!task && task.owner === receipt.owner && task.state === "in_progress" &&
|
|
2853
|
+
return !!task && task.owner === receipt.owner && task.state === "in_progress" && Number.isSafeInteger(receipt.revision) && receipt.revision! >= 0 && receipt.revision! <= task.history.length
|
|
2854
|
+
&& task.history.slice(receipt.revision).every(entry => entry.event === "check run passed" || entry.event === "check run failed")
|
|
2849
2855
|
&& connectionGeneration(receipt.owner) === receipt.generation && may(receipt.owner, "check_run") && membershipAllowed(receipt.owner) && !tasks.isPii(task)
|
|
2850
2856
|
&& !turns.get(receipt.owner)?.private && !contextPii(receipt.owner);
|
|
2851
2857
|
};
|
|
@@ -2894,6 +2900,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2894
2900
|
while (checkBindings.size > 200) checkBindings.delete(checkBindings.keys().next().value!);
|
|
2895
2901
|
if (stopping || !currentCheck(receipt)) { await checkRunner.markStale(receipt.run); return; }
|
|
2896
2902
|
bus.publish(newEnvelope(HUB, sanitize(JSON.stringify(view)), { to: [receipt.owner], kind: "task", refs: { task: String(receipt.task), boundedCheck: receipt.run } }));
|
|
2903
|
+
if (currentCheck(receipt)) tasks.recordCheckResult(receipt);
|
|
2897
2904
|
log(`check ${receipt.run}: exit ${receipt.exit ?? "unknown"}, bytes ${receipt.output_bytes}`);
|
|
2898
2905
|
},
|
|
2899
2906
|
};
|
|
@@ -3636,6 +3643,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3636
3643
|
turnFreeNow = undefined;
|
|
3637
3644
|
scopes = new Map();
|
|
3638
3645
|
progress.prune();
|
|
3646
|
+
if (t.state === "approved" || t.state === "cancelled") { facts.closeTask(t.id); for (const store of worktreeFacts.values()) store.closeTask(t.id); } // #1556 T1: receipts end with the task
|
|
3639
3647
|
factsOn(); // a PII task opening or closing switches tracking at once, not at the next boundary (issue #108)
|
|
3640
3648
|
if (t.state !== "in_progress" || ownerWriteStarts.get(t.id)?.owner !== t.owner) ownerWriteStarts.delete(t.id);
|
|
3641
3649
|
if ((h.event === "integration requested" || h.event === "integration unresolved") && /has not stopped/.test(h.note ?? "")) {
|
|
@@ -4026,6 +4034,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4026
4034
|
}
|
|
4027
4035
|
};
|
|
4028
4036
|
const unsettledReviewerQuota = new Map<string, { account: string; peer: string }>();
|
|
4037
|
+
const quotaEvents = new QuotaEventFilter(event);
|
|
4029
4038
|
const budget = new Budget(join(opts.stateDir, "hub.db"), config.budget, instanceBudgetHooks({
|
|
4030
4039
|
definitionOf,
|
|
4031
4040
|
pause: (peer) => bus.pause(peer),
|
|
@@ -4046,7 +4055,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4046
4055
|
// A reading that arrived through a file carries the file's time; a stale one must not look fresh in the export.
|
|
4047
4056
|
// #683 U1: pauses, resumes and derived resets go to the event log, ids and numbers only.
|
|
4048
4057
|
ledger: entry => event(entry),
|
|
4049
|
-
reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits());
|
|
4058
|
+
reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits()); quotaEvents.record(peer, windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, at); },
|
|
4050
4059
|
handoff: (peer, context, urgentOnly) => tasks.reassignForPause(peer, context, urgentOnly),
|
|
4051
4060
|
resumed: (record) => {
|
|
4052
4061
|
// Coalesce unread notices without forgetting the public moves they carried.
|
|
@@ -4320,13 +4329,16 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4320
4329
|
// Preserve real synchronous native boundaries, but never spend an unbounded sequence of Git waits
|
|
4321
4330
|
// inside a single callback burst. Failed/slow captures are explicitly unknown, never stale baselines.
|
|
4322
4331
|
let snapshotBudget: SnapshotBudget | undefined, snapshotBudgetNoticed = false;
|
|
4332
|
+
const snapshotCooldown = new SnapshotCooldown();
|
|
4333
|
+
type RoutineSnapshot = { repository: string; budget: SnapshotBudget; exhausted: boolean; skipped: boolean };
|
|
4323
4334
|
const reserveSnapshotBudget = (): SnapshotBudget => {
|
|
4324
4335
|
if (!snapshotBudget) {
|
|
4325
4336
|
const requested = opts.snapshotBurstMs ?? 250;
|
|
4326
4337
|
const ms = Number.isFinite(requested) ? Math.max(1, Math.min(250, requested)) : 250;
|
|
4327
4338
|
const now = opts.snapshotClock;
|
|
4328
4339
|
snapshotBudget = { deadline: (now ? now() : performance.now()) + ms, ...(now ? { now } : {}) };
|
|
4329
|
-
|
|
4340
|
+
const burst = snapshotBudget;
|
|
4341
|
+
setImmediate(() => { snapshotCooldown.finish(burst); snapshotBudget = undefined; snapshotBudgetNoticed = false; });
|
|
4330
4342
|
}
|
|
4331
4343
|
return snapshotBudget;
|
|
4332
4344
|
};
|
|
@@ -4338,16 +4350,25 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4338
4350
|
return turnModelFields(bus.peers.get(peer)?.observedModel?.() ?? (hooked ? { model: hooked, evidence: "session" } : undefined));
|
|
4339
4351
|
} catch { return {}; }
|
|
4340
4352
|
};
|
|
4341
|
-
const snapshotFailure = (what: string, error: unknown) => {
|
|
4353
|
+
const snapshotFailure = (what: string, error: unknown, routine?: RoutineSnapshot) => {
|
|
4342
4354
|
if (error instanceof SnapshotBudgetExceeded) {
|
|
4355
|
+
if (routine) { routine.exhausted = true; return; }
|
|
4343
4356
|
if (!snapshotBudgetNoticed) log(`snapshot unavailable: ${error.message}`);
|
|
4344
4357
|
snapshotBudgetNoticed = true;
|
|
4345
4358
|
} else log(`snapshot failed at ${what}: ${(error as Error).message}`);
|
|
4346
4359
|
};
|
|
4347
|
-
const
|
|
4360
|
+
const finishRoutineSnapshot = (routine?: RoutineSnapshot) => {
|
|
4361
|
+
if (!routine || routine.skipped) return;
|
|
4362
|
+
if (routine.exhausted) {
|
|
4363
|
+
if (snapshotCooldown.exhausted(routine.repository, routine.budget)) log("snapshot unavailable: snapshot burst budget exhausted; boundary evidence is unknown; inspect snapshots.enabled");
|
|
4364
|
+
} else snapshotCooldown.success(routine.repository, routine.budget);
|
|
4365
|
+
};
|
|
4366
|
+
const snap = (what: string, capture = config.snapshots.enabled, peer?: string, routine = false): { tree?: string; head?: string | null; commit?: string | null; reflog?: HeadMoveCursor; ms: number; budget?: SnapshotBudget; repo?: Repo; routine?: RoutineSnapshot } => {
|
|
4348
4367
|
if (!capture) return { ms: 0 };
|
|
4349
4368
|
const captureSnapshot = () => {
|
|
4350
4369
|
const t0 = performance.now(), budget = reserveSnapshotBudget();
|
|
4370
|
+
const boundary: RoutineSnapshot | undefined = routine ? { repository: peer ? executionRoot(peer) : opts.cwd, budget, exhausted: false, skipped: false } : undefined;
|
|
4371
|
+
if (boundary && snapshotCooldown.blocked(boundary.repository, budgetNow(budget))) { boundary.skipped = true; return { ms: 0, routine: boundary }; }
|
|
4351
4372
|
let tree: string | undefined, head: string | null | undefined, commit: string | null | undefined, repo: Repo | undefined, reflog: HeadMoveCursor | undefined;
|
|
4352
4373
|
try {
|
|
4353
4374
|
repo = peer ? repoFor(peer, budget) : factsRepo;
|
|
@@ -4360,9 +4381,9 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4360
4381
|
if (repo && !tree) log(`snapshot failed at ${what}`);
|
|
4361
4382
|
} catch (error) {
|
|
4362
4383
|
tree = undefined; head = undefined; commit = undefined; reflog = undefined;
|
|
4363
|
-
snapshotFailure(what, error);
|
|
4384
|
+
snapshotFailure(what, error, boundary);
|
|
4364
4385
|
}
|
|
4365
|
-
return { tree, head, commit, reflog, budget, repo, ms: Math.round(performance.now() - t0) };
|
|
4386
|
+
return { tree, head, commit, reflog, budget, repo, ms: Math.round(performance.now() - t0), ...(boundary ? { routine: boundary } : {}) };
|
|
4366
4387
|
};
|
|
4367
4388
|
return controlWriteTelemetry ? controlWriteTelemetry.observe("snapshot", controlWritePrivacyGuard(true, true, peer as PeerId | undefined), captureSnapshot) : captureSnapshot();
|
|
4368
4389
|
};
|
|
@@ -4826,6 +4847,20 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4826
4847
|
} catch { log(`accepted delivery timeout notice publication unconfirmed; inspect ahub queue list --peer ${sanitize(conductor)} and ahub queue show ${sanitize(row.id)}`); }
|
|
4827
4848
|
}
|
|
4828
4849
|
};
|
|
4850
|
+
let mergeReadbackPass: Promise<void> | undefined;
|
|
4851
|
+
const mergeReadbackTick = () => {
|
|
4852
|
+
if (!mergeReadbackPass) mergeReadbackPass = tasks.settleMergeReadbacks(Date.now()).catch(() => {}).finally(() => { mergeReadbackPass = undefined; });
|
|
4853
|
+
};
|
|
4854
|
+
const stopMergeReadbacks = opts.mergeReadbackTrigger?.(mergeReadbackTick);
|
|
4855
|
+
const mergeReadbackTimer = stopMergeReadbacks ? undefined : setInterval(mergeReadbackTick, MERGE_READBACK_INTERVAL_MS);
|
|
4856
|
+
mergeReadbackTimer?.unref();
|
|
4857
|
+
let mergeReadbackStopped = false;
|
|
4858
|
+
const stopMergeReadbackSchedule = () => {
|
|
4859
|
+
if (mergeReadbackStopped) return;
|
|
4860
|
+
mergeReadbackStopped = true; stopMergeReadbacks?.();
|
|
4861
|
+
if (mergeReadbackTimer) clearInterval(mergeReadbackTimer);
|
|
4862
|
+
};
|
|
4863
|
+
startupCleanup.push(async () => { stopMergeReadbackSchedule(); await mergeReadbackPass; });
|
|
4829
4864
|
const intervals = [
|
|
4830
4865
|
setInterval(() => {
|
|
4831
4866
|
try { sweepInvocations(); } catch { log("invocation deadline sweep failed; the rows keep their state"); }
|
|
@@ -6963,6 +6998,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6963
6998
|
if (!recoveryActive() || releasing || taskOpsInFlight !== 0 || tasks.checksPending() !== 0 || piCallsInFlight() !== 0 || permissions.size !== 0 || starting.size !== 0 || requestedPeerStops.size !== 0 || rosterChanging !== undefined || !budget.recoverySettled || [...bus.peers.values()].filter(peer => !peer.id.includes("@")).some((peer) => peer.state === "busy" || ("recoveryReady" in peer && peer.recoveryReady !== true))) return false;
|
|
6964
6999
|
if (tasks.guidanceProbesPending() !== 0) return false; // Active and uncertain fixture work retains its project lane.
|
|
6965
7000
|
if (checkPending.size !== 0) return false;
|
|
7001
|
+
if (mergeReadbackPass) return false; // A host readback awaiting GitHub must settle before recovery commits.
|
|
6966
7002
|
if (tasks.autoPullsPending() !== 0) return false; // #785 P1c: an automatic backlog pull mid-admission would write after the commit's digest; its own line keeps the line above exact for scripts/seeds.json
|
|
6967
7003
|
if (tasks.queuePressureRechecksPending() !== 0) return false;
|
|
6968
7004
|
if (tasks.schedulesPending() !== 0) return false; // #512a: a scheduled run mid-admission (its PII screen is awaited) would write after the commit's digest; the hold fence refuses its write, and this waits for it to end
|
|
@@ -7869,14 +7905,15 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7869
7905
|
for (const id of turnTasks.keys()) if (!turnLog?.get(id)) turnTasks.delete(id);
|
|
7870
7906
|
turnTasks.set(id, board.list().filter((t) => t.owner === e.peer && ["proposed", "in_progress", "changes_requested", "in_review"].includes(t.state)).map((t) => t.id));
|
|
7871
7907
|
const capture = config.snapshots.enabled && !!turnLog;
|
|
7872
|
-
const start = capture && !pii ? snap(`the start of ${id}`, config.snapshots.enabled, e.peer) : undefined; // before the peer is handed anything: the tap runs inside setState
|
|
7908
|
+
const start = capture && !pii ? snap(`the start of ${id}`, config.snapshots.enabled, e.peer, true) : undefined; // before the peer is handed anything: the tap runs inside setState
|
|
7873
7909
|
try { if (capture) turnLog?.begin(id, e.peer, start?.tree, declarations[e.peer] ? executionRoot(e.peer) : undefined); } catch (error) { log(`turn record ${id}: ${(error as Error).message}`); }
|
|
7874
7910
|
const writeTasks = tasks.ownerTurnTasks(e.peer);
|
|
7875
7911
|
let branches: string | undefined, writeScope: boolean | undefined;
|
|
7876
7912
|
if (writeTasks.length && start?.repo) try {
|
|
7877
7913
|
branches = branchHeads(start.repo, start.budget);
|
|
7878
7914
|
writeScope = ownerWriteRoot(e.peer) === opts.cwd ? canonicalWriteScope(start.repo, start.budget) : true;
|
|
7879
|
-
} catch (error) { snapshotFailure(`the write scope of ${id}`, error); }
|
|
7915
|
+
} catch (error) { snapshotFailure(`the write scope of ${id}`, error, start?.routine); }
|
|
7916
|
+
finishRoutineSnapshot(start?.routine);
|
|
7880
7917
|
const preparedRoles = preparedSessionRoleIdentities.get(e.peer)?.map(role => ({ ...role })) ?? null;
|
|
7881
7918
|
turns.set(e.peer, { id, capture, start: startedAt, tokens: 0, writeTasks, branches, writeScope, deliveryTask: delivery, attribution, preparedRoles, ...(start ? { tree: start.tree, head: start.head, commit: start.commit, reflog: start.reflog, snapshotMs: start.ms } : {}), ...(pii ? { private: true } : {}) });
|
|
7882
7919
|
const modelBoundary = modelBoundaries.get(e.peer);
|
|
@@ -7927,7 +7964,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7927
7964
|
if (open.capture && turnLog && (open.private || holdsPii(e.peer))) {
|
|
7928
7965
|
try { turnLog.end(open.id, undefined, [], Math.max(1, Number(config.snapshots.keep) || 20)); } catch (error) { log(`turn record ${open.id}: ${(error as Error).message}`); }
|
|
7929
7966
|
} else if (open.capture && turnLog) {
|
|
7930
|
-
const end = snap(`the end of ${open.id}`, true, e.peer);
|
|
7967
|
+
const end = snap(`the end of ${open.id}`, true, e.peer, true);
|
|
7931
7968
|
let changed: string[] = [];
|
|
7932
7969
|
if (open.tree && end.tree) {
|
|
7933
7970
|
const turnRepo = end.repo!;
|
|
@@ -7967,7 +8004,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7967
8004
|
}
|
|
7968
8005
|
} catch (error) {
|
|
7969
8006
|
end.tree = undefined; end.head = undefined; changed = [];
|
|
7970
|
-
snapshotFailure(`the diff of ${open.id}`, error);
|
|
8007
|
+
snapshotFailure(`the diff of ${open.id}`, error, end.routine);
|
|
7971
8008
|
}
|
|
7972
8009
|
}
|
|
7973
8010
|
if (open.tree && end.tree) files = changed.length; // unknown, not zero, when a snapshot failed
|
|
@@ -7983,14 +8020,15 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7983
8020
|
if (scope === true) writeProgress = false;
|
|
7984
8021
|
}
|
|
7985
8022
|
}
|
|
7986
|
-
} catch (error) { snapshotFailure(`the branch refs of ${open.id}`, error); }
|
|
8023
|
+
} catch (error) { snapshotFailure(`the branch refs of ${open.id}`, error, end.routine); }
|
|
7987
8024
|
}
|
|
7988
8025
|
}
|
|
7989
8026
|
snapshotMs = (snapshotMs ?? 0) + end.ms;
|
|
7990
8027
|
// #798 D2: a submodule's own edits never move the superproject's gitlink, so the diff above cannot see them. Name the dirty ones as unobserved (never as changed:
|
|
7991
8028
|
// undo would try to restore them). Only for a turn whose trees are known; a read git cannot answer, or the budget cut short, records nothing, which stays unknown.
|
|
7992
8029
|
let unobserved: string[] | undefined;
|
|
7993
|
-
if (open.tree && end.tree && end.repo) try { unobserved = dirtySubmodules(end.repo, end.budget); } catch (error) { snapshotFailure(`the submodules of ${open.id}`, error); }
|
|
8030
|
+
if (open.tree && end.tree && end.repo) try { unobserved = dirtySubmodules(end.repo, end.budget); } catch (error) { snapshotFailure(`the submodules of ${open.id}`, error, end.routine); }
|
|
8031
|
+
finishRoutineSnapshot(end.routine);
|
|
7994
8032
|
try { turnLog.end(open.id, end.tree, changed, Math.max(1, Number(config.snapshots.keep) || 20), unobserved); } catch (error) { log(`turn record ${open.id}: ${(error as Error).message}`); }
|
|
7995
8033
|
// After the turn_end event: a notice delivered at once starts the peer's next turn, which must come after it.
|
|
7996
8034
|
if (changed.length) afterTurn = () => detectConflicts(e.peer, open.id, open.start, changed);
|
|
@@ -10910,6 +10948,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10910
10948
|
...(taskOpsInFlight !== 0 ? ["a task command in flight"] : []),
|
|
10911
10949
|
...(tasks.checksPending() !== 0 ? ["completion checks queued or running"] : []),
|
|
10912
10950
|
...(tasks.guidanceProbesPending() !== 0 ? ["guidance probe work in flight"] : []),
|
|
10951
|
+
...(mergeReadbackPass ? ["an external merge readback in flight"] : []),
|
|
10913
10952
|
...(tasks.autoPullsPending() !== 0 ? ["an automatic backlog pull in flight"] : []),
|
|
10914
10953
|
...(tasks.queuePressureRechecksPending() !== 0 ? ["a queue-pressure assignment recheck in flight"] : []),
|
|
10915
10954
|
...(tasks.schedulesPending() !== 0 ? ["a scheduled task proposal in flight"] : []),
|
|
@@ -11195,7 +11234,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11195
11234
|
sourceInstanceId: instanceId,
|
|
11196
11235
|
operationId: op,
|
|
11197
11236
|
committedAt: Date.now(),
|
|
11198
|
-
bus: bus.snapshot(),
|
|
11237
|
+
bus: compactRestartBus(bus.snapshot()),
|
|
11199
11238
|
manualPaused: [...manualPaused],
|
|
11200
11239
|
peers,
|
|
11201
11240
|
integrity: integrity(),
|
|
@@ -12670,7 +12709,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
12670
12709
|
const current = board.get(task.id) ?? task;
|
|
12671
12710
|
rows.push({ id: task.id, title: tasks.publicTitle(current), ...(tasks.isPii(current) ? {} : { receipt: tasks.publicView(current).sdlc }), ...status });
|
|
12672
12711
|
}
|
|
12673
|
-
reply({ ok: true, mode: lifecycleConfig.mode, rows, truncated: selected.length > 100 });
|
|
12712
|
+
reply({ ok: true, mode: lifecycleConfig.mode, rows, ...(tasks.securityScanCounts() ? { securityScan: tasks.securityScanCounts() } : {}), truncated: selected.length > 100 });
|
|
12674
12713
|
})().catch(() => reply({ ok: false, error: "lifecycle readback unavailable" }));
|
|
12675
12714
|
return;
|
|
12676
12715
|
}
|
|
@@ -13347,6 +13386,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13347
13386
|
writeStatus();
|
|
13348
13387
|
dashboard?.stop();
|
|
13349
13388
|
stopConfigWatch();
|
|
13389
|
+
stopMergeReadbackSchedule();
|
|
13350
13390
|
clearInterval(sweepTimer);
|
|
13351
13391
|
clearMemorySyncTimers();
|
|
13352
13392
|
clearInterval(schedulesTimer);
|
|
@@ -13380,11 +13420,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13380
13420
|
// logged and shutdown finishes anyway, or the process ignores SIGTERM forever.
|
|
13381
13421
|
for (const exit of exits) if (exit.status === "rejected") log(`peer stop failed during shutdown: ${(exit.reason as Error)?.message ?? exit.reason}`);
|
|
13382
13422
|
await runnerStopped;
|
|
13423
|
+
await mergeReadbackPass;
|
|
13383
13424
|
await Promise.all([...modelRelays.values()].map(relay => relay.close()));
|
|
13384
13425
|
await egress?.close();
|
|
13385
13426
|
await webEgress?.close();
|
|
13386
13427
|
await Promise.all([...piReceiptLedgers.values()].map(ledger => ledger.close()));
|
|
13387
13428
|
collectClaudeUsage();
|
|
13429
|
+
quotaEvents.flush();
|
|
13388
13430
|
for (const id of [...researchPending.keys()]) writeResearch(id); // the peers have stopped, so their turns have ended
|
|
13389
13431
|
budget.close();
|
|
13390
13432
|
schedulesStore.close();
|