@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.
Files changed (54) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +1 -1
  3. package/docs/agent-notes/daemon.md +3 -3
  4. package/docs/agent-notes/local-worker.md +1 -0
  5. package/docs/agent-notes/tasks.md +2 -1
  6. package/docs/agent-notes/tests.md +1 -1
  7. package/docs/design/agent-hub-architecture.md +2 -0
  8. package/docs/design/supervision.md +13 -1
  9. package/docs/design/task-board.md +7 -1
  10. package/docs/dogfood.md +8 -2
  11. package/docs/events.md +4 -2
  12. package/docs/memory.md +3 -3
  13. package/docs/operations.md +37 -17
  14. package/docs/quickstart.md +8 -2
  15. package/docs/research.md +2 -0
  16. package/docs/sdlc.md +5 -2
  17. package/docs/security.md +2 -2
  18. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  19. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  20. package/docs/verified.json +22 -22
  21. package/package.json +2 -2
  22. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  23. package/plugins/agent-hub/kimi-hook.js +183 -105
  24. package/plugins/agent-hub/server.js +202 -121
  25. package/src/cli/main.ts +1 -1
  26. package/src/cli/output.ts +2 -2
  27. package/src/cli/sdlc-output.ts +7 -1
  28. package/src/cli/upgrade.ts +9 -3
  29. package/src/hub/board.ts +14 -1
  30. package/src/hub/bus.ts +4 -0
  31. package/src/hub/claude-shell-wrapper.ts +2 -1
  32. package/src/hub/control-write-trace.ts +39 -2
  33. package/src/hub/daemon.ts +66 -24
  34. package/src/hub/facts.ts +30 -0
  35. package/src/hub/hub-tools.ts +1 -1
  36. package/src/hub/quota-events.ts +40 -0
  37. package/src/hub/recovery-store.ts +21 -3
  38. package/src/hub/report.ts +1 -1
  39. package/src/hub/research-quality.ts +5 -1
  40. package/src/hub/research-record.ts +3 -2
  41. package/src/hub/restart.ts +49 -2
  42. package/src/hub/runtime-capture-prune.ts +9 -1
  43. package/src/hub/runtime-prune-health.ts +5 -1
  44. package/src/hub/sdlc-merge.ts +7 -3
  45. package/src/hub/sdlc-metrics.ts +15 -6
  46. package/src/hub/sdlc.ts +18 -6
  47. package/src/hub/snapshots.ts +43 -0
  48. package/src/hub/supervision-rules.ts +2 -2
  49. package/src/hub/task-shell-command.ts +124 -0
  50. package/src/hub/tasks.ts +124 -20
  51. package/src/hub/worktree-shelf.ts +2 -1
  52. package/src/local/sandbox.ts +2 -1
  53. package/src/local/shell-environment.ts +6 -0
  54. package/src/memory/brief.ts +10 -1
@@ -83,3 +83,127 @@ export function taskShellCommand(command: unknown, binding: TaskShellBinding): T
83
83
  const file = flags.get("--body-file")!;
84
84
  return literalPath(file) ? result("pr-create", "gh", [file]) : undefined;
85
85
  }
86
+
87
+ export interface ShellWriteClass { kind: "write" | "read" | "unknown"; targets: string[] }
88
+
89
+ const SINK = /^(?:\/dev\/(?:null|stdout|stderr|tty)|&\d+|-)$/;
90
+ const unq = (w: string) => w.replace(/^(['"])(.*)\1$/, "$2");
91
+
92
+ /** Words of one simple command, quotes kept whole (a quoted `>` is not a redirection). */
93
+ function words(cmd: string): string[] | undefined {
94
+ const out: string[] = [];
95
+ let cur = "", q = "";
96
+ for (const c of cmd) {
97
+ if (q) { cur += c; if (c === q) q = ""; continue; }
98
+ if (c === "'" || c === '"') { q = c; cur += c; continue; }
99
+ if (/\s/.test(c)) { if (cur) out.push(cur), (cur = ""); continue; }
100
+ if (c === "`" || c === "$") return undefined; // substitution: not guessed
101
+ if (c === ">" && cur && !/^\d+$/.test(cur) && !/[>&]$/.test(cur)) { out.push(cur); cur = ""; } // `echo hi>f`: the redirection is its own word
102
+ cur += c;
103
+ }
104
+ if (q) return undefined;
105
+ if (cur) out.push(cur);
106
+ return out;
107
+ }
108
+
109
+ const CODE_RUNNER = /(?:^|[\s|;&(])(?:sh|bash|zsh|dash|ksh|python[\d.]*|node|bun|deno|ruby|perl|php)(?:\s|$)/;
110
+
111
+ /**
112
+ * One quote-aware pass: split only at unquoted newline, `;`, `&&`, `||` and `|`, and find `<<WORD` only outside quotes.
113
+ * A heredoc body is data and is skipped, unless its start line runs a shell or interpreter (then it is code) or it
114
+ * never ends: both are unknown. Unbalanced quotes are unknown too.
115
+ */
116
+ function segment(command: string): { parts: string[]; unknown: boolean } {
117
+ const parts: string[] = [];
118
+ let cur = "", q = "", unknown = false, lineStart = 0;
119
+ const heredocs: { word: string; strip: boolean }[] = [];
120
+ const push = () => { if (cur.trim()) parts.push(cur); cur = ""; };
121
+ for (let i = 0; i < command.length; i++) {
122
+ const c = command[i]!;
123
+ if (q) {
124
+ cur += c;
125
+ if (c === "\\" && q === '"' && i + 1 < command.length) cur += command[++i]!;
126
+ else if (c === q) q = "";
127
+ continue;
128
+ }
129
+ if (c === "\\" && i + 1 < command.length) { cur += c + command[++i]!; continue; }
130
+ if (c === "'" || c === '"') { q = c; cur += c; continue; }
131
+ if (c === "<" && command[i + 1] === "<" && command[i + 2] !== "<") {
132
+ const m = /^<<(-?)[ \t]*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))/.exec(command.slice(i));
133
+ if (m) { heredocs.push({ word: (m[2] ?? m[3] ?? m[4])!, strip: m[1] === "-" }); cur += " "; i += m[0].length - 1; continue; }
134
+ unknown = true; cur += c; continue;
135
+ }
136
+ if (c === "\n") {
137
+ const line = command.slice(lineStart, i);
138
+ push();
139
+ if (heredocs.length) {
140
+ if (CODE_RUNNER.test(line)) unknown = true;
141
+ for (const h of heredocs) {
142
+ let ended = false;
143
+ while (i + 1 < command.length) {
144
+ const end = command.indexOf("\n", i + 1);
145
+ const text = command.slice(i + 1, end < 0 ? command.length : end);
146
+ i = end < 0 ? command.length : end;
147
+ if ((h.strip ? text.replace(/^\t+/, "") : text) === h.word) { ended = true; break; }
148
+ }
149
+ if (!ended) unknown = true;
150
+ }
151
+ heredocs.length = 0;
152
+ }
153
+ lineStart = i + 1;
154
+ continue;
155
+ }
156
+ if (c === ";") { push(); continue; }
157
+ if ((c === "&" || c === "|") && command[i + 1] === c) { push(); i++; continue; }
158
+ if (c === "|") { push(); continue; }
159
+ cur += c;
160
+ }
161
+ if (q) unknown = true;
162
+ if (heredocs.length) { unknown = true; if (CODE_RUNNER.test(command.slice(lineStart))) unknown = true; }
163
+ push();
164
+ return { parts, unknown };
165
+ }
166
+
167
+ /**
168
+ * Pure classifier of in-place shell writes (#1556 T1, observation only). A write is named only when certain;
169
+ * anything it cannot parse is unknown, never a guess. Targets under /tmp or /dev sinks are not worktree writes.
170
+ */
171
+ export function classifyShellWrite(command: string): ShellWriteClass {
172
+ const targets: string[] = [];
173
+ const seg = segment(command);
174
+ let unknown = seg.unknown;
175
+ for (const part of seg.parts) {
176
+ const w = words(part);
177
+ if (!w) { unknown = true; continue; }
178
+ for (let i = 0; i < w.length; i++) {
179
+ const m = /^(\d*)(>>?|&>>?)(.*)$/.exec(w[i]!);
180
+ if (!m || w[i]!.startsWith("'") || w[i]!.startsWith('"')) continue;
181
+ const t = unq(m[3] || w[++i] || "");
182
+ if (!t || SINK.test(t) || /^>?&\d*$/.test(m[3] ?? "") || /^&/.test(t)) continue;
183
+ targets.push(t);
184
+ }
185
+ const args = w.filter((x) => !/^\d*(>>?|&>>?)/.test(x));
186
+ const head = args[0] === "sudo" || args[0] === "env" ? args.slice(1) : args;
187
+ const [c, ...rest] = head;
188
+ const files = rest.filter((x) => !x.startsWith("-")).map(unq);
189
+ if (!c) continue;
190
+ if (c === "sed" && rest.some((x) => /^-[a-zA-Z]*i/.test(x) || x.startsWith("--in-place"))) {
191
+ // -e/-f/--expression make every positional a file; an unusual suffix form is not guessed: unknown, never a wrong target.
192
+ if (rest.some((x) => /^-[a-zA-Z]*[ef]/.test(x) || x.startsWith("--expression") || x.startsWith("--file"))) unknown = true;
193
+ else targets.push(...files.filter((x) => x !== "").slice(1));
194
+ }
195
+ else if (c === "perl" && rest.some((x) => /^-[a-zA-Z]*i/.test(x))) targets.push(...files.slice(1));
196
+ else if (c === "awk" && rest.includes("inplace") && rest.includes("-i")) targets.push(...files.slice(1).filter((x) => x !== "inplace"));
197
+ else if (c === "tee") targets.push(...files);
198
+ else if (c === "dd") { for (const x of rest) if (x.startsWith("of=")) targets.push(unq(x.slice(3))); }
199
+ else if (c === "cp" || c === "mv" || c === "install") { if (files.length) targets.push(files[files.length - 1]!); }
200
+ else if (c === "patch") targets.push(...files);
201
+ else if (c === "git" && rest[0] === "apply" && !rest.includes("--check")) targets.push("(git apply)");
202
+ else if (/^(python3?|node|bun|ruby|perl)$/.test(c) && rest.some((x) => x === "-c" || x === "-e")) {
203
+ if (/write_text|write\(|writeFile|fs\.write|open\([^)]*['"][wa]|File\.write/.test(part)) unknown = true;
204
+ }
205
+ }
206
+ const real = targets.filter((t) => !/^\/(?:tmp|private\/tmp|var\/folders)\//.test(t));
207
+ if (real.length) return { kind: "write", targets: real };
208
+ return { kind: unknown ? "unknown" : "read", targets: [] };
209
+ }
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)";
@@ -245,7 +245,7 @@ export interface TasksDeps {
245
245
  auditSource?: AuditSource;
246
246
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
247
247
  ciWatch?: { deadlineMs?: number; pollMs?: number };
248
- /** #785 P1c: `tasks.auto_pull`, read at each capacity release so a reload applies to the next one; absent or false pulls nothing. */
248
+ /** #785 P1c: `tasks.auto_pull`, read for every automatic pull trigger; absent or false pulls nothing. */
249
249
  autoPull?: () => boolean;
250
250
  briefs?: Briefs;
251
251
  /** Screened live fail notes directly intersecting the task plan or refs; read-only advice. */
@@ -409,6 +409,8 @@ QUIET_EVENTS.add("plan observed"); // Host observation does not move the task or
409
409
  QUIET_EVENTS.add("planner changed"); // Planning authority does not move the execution owner or revoke its handoff.
410
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".
411
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");
412
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".
413
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.
414
416
  /** The records of the `done (checking)` entry a passed check now completes: what the owner delivered then (#509a). */
@@ -860,6 +862,7 @@ export class Tasks {
860
862
  /** #785 P1b: one bounded CI watcher per exact PR head, and the reviews the hub held as premature, by task id. */
861
863
  private readonly ciWatchers: CiWatchers;
862
864
  private readonly heldReviews = new Map<number, { head: string; reviewer: PeerId; revision: number }>();
865
+ private readonly autoPullAttached = new Set<PeerId>();
863
866
 
864
867
  constructor(private readonly d: TasksDeps) {
865
868
  this.ciWatchers = new CiWatchers({
@@ -890,7 +893,15 @@ export class Tasks {
890
893
  });
891
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
892
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
+ };
893
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
+ }
894
905
  if (e.t === "overflow" && e.env.from === HUB && e.env.kind === "task" && Array.isArray(e.env.refs?.backlog)) {
895
906
  const ids = e.env.refs.backlog;
896
907
  if (ids.length <= 64 && ids.every(id => Number.isSafeInteger(id) && id > 0)) this.addPlannerBacklog(e.peer, ids);
@@ -908,6 +919,12 @@ export class Tasks {
908
919
  });
909
920
  }
910
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
+
911
928
  isPii = (task: Pick<Task, "signals">) => task.signals.includes("pii_path") || (task.signals.includes("pii") && this.d.routing().constraints.pii === "local_only");
912
929
 
913
930
  private signalsFor(task: Pick<Task, "title" | "detail" | "refs"> & { plan?: TaskPlan }, routing = this.d.routing()) {
@@ -3073,9 +3090,13 @@ export class Tasks {
3073
3090
  changes.set(planner, change);
3074
3091
  };
3075
3092
  const released = new Set<PeerId>();
3093
+ const readied = new Set<PeerId>();
3076
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); }
3077
3095
  if (approved) for (const card of this.d.board.list("backlog")) {
3078
- if (card.deps?.includes(task.id) && !this.waitsFor(card).length && !plannedStartPending(card, now)) for (const planner of this.taskPlanner(card)) add(planner, undefined, card.id);
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
+ }
3079
3100
  }
3080
3101
  for (const [planner, change] of changes) this.releaseNotice(`could not notify planner ${planner} about ready work`, () => {
3081
3102
  const pending = this.d.bus.pendingEnvelopes(planner).filter(env => env.from === HUB && env.kind === "task" && env.body.startsWith("Planner work ready:"));
@@ -3100,8 +3121,9 @@ export class Tasks {
3100
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" });
3101
3122
  if (!this.d.bus.publish(env).includes(planner)) throw new Error("the notice was not queued");
3102
3123
  });
3103
- // #785 P1c: only this write's own release, never a merged earlier one, and only when the person turned it on.
3124
+ // Only this write's own release or newly ready dependency, never a merged earlier notice.
3104
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");
3105
3127
  });
3106
3128
  }
3107
3129
 
@@ -3114,32 +3136,32 @@ export class Tasks {
3114
3136
  }
3115
3137
 
3116
3138
  /**
3117
- * #785 P1c: `tasks.auto_pull`. A slot freed for a peer pulls the one top backlog card explicitly reserved for it, through `pullPlanned` as the hub acting for that card's planner of
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
3118
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.
3119
- * Serialized on one chain, so two releases cannot pick the same card; each job re-reads the board, so a card that moved meanwhile is skipped.
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.
3120
3142
  */
3121
3143
  private autoPulls: Promise<void> = Promise.resolve();
3122
3144
  private autoPullsOpen = 0;
3123
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. */
3124
3146
  autoPullsPending = (): number => this.autoPullsOpen;
3125
- private queueAutoPulls(released: ReadonlySet<PeerId>): void {
3147
+ private queueAutoPulls(released: ReadonlySet<PeerId>, cause = "capacity released"): void {
3126
3148
  for (const peer of released) {
3127
3149
  this.autoPullsOpen++;
3128
- 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--; });
3129
3151
  }
3130
3152
  }
3131
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. */
3132
3154
  private autoPullAdmitted(): boolean {
3133
3155
  return this.d.autoPull?.() === true && !this.d.sweepHeld?.() && !this.d.bus.isRecoveryHeld && !this.d.bus.storageError;
3134
3156
  }
3135
- private async autoPull(peer: PeerId): Promise<void> {
3157
+ private async autoPull(peer: PeerId, cause: string): Promise<void> {
3136
3158
  if (!this.autoPullAdmitted()) return;
3137
3159
  const card = this.topReservedReady(peer, undefined, true);
3138
3160
  if (!card) return;
3139
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).
3140
3162
  const planner = this.taskPlanner(card)[0];
3141
3163
  if (!planner || !this.d.bus.isRostered(planner)) return;
3142
- const reason = `auto_pull: capacity released for ${peer}; hub acted for planner ${planner}`;
3164
+ const reason = `auto_pull: ${cause} for ${peer}; hub acted for planner ${planner}`;
3143
3165
  try {
3144
3166
  await this.pullPlanned(HUB, { id: card.id, revision: card.planningRevision ?? 0, reason }, { onBehalfOf: planner, guard: () => {
3145
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");
@@ -3804,6 +3826,8 @@ export class Tasks {
3804
3826
  catch (error) { throw new PreEffectToolRefusal((error as Error).message); }
3805
3827
  const updated = this.d.board.plan(task.id, by, patch, input.revision, input.reason.trim(), withheld, receipt);
3806
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");
3807
3831
  return updated; // persistence/readback failures must never claim no effect
3808
3832
  }
3809
3833
 
@@ -6778,7 +6802,7 @@ export class Tasks {
6778
6802
  }
6779
6803
  const rows = this.d.board.list();
6780
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,
6781
- ...(entry.event === "done" && (entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head) ? { requestHead: entry.requestHead ?? entry.reviewCost?.head ?? entry.specReport?.head } : {}), ...(entry.reviewFindings?.head ? { verdictHead: entry.reviewFindings.head } : {}), ...(entry.evidenceOnly ? { evidenceOnly: true as const } : {}) })) }));
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 } : {}) })) }));
6782
6806
  const visibleIds = new Set(rows.filter(task => !this.isPii(task)).map(task => task.id));
6783
6807
  const byKind: Record<string, number> = {};
6784
6808
  for (const stall of this.stalled()) if (visibleIds.has(stall.task)) byKind[stall.cause.kind] = (byKind[stall.cause.kind] ?? 0) + 1;
@@ -6786,14 +6810,22 @@ export class Tasks {
6786
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.
6787
6811
  const mergedAt: Record<number, number> = {}, ciReruns: Record<number, number | null> = {}, ciRuns: Record<number, number | null> = {}, reviews: Record<number, number | null> = {};
6788
6812
  for (const task of rows) {
6789
- const merge = task.sdlc?.merge;
6813
+ const guarded = task.sdlc?.merge;
6814
+ const merge = guarded?.state === "merged" ? guarded : task.sdlc?.mergeReadback;
6790
6815
  if (!visibleIds.has(task.id) || merge?.state !== "merged") continue;
6791
6816
  const cost = cleanMergeCost(merge.cost);
6792
- 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);
6793
6818
  if (at !== null) mergedAt[task.id] = at;
6794
6819
  if (cost) { ciReruns[task.id] = cost.ciReruns; ciRuns[task.id] = cost.ciRuns; reviews[task.id] = cost.reviews; }
6795
6820
  }
6796
- 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(","));
6797
6829
  }
6798
6830
 
6799
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. */
@@ -7751,12 +7783,19 @@ export class Tasks {
7751
7783
  return result;
7752
7784
  };
7753
7785
  const evidence = await readAdoptMergeEvidence(receipt, run);
7754
- const now = current();
7786
+ current();
7755
7787
  const gates = adoptMergeGates(evidence, head, requiredChecksFor(config, repo));
7756
7788
  if (gates.length) throw new PreEffectToolRefusal(gates.join("; "));
7757
- const capacity = this.capacityBefore(now);
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);
7758
7797
  current(); // No await between the last authority/privacy/flow check and the sole approval write.
7759
- const next = this.d.board.adoptMerge(now.id, by, receipt, head, now.history.length, HOST_MERGE_ADOPTION);
7798
+ const next = this.d.board.adoptMerge(latest.id, by, { ...receipt, mergeReadback: merge }, head, latest.history.length, HOST_MERGE_ADOPTION);
7760
7799
  this.cohorts.closed(next.id);
7761
7800
  this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id);
7762
7801
  this.writePlannerNotices(next, capacity, true);
@@ -7838,6 +7877,61 @@ export class Tasks {
7838
7877
  if(!current.history.some(h=>h.by===HUB && h.event==="merge refused" && h.note===note))
7839
7878
  this.d.board.update(id,HUB,"merge refused",{},note,{...(this.isPii(current)||this.d.privateTurn?.(by)?{withheld:true}:{})});
7840
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
+
7841
7935
  private mergeRecordCurrent(id:number,by:PeerId,record:MergeRecord,artifactCurrent:()=>boolean):Task|undefined {
7842
7936
  const now=this.d.board.get(id);
7843
7937
  return artifactCurrent() && now && now.sdlc?.repo===record.repo && now.sdlc.pr===record.pr && now.sdlc.reviewedHead===record.head
@@ -8325,7 +8419,7 @@ export class Tasks {
8325
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)}`);
8326
8420
  const task = this.d.board.get(n);
8327
8421
  if (!task) throw new (preEffect ? PreEffectToolRefusal : Error)(`no task #${n}`);
8328
- 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)`);
8329
8423
  // Handing a task to someone else only makes sense while there is work left on it.
8330
8424
  if (open && !OPEN.includes(task.state)) throw new (preEffect ? PreEffectToolRefusal : Error)(`task #${task.id} is ${task.state}: it can no longer change hands`);
8331
8425
  return task;
@@ -8805,6 +8899,7 @@ export class Tasks {
8805
8899
  if (sdlc.reviewedHead !== refresh.commit) delete sdlc.reviewedHead;
8806
8900
  if (sdlc.localHead !== refresh.commit) { delete sdlc.localHead; delete sdlc.localResult; }
8807
8901
  delete sdlc.merge;
8902
+ delete sdlc.mergeReadback;
8808
8903
  return { ...task, sdlc };
8809
8904
  }
8810
8905
 
@@ -9047,6 +9142,15 @@ export class Tasks {
9047
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");
9048
9143
  }
9049
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
+
9050
9154
  /**
9051
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
9052
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);
@@ -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 merge = task?.sdlc?.merge;
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;
@@ -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, TMPDIR: `${own}/` };
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
+ }
@@ -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 result = await buildIntentBrief(context.source, context.options);
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?.();