@staix/agent-hub 0.42.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 +42 -0
- package/README.md +2 -1
- package/docs/adding-an-ai-tool.md +2 -0
- package/docs/agent-notes/daemon.md +3 -3
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/tasks.md +3 -2
- package/docs/agent-notes/tests.md +2 -2
- package/docs/design/adapters.md +3 -0
- package/docs/design/agent-hub-architecture.md +2 -0
- package/docs/design/bus.md +2 -0
- package/docs/design/supervision.md +13 -1
- package/docs/design/task-board.md +13 -1
- package/docs/dogfood.md +13 -3
- package/docs/events.md +4 -2
- package/docs/memory.md +5 -3
- package/docs/operations.md +97 -17
- package/docs/quickstart.md +18 -2
- package/docs/research.md +2 -0
- package/docs/sdlc.md +6 -3
- package/docs/security.md +2 -2
- package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
- package/docs/verification/2026-11-18-0.43.0.md +56 -0
- package/docs/verification/2026-11-19-0.44.0.md +60 -0
- package/docs/verified.json +25 -25
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +486 -218
- package/plugins/agent-hub/server.js +505 -234
- 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/help.ts +3 -3
- package/src/cli/identity.ts +2 -0
- package/src/cli/main.ts +57 -5
- package/src/cli/output.ts +2 -2
- package/src/cli/sdlc-output.ts +7 -1
- 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/cli/upgrade.ts +9 -3
- package/src/hub/board.ts +17 -2
- package/src/hub/bus.ts +4 -0
- package/src/hub/claude-shell-wrapper.ts +2 -1
- package/src/hub/config-apply.ts +1 -0
- package/src/hub/control-write-trace.ts +39 -2
- package/src/hub/daemon.ts +141 -37
- package/src/hub/envelope.ts +1 -0
- package/src/hub/facts.ts +30 -0
- package/src/hub/handoff.ts +14 -0
- package/src/hub/hub-tools.ts +1 -1
- package/src/hub/questions.ts +7 -0
- package/src/hub/quota-events.ts +40 -0
- package/src/hub/recovery-store.ts +57 -0
- package/src/hub/report.ts +1 -1
- package/src/hub/research-quality.ts +5 -1
- package/src/hub/research-record.ts +5 -3
- package/src/hub/restart.ts +49 -2
- package/src/hub/runtime-capture-prune.ts +123 -4
- package/src/hub/runtime-prune-health.ts +10 -2
- package/src/hub/sdlc-merge.ts +7 -3
- package/src/hub/sdlc-metrics.ts +17 -8
- package/src/hub/sdlc.ts +18 -6
- package/src/hub/settings.ts +2 -0
- 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/task-sweep.ts +6 -2
- package/src/hub/tasks.ts +131 -22
- package/src/hub/turn-attribution.ts +46 -0
- 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/templates/AGENTS.block.md +1 -1
package/src/hub/tasks.ts
CHANGED
|
@@ -68,7 +68,7 @@ import { folderDetail, MAX_NEW_PER_POLL, scheduleNext, SOURCE_ID, scheduledDetai
|
|
|
68
68
|
import { INTAKE_MAX_SOURCES, INTAKE_MAX_TEXT, intakeDetail, intakeSystemPrompt, intakeUserMessage, parseIntakeDetail, parseIntakeSplit, plannerRequestBody } from "./intake.ts";
|
|
69
69
|
import { DEFAULT_BAND, EPISODE_LOOKBACK, sdlcMetrics, type BandMetric, type BandResult, type MetricTask, type MetricsReport, type SeriesPoint } from "./sdlc-metrics.ts";
|
|
70
70
|
import { readSecurityScan } from "./security-baseline.ts";
|
|
71
|
-
import { cleanMergeCost } from "./cost-governance.ts";
|
|
71
|
+
import { cleanMergeCost, mergeCostFrom } from "./cost-governance.ts";
|
|
72
72
|
import type { InstancesConfig } from "./instances.ts";
|
|
73
73
|
import { composeRememberText } from "./memory-fail.ts";
|
|
74
74
|
import { VERSION } from "../version.ts";
|
|
@@ -76,7 +76,7 @@ import { NoWriteTurns } from "./no-writes.ts";
|
|
|
76
76
|
import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
|
|
77
77
|
import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
|
|
78
78
|
import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
|
|
79
|
-
import { adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
|
|
79
|
+
import { MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
|
|
80
80
|
import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirror.ts";
|
|
81
81
|
import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
|
|
82
82
|
import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
|
|
@@ -126,7 +126,7 @@ import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
|
|
|
126
126
|
import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
|
|
127
127
|
import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskWait, TASK_WAIT_MAX_MS, TASK_WAIT_REASON_MAX, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
|
|
128
128
|
import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts";
|
|
129
|
-
import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
|
|
129
|
+
import { planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type ReadbackMergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
|
|
130
130
|
|
|
131
131
|
/** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */
|
|
132
132
|
const PERSON_RUN_SPLIT = "a person-run card is the person's to split: its children would be unmarked cards an agent could take (the person's own split marks every child person-run)";
|
|
@@ -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;
|
|
@@ -243,7 +245,7 @@ export interface TasksDeps {
|
|
|
243
245
|
auditSource?: AuditSource;
|
|
244
246
|
/** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
|
|
245
247
|
ciWatch?: { deadlineMs?: number; pollMs?: number };
|
|
246
|
-
/** #785 P1c: `tasks.auto_pull`, read
|
|
248
|
+
/** #785 P1c: `tasks.auto_pull`, read for every automatic pull trigger; absent or false pulls nothing. */
|
|
247
249
|
autoPull?: () => boolean;
|
|
248
250
|
briefs?: Briefs;
|
|
249
251
|
/** Screened live fail notes directly intersecting the task plan or refs; read-only advice. */
|
|
@@ -407,6 +409,8 @@ QUIET_EVENTS.add("plan observed"); // Host observation does not move the task or
|
|
|
407
409
|
QUIET_EVENTS.add("planner changed"); // Planning authority does not move the execution owner or revoke its handoff.
|
|
408
410
|
QUIET_EVENTS.add("claim verdict"); // #901: a person's bookkeeping on a plan claim moves nothing, so it must not turn a running check into "check finished late".
|
|
409
411
|
QUIET_EVENTS.add("invocation");
|
|
412
|
+
QUIET_EVENTS.add("check run passed"); // Isolated check bookkeeping does not invalidate an in-flight completion check.
|
|
413
|
+
QUIET_EVENTS.add("check run failed");
|
|
410
414
|
QUIET_EVENTS.add("wait recorded"); // #1454: a recorded wait moves nothing; it only suspends the idle-owner ladder, so it must not turn a running check into "check finished late".
|
|
411
415
|
QUIET_EVENTS.add("shell branch bound"); // #880: the hub's host-observed branch binding (#845) is bookkeeping; it neither moves nor settles the task.
|
|
412
416
|
/** The records of the `done (checking)` entry a passed check now completes: what the owner delivered then (#509a). */
|
|
@@ -858,6 +862,7 @@ export class Tasks {
|
|
|
858
862
|
/** #785 P1b: one bounded CI watcher per exact PR head, and the reviews the hub held as premature, by task id. */
|
|
859
863
|
private readonly ciWatchers: CiWatchers;
|
|
860
864
|
private readonly heldReviews = new Map<number, { head: string; reviewer: PeerId; revision: number }>();
|
|
865
|
+
private readonly autoPullAttached = new Set<PeerId>();
|
|
861
866
|
|
|
862
867
|
constructor(private readonly d: TasksDeps) {
|
|
863
868
|
this.ciWatchers = new CiWatchers({
|
|
@@ -888,7 +893,15 @@ export class Tasks {
|
|
|
888
893
|
});
|
|
889
894
|
// What the on-prem worker says about a PII task is private on the bus (console tail and log show a stub), so the
|
|
890
895
|
// board keeps the text: `ahub task show <id>` is where the console user reads it, a refusal included.
|
|
896
|
+
d.bus.onPeerAdded = peer => {
|
|
897
|
+
this.autoPullAttached.delete(peer);
|
|
898
|
+
if (d.bus.stateOf(peer) === "idle") this.autoPullForAttachment(peer);
|
|
899
|
+
};
|
|
891
900
|
d.bus.tap((e) => {
|
|
901
|
+
if (e.t === "state" && e.state === "offline") this.autoPullAttached.delete(e.peer);
|
|
902
|
+
if (e.t === "state" && e.state === "idle" && !this.autoPullAttached.has(e.peer) && this.d.autoPull?.() === true) {
|
|
903
|
+
this.autoPullForAttachment(e.peer);
|
|
904
|
+
}
|
|
892
905
|
if (e.t === "overflow" && e.env.from === HUB && e.env.kind === "task" && Array.isArray(e.env.refs?.backlog)) {
|
|
893
906
|
const ids = e.env.refs.backlog;
|
|
894
907
|
if (ids.length <= 64 && ids.every(id => Number.isSafeInteger(id) && id > 0)) this.addPlannerBacklog(e.peer, ids);
|
|
@@ -906,6 +919,12 @@ export class Tasks {
|
|
|
906
919
|
});
|
|
907
920
|
}
|
|
908
921
|
|
|
922
|
+
private autoPullForAttachment(peer: PeerId): void {
|
|
923
|
+
if (this.autoPullAttached.has(peer) || this.d.autoPull?.() !== true) return;
|
|
924
|
+
this.autoPullAttached.add(peer);
|
|
925
|
+
if (this.topReservedReady(peer, undefined, true)) this.queueAutoPulls(new Set([peer]), "peer available");
|
|
926
|
+
}
|
|
927
|
+
|
|
909
928
|
isPii = (task: Pick<Task, "signals">) => task.signals.includes("pii_path") || (task.signals.includes("pii") && this.d.routing().constraints.pii === "local_only");
|
|
910
929
|
|
|
911
930
|
private signalsFor(task: Pick<Task, "title" | "detail" | "refs"> & { plan?: TaskPlan }, routing = this.d.routing()) {
|
|
@@ -974,7 +993,8 @@ export class Tasks {
|
|
|
974
993
|
for (const task of this.d.board.list()) {
|
|
975
994
|
if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break;
|
|
976
995
|
if (!task.owner && this.personUnassigned(task)) continue;
|
|
977
|
-
const
|
|
996
|
+
const questionWait = task.state === "in_progress" && task.owner ? this.d.ownerQuestionWait?.(task.id, task.owner) : undefined;
|
|
997
|
+
const finding = nextSweep(task, config, now, this.waitsFor(task).length === 0 && !plannedStartPending(task, now), questionWait);
|
|
978
998
|
if (!finding || this.waitsFor(task).length || this.isChecking(task.id) || this.silentFor(task.id)) continue;
|
|
979
999
|
if (finding.kind === "ready-unassigned") {
|
|
980
1000
|
this.d.board.update(task.id, HUB, "idle sweep", {}, undefined, { sweep: finding });
|
|
@@ -3070,9 +3090,13 @@ export class Tasks {
|
|
|
3070
3090
|
changes.set(planner, change);
|
|
3071
3091
|
};
|
|
3072
3092
|
const released = new Set<PeerId>();
|
|
3093
|
+
const readied = new Set<PeerId>();
|
|
3073
3094
|
for (const [peer, used] of before) if (this.wip(peer) < used) { released.add(peer); for (const planner of this.taskPlanner(task)) add(planner, peer); }
|
|
3074
3095
|
if (approved) for (const card of this.d.board.list("backlog")) {
|
|
3075
|
-
if (card.deps?.includes(task.id) && !this.waitsFor(card).length && !plannedStartPending(card, now))
|
|
3096
|
+
if (card.deps?.includes(task.id) && !this.waitsFor(card).length && !plannedStartPending(card, now)) {
|
|
3097
|
+
for (const planner of this.taskPlanner(card)) add(planner, undefined, card.id);
|
|
3098
|
+
if (card.reserved) readied.add(card.reserved);
|
|
3099
|
+
}
|
|
3076
3100
|
}
|
|
3077
3101
|
for (const [planner, change] of changes) this.releaseNotice(`could not notify planner ${planner} about ready work`, () => {
|
|
3078
3102
|
const pending = this.d.bus.pendingEnvelopes(planner).filter(env => env.from === HUB && env.kind === "task" && env.body.startsWith("Planner work ready:"));
|
|
@@ -3097,8 +3121,9 @@ export class Tasks {
|
|
|
3097
3121
|
const env = newEnvelope(HUB, sanitize(`Planner work ready:\n${lines.join("\n")}\nRead the current board before planning or pulling work.`), { to: [planner], kind: "task" });
|
|
3098
3122
|
if (!this.d.bus.publish(env).includes(planner)) throw new Error("the notice was not queued");
|
|
3099
3123
|
});
|
|
3100
|
-
//
|
|
3124
|
+
// Only this write's own release or newly ready dependency, never a merged earlier notice.
|
|
3101
3125
|
if (this.d.autoPull?.() === true) this.queueAutoPulls(released);
|
|
3126
|
+
if (this.d.autoPull?.() === true) this.queueAutoPulls(new Set([...readied].filter(peer => !released.has(peer))), "backlog ready");
|
|
3102
3127
|
});
|
|
3103
3128
|
}
|
|
3104
3129
|
|
|
@@ -3111,32 +3136,32 @@ export class Tasks {
|
|
|
3111
3136
|
}
|
|
3112
3137
|
|
|
3113
3138
|
/**
|
|
3114
|
-
* #785 P1c: `tasks.auto_pull`. A
|
|
3139
|
+
* #785 P1c: `tasks.auto_pull`. A trigger pulls the one top backlog card explicitly reserved for a peer, through `pullPlanned` as the hub acting for that card's planner of
|
|
3115
3140
|
* record: revision, dependency, reservation, pinned, frozen-release, P0 order and WIP checks all run there unchanged. One card per release. Never an unreserved card, never PII.
|
|
3116
|
-
* Serialized on one chain, so
|
|
3141
|
+
* Serialized on one chain, so concurrent triggers cannot pick the same card; each job re-reads the board, so a card that moved meanwhile is skipped.
|
|
3117
3142
|
*/
|
|
3118
3143
|
private autoPulls: Promise<void> = Promise.resolve();
|
|
3119
3144
|
private autoPullsOpen = 0;
|
|
3120
3145
|
/** Queued or running auto pulls, so a recovery commit waits for them the way it waits for `checksPending` (#785 P1c): one that is mid-admission would otherwise write after the commit's digest. */
|
|
3121
3146
|
autoPullsPending = (): number => this.autoPullsOpen;
|
|
3122
|
-
private queueAutoPulls(released: ReadonlySet<PeerId
|
|
3147
|
+
private queueAutoPulls(released: ReadonlySet<PeerId>, cause = "capacity released"): void {
|
|
3123
3148
|
for (const peer of released) {
|
|
3124
3149
|
this.autoPullsOpen++;
|
|
3125
|
-
this.autoPulls = this.autoPulls.then(() => this.autoPull(peer)).catch(() => { /* autoPull reports its own refusals */ }).finally(() => { this.autoPullsOpen--; });
|
|
3150
|
+
this.autoPulls = this.autoPulls.then(() => this.autoPull(peer, cause)).catch(() => { /* autoPull reports its own refusals */ }).finally(() => { this.autoPullsOpen--; });
|
|
3126
3151
|
}
|
|
3127
3152
|
}
|
|
3128
3153
|
/** Whether the hub may still start work on its own: the setting is on, and no recovery, shutdown or storage hold is active. Read at entry and again right before the assignment write. */
|
|
3129
3154
|
private autoPullAdmitted(): boolean {
|
|
3130
3155
|
return this.d.autoPull?.() === true && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError;
|
|
3131
3156
|
}
|
|
3132
|
-
private async autoPull(peer: PeerId): Promise<void> {
|
|
3157
|
+
private async autoPull(peer: PeerId, cause: string): Promise<void> {
|
|
3133
3158
|
if (!this.autoPullAdmitted()) return;
|
|
3134
3159
|
const card = this.topReservedReady(peer, undefined, true);
|
|
3135
3160
|
if (!card) return;
|
|
3136
3161
|
// The planner of record is the card's own: its bound planner, else the first current holder, and it must be rostered. A private card never gets here (topReservedReady skips it).
|
|
3137
3162
|
const planner = this.taskPlanner(card)[0];
|
|
3138
3163
|
if (!planner || !this.d.bus.isRostered(planner)) return;
|
|
3139
|
-
const reason = `auto_pull:
|
|
3164
|
+
const reason = `auto_pull: ${cause} for ${peer}; hub acted for planner ${planner}`;
|
|
3140
3165
|
try {
|
|
3141
3166
|
await this.pullPlanned(HUB, { id: card.id, revision: card.planningRevision ?? 0, reason }, { onBehalfOf: planner, guard: () => {
|
|
3142
3167
|
if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted: tasks.auto_pull was turned off or a recovery, shutdown or storage hold began");
|
|
@@ -3801,6 +3826,8 @@ export class Tasks {
|
|
|
3801
3826
|
catch (error) { throw new PreEffectToolRefusal((error as Error).message); }
|
|
3802
3827
|
const updated = this.d.board.plan(task.id, by, patch, input.revision, input.reason.trim(), withheld, receipt);
|
|
3803
3828
|
this.planningRecorded({ by, task: task.id, fields: Object.keys(patch), revision: updated.planningRevision! });
|
|
3829
|
+
if (updated.state === "backlog" && updated.reserved && ["reserved", "pinned", "deps", "plannedStart", "release", "needsPerson"].some(key => Object.hasOwn(patch, key)) && this.d.autoPull?.() === true)
|
|
3830
|
+
this.queueAutoPulls(new Set([updated.reserved]), "backlog planned");
|
|
3804
3831
|
return updated; // persistence/readback failures must never claim no effect
|
|
3805
3832
|
}
|
|
3806
3833
|
|
|
@@ -6775,7 +6802,7 @@ export class Tasks {
|
|
|
6775
6802
|
}
|
|
6776
6803
|
const rows = this.d.board.list();
|
|
6777
6804
|
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 } : {}) })) }));
|
|
6805
|
+
...(["check run passed", "check run failed"].includes(entry.event) && entry.requestHead ? { requestHead: entry.requestHead } : {}), ...(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
6806
|
const visibleIds = new Set(rows.filter(task => !this.isPii(task)).map(task => task.id));
|
|
6780
6807
|
const byKind: Record<string, number> = {};
|
|
6781
6808
|
for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1;
|
|
@@ -6783,14 +6810,22 @@ export class Tasks {
|
|
|
6783
6810
|
// #481 S7: the merge-time readback the guarded merge recorded on each merged task's receipt (host-written, never a tool input), and the two series that are not made of tasks.
|
|
6784
6811
|
const mergedAt: Record<number, number> = {}, ciReruns: Record<number, number | null> = {}, ciRuns: Record<number, number | null> = {}, reviews: Record<number, number | null> = {};
|
|
6785
6812
|
for (const task of rows) {
|
|
6786
|
-
const
|
|
6813
|
+
const guarded = task.sdlc?.merge;
|
|
6814
|
+
const merge = guarded?.state === "merged" ? guarded : task.sdlc?.mergeReadback;
|
|
6787
6815
|
if (!visibleIds.has(task.id) || merge?.state !== "merged") continue;
|
|
6788
6816
|
const cost = cleanMergeCost(merge.cost);
|
|
6789
|
-
const at = cost?.mergedAt ?? (Number.isSafeInteger(merge.at) ? merge.at : null);
|
|
6817
|
+
const at = cost?.mergedAt ?? (merge === guarded && Number.isSafeInteger(merge.at) ? merge.at : null);
|
|
6790
6818
|
if (at !== null) mergedAt[task.id] = at;
|
|
6791
6819
|
if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; }
|
|
6792
6820
|
}
|
|
6793
|
-
return sdlcMetrics(tasks, { ...(cutoff !== undefined ? { since: cutoff } : {}), ...(this.d.sdlc?.config().bands ? { bands: this.d.sdlc.config().bands } : {}), stalls, mergedAt, ciReruns, ciRuns, reviews, external: this.externalSeries(), ...(merged ?? {}) });
|
|
6821
|
+
return { ...sdlcMetrics(tasks, { ...(cutoff !== undefined ? { since: cutoff } : {}), ...(this.d.sdlc?.config().bands ? { bands: this.d.sdlc.config().bands } : {}), stalls, mergedAt, ciReruns, ciRuns, reviews, external: this.externalSeries(), ...(merged ?? {}) }), ...(this.securityScanCounts() ? { securityScan: this.securityScanCounts() } : {}) };
|
|
6822
|
+
}
|
|
6823
|
+
|
|
6824
|
+
/** Latest configured scan source counts; no repository or alert text is projected. */
|
|
6825
|
+
securityScanCounts(): Record<string, number | null> | undefined {
|
|
6826
|
+
const scan = this.d.sdlc?.config().securityScan, repo = scan?.repo ?? this.d.repository;
|
|
6827
|
+
if (!scan || typeof repo !== "string" || !this.nameable(repo)) return undefined;
|
|
6828
|
+
return this.d.board.latestSecurityScanCounts(repo, scan.sources.join(","));
|
|
6794
6829
|
}
|
|
6795
6830
|
|
|
6796
6831
|
/** #481 S7: one point per shipped release (1 for a hotfix, 0 otherwise; a release with no recorded train is skipped, never a 0) and one per recorded security scan whose total is known. */
|
|
@@ -7748,12 +7783,19 @@ export class Tasks {
|
|
|
7748
7783
|
return result;
|
|
7749
7784
|
};
|
|
7750
7785
|
const evidence = await readAdoptMergeEvidence(receipt, run);
|
|
7751
|
-
|
|
7786
|
+
current();
|
|
7752
7787
|
const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
|
|
7753
7788
|
if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
|
|
7754
|
-
const
|
|
7789
|
+
const costDeadline = performance.now() + MERGE_READBACK_DEADLINE_MS;
|
|
7790
|
+
const cost = evidence?.costSnapshot ? await readPrCostHistory(repo, pr as number, (args, timeout, cwd, cap) => {
|
|
7791
|
+
const remaining = costDeadline - performance.now();
|
|
7792
|
+
return remaining > 0 ? run(args, Math.min(timeout ?? remaining, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
|
|
7793
|
+
}, evidence.costSnapshot, head).then(pr => pr?.complete ? mergeCostFrom(pr) : undefined, () => undefined) : undefined;
|
|
7794
|
+
const latest = current();
|
|
7795
|
+
const merge: ReadbackMergeRecord = { repo, pr: pr as number, head, at: Date.now(), state: "merged", ...(evidence?.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
|
|
7796
|
+
const capacity = this.capacityBefore(latest);
|
|
7755
7797
|
current(); // No await between the last authority/privacy/flow check and the sole approval write.
|
|
7756
|
-
const next = this.d.board.adoptMerge(
|
|
7798
|
+
const next = this.d.board.adoptMerge(latest.id, by, { ...receipt, mergeReadback: merge }, head, latest.history.length, HOST_MERGE_ADOPTION);
|
|
7757
7799
|
this.cohorts.closed(next.id);
|
|
7758
7800
|
this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id);
|
|
7759
7801
|
this.writePlannerNotices(next, capacity, true);
|
|
@@ -7835,6 +7877,61 @@ export class Tasks {
|
|
|
7835
7877
|
if(!current.history.some(h=>h.by===HUB && h.event==="merge refused" && h.note===note))
|
|
7836
7878
|
this.d.board.update(id,HUB,"merge refused",{},note,{...(this.isPii(current)||this.d.privateTurn?.(by)?{withheld:true}:{})});
|
|
7837
7879
|
}
|
|
7880
|
+
/** Observe one eligible externally merged approved PR without mutating GitHub. */
|
|
7881
|
+
async captureExternalMerge(id: number): Promise<"merged" | "closed" | "retry" | "skip"> {
|
|
7882
|
+
const task = this.d.board.get(id), config = this.d.sdlc?.config(), receipt = task?.sdlc;
|
|
7883
|
+
const repo = receipt?.repo, pr = receipt?.pr, head = task && this.reviewHead(task);
|
|
7884
|
+
if (!task || task.state !== "approved" || this.isPii(task) || (task.owner && this.d.privateTurn?.(task.owner)) || !config || !repo || !pr || !head || !/^[a-f0-9]{40}$/.test(head)
|
|
7885
|
+
|| this.repositories.scope(task.refs).key !== this.repositories.scope({ repo }).key || mergeModeFor(config, repo) !== "off" || (receipt?.merge?.state === "merged" || receipt?.mergeReadback?.state === "merged") || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return "skip";
|
|
7886
|
+
const identity = JSON.stringify([task.history.length, task.updated, task.owner, receipt, config]);
|
|
7887
|
+
const current = () => {
|
|
7888
|
+
const now = this.d.board.get(id), policy = this.d.sdlc?.config();
|
|
7889
|
+
return !!now && !this.isPii(now) && !(now.owner && this.d.privateTurn?.(now.owner)) && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError
|
|
7890
|
+
&& JSON.stringify([now.history.length, now.updated, now.owner, now.sdlc, policy]) === identity;
|
|
7891
|
+
};
|
|
7892
|
+
const deadline = performance.now() + MERGE_READBACK_DEADLINE_MS;
|
|
7893
|
+
const run: SdlcGh = (args, timeout, cwd, cap) => {
|
|
7894
|
+
const remaining = deadline - performance.now();
|
|
7895
|
+
return current() && remaining > 0 ? (this.d.sdlc?.gh ?? sdlcGh)(args, Math.min(timeout ?? remaining, remaining), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
|
|
7896
|
+
};
|
|
7897
|
+
const evidence = await readSdlcPr(receipt!, run).catch(() => undefined);
|
|
7898
|
+
if (!current()) return "skip";
|
|
7899
|
+
if (evidence?.state === "CLOSED") return "closed";
|
|
7900
|
+
if (evidence?.state !== "MERGED" || evidence.head !== head) return "retry";
|
|
7901
|
+
const cost = await readPrCostHistory(repo, pr, run, undefined, head).then(value => value?.complete ? mergeCostFrom(value) : undefined, () => undefined);
|
|
7902
|
+
if (!current()) return "skip";
|
|
7903
|
+
const now = this.d.board.get(id)!;
|
|
7904
|
+
const merge: ReadbackMergeRecord = { repo, pr, head, at: Date.now(), state: "merged", ...(evidence.mergeCommit ? { mergeCommit: evidence.mergeCommit } : {}), ...(cost ? { cost } : {}) };
|
|
7905
|
+
this.d.board.update(id, HUB, "merge observed", { sdlc: { ...now.sdlc!, mergeReadback: merge } }, undefined, {}, now.history.length);
|
|
7906
|
+
return "merged";
|
|
7907
|
+
}
|
|
7908
|
+
|
|
7909
|
+
// ponytail: this in-memory schedule is lost on restart; only approvals still within 24 hours are retried.
|
|
7910
|
+
private readonly mergeReadbackSchedule = new Map<number, { approval: number; next: number; closed: boolean }>();
|
|
7911
|
+
private mergeReadbackRunning = false;
|
|
7912
|
+
async settleMergeReadbacks(now = Date.now()): Promise<void> {
|
|
7913
|
+
if (this.mergeReadbackRunning || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) return;
|
|
7914
|
+
this.mergeReadbackRunning = true;
|
|
7915
|
+
try {
|
|
7916
|
+
let reads = 0;
|
|
7917
|
+
// Unseen work goes first, then the least recently scheduled read, so a busy backlog cannot starve later tasks.
|
|
7918
|
+
const candidates = this.d.board.list().sort((a, b) => (this.mergeReadbackSchedule.get(a.id)?.next ?? -Infinity) - (this.mergeReadbackSchedule.get(b.id)?.next ?? -Infinity) || a.id - b.id);
|
|
7919
|
+
for (const task of candidates) {
|
|
7920
|
+
if (reads >= 3 || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) break;
|
|
7921
|
+
if (task.state !== "approved" || this.isPii(task) || !task.sdlc?.repo || !task.sdlc.pr || task.sdlc.merge || task.sdlc.mergeReadback) { this.mergeReadbackSchedule.delete(task.id); continue; }
|
|
7922
|
+
const approval = task.history.findLastIndex(entry => entry.event === "approved" || entry.event === "done" && entry.by === task.owner);
|
|
7923
|
+
const at = task.history[approval]?.at;
|
|
7924
|
+
if (approval < 0 || at === undefined || now < at || now - at >= 24 * 60 * 60_000) { this.mergeReadbackSchedule.delete(task.id); continue; }
|
|
7925
|
+
const previous = this.mergeReadbackSchedule.get(task.id);
|
|
7926
|
+
if (previous?.approval === approval && (previous.closed || now < previous.next)) continue;
|
|
7927
|
+
this.mergeReadbackSchedule.set(task.id, { approval, next: now + 10 * 60_000, closed: false });
|
|
7928
|
+
reads++;
|
|
7929
|
+
const outcome = await this.captureExternalMerge(task.id).catch(() => "retry" as const);
|
|
7930
|
+
if (outcome === "closed") this.mergeReadbackSchedule.set(task.id, { approval, next: now + 10 * 60_000, closed: true });
|
|
7931
|
+
}
|
|
7932
|
+
} finally { this.mergeReadbackRunning = false; }
|
|
7933
|
+
}
|
|
7934
|
+
|
|
7838
7935
|
private mergeRecordCurrent(id:number,by:PeerId,record:MergeRecord,artifactCurrent:()=>boolean):Task|undefined {
|
|
7839
7936
|
const now=this.d.board.get(id);
|
|
7840
7937
|
return artifactCurrent() && now && now.sdlc?.repo===record.repo && now.sdlc.pr===record.pr && now.sdlc.reviewedHead===record.head
|
|
@@ -8322,7 +8419,7 @@ export class Tasks {
|
|
|
8322
8419
|
if (!Number.isInteger(n)) throw new (preEffect ? PreEffectToolRefusal : Error)(`id must be a task number, not ${(typeof id === "number" ? String(id) : JSON.stringify(id ?? null)).slice(0, 60)}`);
|
|
8323
8420
|
const task = this.d.board.get(n);
|
|
8324
8421
|
if (!task) throw new (preEffect ? PreEffectToolRefusal : Error)(`no task #${n}`);
|
|
8325
|
-
if (task.state === "backlog" && !allowBacklog) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${n} is backlog: pull it into To Do first`);
|
|
8422
|
+
if (task.state === "backlog" && !allowBacklog) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${n} is in backlog: a planner or person must pull it into To Do first (hub_backlog_pull)`);
|
|
8326
8423
|
// Handing a task to someone else only makes sense while there is work left on it.
|
|
8327
8424
|
if (open && !OPEN.includes(task.state)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: it can no longer change hands`);
|
|
8328
8425
|
return task;
|
|
@@ -8802,6 +8899,7 @@ export class Tasks {
|
|
|
8802
8899
|
if (sdlc.reviewedHead !== refresh.commit) delete sdlc.reviewedHead;
|
|
8803
8900
|
if (sdlc.localHead !== refresh.commit) { delete sdlc.localHead; delete sdlc.localResult; }
|
|
8804
8901
|
delete sdlc.merge;
|
|
8902
|
+
delete sdlc.mergeReadback;
|
|
8805
8903
|
return { ...task, sdlc };
|
|
8806
8904
|
}
|
|
8807
8905
|
|
|
@@ -9044,6 +9142,15 @@ export class Tasks {
|
|
|
9044
9142
|
return [head, "The done counts once the files did not change between two calls and the others have stopped.", ...lines, facts?.text ?? ""].filter(Boolean).join("\n");
|
|
9045
9143
|
}
|
|
9046
9144
|
|
|
9145
|
+
/** Record an already-admitted isolated run without retaining its output. */
|
|
9146
|
+
recordCheckResult(receipt: import("./check-runner.ts").RunReceipt): void {
|
|
9147
|
+
const task = this.d.board.get(receipt.task);
|
|
9148
|
+
if (!task || task.state !== "in_progress" || task.owner !== receipt.owner) return;
|
|
9149
|
+
const passed = receipt.exit === 0 && !receipt.timed_out && !receipt.cancelled && !receipt.interrupted;
|
|
9150
|
+
this.d.board.update(task.id, HUB, passed ? "check run passed" : "check run failed", {}, undefined,
|
|
9151
|
+
{ checkKey: receipt.check, requestHead: receipt.sha }, task.history.length);
|
|
9152
|
+
}
|
|
9153
|
+
|
|
9047
9154
|
/**
|
|
9048
9155
|
* #901: which check key produced this result, and how many citation keys the example citation check said were unresolved. The key is the hub's own selection (`Deps.checkKey`, the lookup
|
|
9049
9156
|
* `Deps.check` makes), never read from output; without that dependency it is not recorded. The count is read only from the example check's own last line (`citations: N declared keys, M missing`, scripts/check-citations.ts);
|
|
@@ -9138,6 +9245,8 @@ export class Tasks {
|
|
|
9138
9245
|
if (specInspection?.report?.head && !completedRefs.commit) completedRefs.commit = specInspection.report.head;
|
|
9139
9246
|
if (specInspection?.report && specInspection.repo && !completedRefs.repo) completedRefs.repo = specInspection.repo;
|
|
9140
9247
|
const storedRefs = { ...task.refs, ...completedRefs };
|
|
9248
|
+
const requestedHead = completedRefs.commit ?? admission?.head ?? specInspection?.report?.head;
|
|
9249
|
+
const requestHead = requestedHead && /^[a-f0-9]{40}$/.test(requestedHead) ? requestedHead : undefined;
|
|
9141
9250
|
if (specInspection) {
|
|
9142
9251
|
if (asyncCheckCompletion) {
|
|
9143
9252
|
if (this.refreshAsyncSpecInspection(specInspection, { ...task, refs: storedRefs }, by)) { this.requestSpecRefile(task); return task; }
|
|
@@ -9148,7 +9257,7 @@ export class Tasks {
|
|
|
9148
9257
|
const capacity = this.capacityBefore(task);
|
|
9149
9258
|
reviewObserverExcluded ||= this.reviewObserverTurn(by, task.id);
|
|
9150
9259
|
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);
|
|
9260
|
+
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
9261
|
this.queueReviewWritten(next);
|
|
9153
9262
|
this.writePlannerNotices(next, capacity, next.state === "approved");
|
|
9154
9263
|
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
|
+
}
|
|
@@ -113,7 +113,8 @@ export function boundTask(tasks: readonly Pick<Task, "id" | "state" | "refs" | "
|
|
|
113
113
|
* action, which reads GitHub, may learn `closed` or `open` (a later change).
|
|
114
114
|
*/
|
|
115
115
|
export function prFromTask(task: Pick<Task, "state" | "sdlc" | "history"> | undefined, observed?: PrObserver): WorktreeFact["pr"] {
|
|
116
|
-
const
|
|
116
|
+
const guarded = task?.sdlc?.merge;
|
|
117
|
+
const merge = guarded?.state === "merged" ? guarded : task?.sdlc?.mergeReadback;
|
|
117
118
|
if (merge && merge.state === "merged" && Number.isFinite(merge.at)) return { state: "merged", changedAt: merge.at };
|
|
118
119
|
// A PR state the person asked the hub to read (the explicit refresh action) is a stored fact, never fetched here: this module has no GitHub access (AC5).
|
|
119
120
|
const repo = task?.sdlc?.repo, pr = task?.sdlc?.pr;
|
package/src/local/sandbox.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { realPath } from "../hub/project.ts";
|
|
|
6
6
|
import { hubGitSync } from "../hub/git.ts";
|
|
7
7
|
import { denyRegexes, hubWriteRegexes, objectStoreRules, sbplString } from "./deny.ts";
|
|
8
8
|
import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
|
|
9
|
+
import { sandboxCommandEnvironment } from "./shell-environment.ts";
|
|
9
10
|
|
|
10
11
|
const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
|
|
11
12
|
export const OUTPUT_CAP = 20_000;
|
|
@@ -216,7 +217,7 @@ export function sandboxedExec(argv: string[], opts: { cwd: string; profile: stri
|
|
|
216
217
|
const own = realPath(mkdtempSync(join(tmpdir(), "ahub-cmd-")));
|
|
217
218
|
const sandbox = `${opts.profile}\n(allow file-read* ${opts.readOnlyData ? "" : "file-write* "}process-exec (subpath ${q(own)}))`;
|
|
218
219
|
// A path-only deny cannot contain hardlink aliases; data mode allows reads/stdout, never filesystem writes.
|
|
219
|
-
const env = { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env,
|
|
220
|
+
const env = sandboxCommandEnvironment({ PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env }, own);
|
|
220
221
|
// Own process group: a timeout has to take the grandchildren too, or they keep the pipes open and the project writable.
|
|
221
222
|
const child = spawn(SANDBOX_EXEC, ["-p", sandbox, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
222
223
|
let output = "";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
2
3
|
|
|
3
4
|
export interface HostShellEnvironment extends Record<string, string> { PATH: string; HOME: string; LANG: string; TERM: string }
|
|
4
5
|
|
|
@@ -8,3 +9,8 @@ export interface HostShellEnvironment extends Record<string, string> { PATH: str
|
|
|
8
9
|
export function hostShellEnvironment(extra: Readonly<Record<string, string>> = {}): HostShellEnvironment {
|
|
9
10
|
return { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...extra };
|
|
10
11
|
}
|
|
12
|
+
|
|
13
|
+
/** Per-command cache defaults are confined to the same owned temp directory as TMPDIR. */
|
|
14
|
+
export function sandboxCommandEnvironment(base: Readonly<Record<string, string>>, own: string): Record<string, string> {
|
|
15
|
+
return { BUN_INSTALL_CACHE_DIR: join(own, "bun-cache"), NPM_CONFIG_CACHE: join(own, "npm-cache"), ...base, TMPDIR: `${own}/` };
|
|
16
|
+
}
|
package/src/memory/brief.ts
CHANGED
|
@@ -67,6 +67,7 @@ export interface RecordBriefPort {
|
|
|
67
67
|
maxBytes?: number | (() => number);
|
|
68
68
|
}
|
|
69
69
|
const RECORD_ROWS = 32, RECORD_BYTES = 2048;
|
|
70
|
+
const INTENT_SCREEN_BATCH = 32;
|
|
70
71
|
const LEGACY_KNOWLEDGE_HEADER = "Knowledge brief (advice, not a block):";
|
|
71
72
|
const LEGACY_NATIVE_HEADER = "Memory brief (hub memory first, fails first: ahub memory show <mem id>; amem by mem:id):";
|
|
72
73
|
const LEGACY_CURATED_HEADER = "Memory brief (amem curated notes; fetch details by mem:id):";
|
|
@@ -220,7 +221,15 @@ export class Briefs {
|
|
|
220
221
|
if (!current()) return undefined;
|
|
221
222
|
const seen = this.seen.get(peer) ?? new Set<string>();
|
|
222
223
|
const revision = context.options.policyVersion();
|
|
223
|
-
const
|
|
224
|
+
const policy = context.options.policy(); let screened = 0;
|
|
225
|
+
const result = await buildIntentBrief(context.source, { ...context.options, policy: () => ({ ...policy, screen: async value => {
|
|
226
|
+
const accepted = await policy.screen(value);
|
|
227
|
+
if (++screened % INTENT_SCREEN_BATCH === 0) {
|
|
228
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
229
|
+
context.options.assertCurrent?.();
|
|
230
|
+
}
|
|
231
|
+
return accepted;
|
|
232
|
+
} }) });
|
|
224
233
|
if (!current()) return undefined;
|
|
225
234
|
if (result.state === "unknown" || context.options.allowed?.() === false || context.options.policyVersion() !== revision) return undefined;
|
|
226
235
|
context.options.assertCurrent?.();
|
|
@@ -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.
|