@staix/agent-hub 0.44.0 → 0.46.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 (168) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +12 -11
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +35 -6
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/local-worker.md +1 -1
  8. package/docs/agent-notes/security-review.md +3 -2
  9. package/docs/agent-notes/tasks.md +6 -2
  10. package/docs/agent-notes/tests.md +4 -3
  11. package/docs/design/adapters.md +20 -2
  12. package/docs/design/agent-hub-architecture.md +12 -0
  13. package/docs/design/agent-hub.md +1 -1
  14. package/docs/design/cli-output.md +2 -0
  15. package/docs/design/roadmap.md +158 -4
  16. package/docs/design/supervision.md +21 -1
  17. package/docs/design/task-board.md +32 -4
  18. package/docs/dogfood.md +28 -4
  19. package/docs/events.md +7 -3
  20. package/docs/influences.md +7 -0
  21. package/docs/memory.md +4 -4
  22. package/docs/operations.md +151 -36
  23. package/docs/quickstart.md +16 -4
  24. package/docs/research.md +16 -0
  25. package/docs/roadmap.json +4 -0
  26. package/docs/roadmap.md +9 -0
  27. package/docs/sdlc.md +15 -3
  28. package/docs/security.md +9 -7
  29. package/docs/smoke.md +1 -1
  30. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  31. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  32. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  33. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  34. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  35. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  36. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  37. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  38. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  39. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  40. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  41. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  42. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  43. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  44. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  45. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  46. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  47. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  48. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  49. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  50. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  51. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  52. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  53. package/docs/verified.json +33 -27
  54. package/package.json +3 -2
  55. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  56. package/plugins/agent-hub/kimi-hook.js +4743 -4048
  57. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  58. package/plugins/agent-hub/server.js +1641 -1265
  59. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  60. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  61. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  62. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  63. package/scripts/check-docs.mjs +9 -1
  64. package/src/adapters/acp.ts +11 -1
  65. package/src/adapters/claude-channel.ts +2 -1
  66. package/src/adapters/compat.ts +15 -14
  67. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  68. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  69. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  70. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  71. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  72. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  73. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  74. package/src/adapters/definitions/native-context.ts +10 -0
  75. package/src/adapters/jcode.ts +10 -0
  76. package/src/adapters/local-worker.ts +3 -2
  77. package/src/adapters/pi.ts +15 -4
  78. package/src/cli/claude-profile-hook.ts +40 -3
  79. package/src/cli/console-state.ts +58 -27
  80. package/src/cli/console-usage.ts +5 -3
  81. package/src/cli/console.ts +35 -4
  82. package/src/cli/help.ts +17 -10
  83. package/src/cli/identity.ts +4 -2
  84. package/src/cli/instruction-hook.ts +28 -0
  85. package/src/cli/jcode-mcp.ts +2 -1
  86. package/src/cli/main.js +8 -0
  87. package/src/cli/main.ts +149 -23
  88. package/src/cli/output-standard.ts +3 -55
  89. package/src/cli/output.ts +8 -2
  90. package/src/cli/recovery-package.ts +62 -13
  91. package/src/cli/roadmap-write.ts +59 -0
  92. package/src/cli/roadmap.ts +115 -4
  93. package/src/cli/sdlc-output.ts +4 -0
  94. package/src/cli/setup-homes.ts +1 -0
  95. package/src/cli/setup.ts +1 -1
  96. package/src/cli/skills-install.ts +463 -0
  97. package/src/cli/task-output.ts +1 -1
  98. package/src/cli/upgrade-presentation-flags.ts +1 -1
  99. package/src/cli/upgrade-runtime.ts +10 -6
  100. package/src/hub/agent-mem-range.ts +43 -0
  101. package/src/hub/board.ts +144 -5
  102. package/src/hub/budget-projection.ts +99 -0
  103. package/src/hub/check-runner.ts +25 -1
  104. package/src/hub/claude-launch-proof.ts +5 -1
  105. package/src/hub/conductor.ts +8 -3
  106. package/src/hub/config-apply.ts +6 -3
  107. package/src/hub/config-tier.ts +1 -1
  108. package/src/hub/config-trust.ts +1 -1
  109. package/src/hub/context-window.ts +1 -1
  110. package/src/hub/control-client.ts +9 -2
  111. package/src/hub/cost-governance.ts +11 -7
  112. package/src/hub/daemon.ts +707 -53
  113. package/src/hub/dogfood-read.ts +4 -2
  114. package/src/hub/edit-guard.ts +100 -0
  115. package/src/hub/events.ts +80 -9
  116. package/src/hub/execution-budget.ts +29 -8
  117. package/src/hub/facts.ts +57 -4
  118. package/src/hub/hub-tools.ts +3 -1
  119. package/src/hub/inference.ts +1 -1
  120. package/src/hub/instances.ts +10 -1
  121. package/src/hub/instructed-exact.ts +95 -0
  122. package/src/hub/instructed-intent.ts +64 -0
  123. package/src/hub/instructed-ipc.ts +33 -0
  124. package/src/hub/instructed-runtime.ts +19 -0
  125. package/src/hub/instruction-receipt.ts +218 -0
  126. package/src/hub/lifecycle.ts +6 -1
  127. package/src/hub/log-rotation.ts +130 -0
  128. package/src/hub/manager.ts +46 -3
  129. package/src/hub/memory-profile.ts +137 -21
  130. package/src/hub/no-writes.ts +1 -0
  131. package/src/hub/operational-authority.ts +3 -2
  132. package/src/hub/operational-settings.ts +2 -2
  133. package/src/hub/recovery-store.ts +49 -21
  134. package/src/hub/registry.ts +1 -1
  135. package/src/hub/research-experiments.ts +132 -0
  136. package/src/hub/research-quality.ts +8 -2
  137. package/src/hub/research-record.ts +35 -0
  138. package/src/hub/research.ts +128 -28
  139. package/src/hub/roadmap-check.ts +65 -0
  140. package/src/hub/roadmap-decompose.ts +139 -0
  141. package/src/hub/roadmap-export.ts +27 -0
  142. package/src/hub/roadmap-sync.ts +97 -0
  143. package/src/hub/roadmap.ts +59 -1
  144. package/src/hub/routing.ts +18 -1
  145. package/src/hub/runtime-capture-prune.ts +2 -1
  146. package/src/hub/sdlc-branch-ci.ts +128 -0
  147. package/src/hub/sdlc-merge.ts +6 -3
  148. package/src/hub/sdlc-metrics.ts +19 -5
  149. package/src/hub/sdlc.ts +73 -5
  150. package/src/hub/settings.ts +3 -1
  151. package/src/hub/snapshots.ts +13 -1
  152. package/src/hub/startup-event-seeds.ts +21 -15
  153. package/src/hub/startup-timing.ts +3 -1
  154. package/src/hub/supervision-proposals.ts +10 -2
  155. package/src/hub/supervision-rules.ts +26 -3
  156. package/src/hub/supervision.ts +7 -0
  157. package/src/hub/task-pr.ts +47 -0
  158. package/src/hub/task-worktree.ts +18 -11
  159. package/src/hub/tasks.ts +694 -44
  160. package/src/hub/ui.ts +6 -2
  161. package/src/hub/usage-rollup.ts +77 -22
  162. package/src/local/tools.ts +13 -1
  163. package/src/memory/client.ts +3 -2
  164. package/src/pi/extension.ts +15 -3
  165. package/src/pi/tool-receipts.ts +26 -0
  166. package/src/ui/index.html +342 -8
  167. package/src/ui/plugin.ts +6 -2
  168. package/src/ui/roadmap-model.ts +70 -0
package/src/hub/board.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { instructedExecution, instructedHistory } from "./instructed-exact.ts";
1
2
  import { PreEffectToolRefusal } from "./tool-refusal.ts";
2
3
  import { GUIDANCE_VARIANT_LIMITS, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_HASH_HEX_LENGTH, parseGuidanceVariantV1, parseGuidanceExperiment, parseGuidanceStoredRecord, validateGuidanceVariantV1, type GuidanceVariantV1, type GuidanceExperimentRecord, type GuidanceStoredRecord, type GuidanceWriteFence } from "./guidance-variants.ts";
3
4
  import { ExecutionLinkError, EXECUTION_LINK_LIMITS, executionLinkActor, executionLinkInteger, executionLinkId, executionLinkReferences, executionReferenceDigest, parseExecutionLinkInput, parseExecutionLinkRecord, type ExecutionLinkInput, type ExecutionLinkRecord, type ExecutionLinkFence } from "./execution-links.ts";
@@ -20,7 +21,7 @@ import type { Database } from "./db-schema.ts";
20
21
  import { openHubDatabase, advanceHubDbSchema } from "./db-schema.ts";
21
22
  import { controlWriteSpan } from "./control-write-trace.ts";
22
23
  import { planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
23
- import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState } from "./roadmap.ts";
24
+ import { MILESTONE_HISTORY_LIMIT, parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneActor, milestoneHistory, milestoneLinkRef, githubRepo, type Milestone, type MilestoneInput, type MilestonePatch, type MilestoneLink, type MilestoneLinkKind, type MilestoneHistoryEntry, type MilestoneSuggestion, type SuggestionItemKind, type SuggestionState, type DecomposePart, type DecomposeIntake, type DecompositionState, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
24
25
  import { HUB, USER, type PeerId } from "./envelope.ts";
25
26
  import type { AuditFinding, AuditProfile, AuditUnit } from "./security-audit.ts";
26
27
  import type { ReviewFinding } from "./review-findings.ts";
@@ -72,6 +73,11 @@ const GUIDANCE_VARIANT_SELECT = `SELECT CASE WHEN typeof(id)='text' AND length(C
72
73
  export const HOST_MERGE_ADOPTION = Symbol("host merge adoption");
73
74
  /** Internal publication capability, independent of the person-only acceptance API. */
74
75
  export const HOST_SPEC_ACCEPTANCE_CARRY = Symbol("host spec acceptance carry");
76
+ /**
77
+ * Internal capability for R2 part 2 (#1480): the draft `roadmapDecomposePart` stages for an accepted part is held exactly like the
78
+ * person's intake draft. A Symbol cannot arrive in a tool argument, so no caller can stage a hidden draft through it.
79
+ */
80
+ export const HOST_ROADMAP_DRAFT = Symbol("host roadmap acceptance draft");
75
81
  export interface SpecAcceptanceCommit { source: number; cancellationRevision: number; acceptance: SpecAcceptance; }
76
82
 
77
83
  export interface ResearchCampaignRecord {
@@ -257,6 +263,9 @@ export type TaskMoveReason = (typeof TASK_MOVE_REASONS)[number];
257
263
  export type InvocationHistory = Pick<InvocationRow, "id" | "caller" | "target" | "capability" | "digest" | "class" | "approval" | "argsSha256" | "outcome">;
258
264
 
259
265
  export interface HistoryEntry {
266
+ instructed?: true;
267
+ instructedPeer?: string;
268
+ instructionReceipt?: string;
260
269
  /** Host-owned invocation metadata only, never arguments or results. */
261
270
  invocation?: InvocationHistory;
262
271
  at: number;
@@ -593,6 +602,7 @@ export class Board {
593
602
  this.db.run("CREATE INDEX IF NOT EXISTS tasks_human_reviews ON tasks(id) WHERE state='in_review' AND reviewer='user'");
594
603
  // #481 S7: one row per log-tier band breach episode already announced, so a restart never repeats the notice.
595
604
  this.db.run("CREATE TABLE IF NOT EXISTS band_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)");
605
+ this.db.run("CREATE TABLE IF NOT EXISTS roadmap_notices (marker TEXT PRIMARY KEY, at INTEGER NOT NULL)");
596
606
  // #481 S7: one row per scheduled security scan. Counts only (no alert text); `total` is null when a named source could not be read completely.
597
607
  this.db.run("CREATE TABLE IF NOT EXISTS security_scans (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, repo TEXT NOT NULL, sources TEXT NOT NULL, counts TEXT NOT NULL, total INTEGER)");
598
608
  // #843 AC3: one row per (agent id, installed version, planner) already queued, so a restart never repeats it.
@@ -647,6 +657,22 @@ export class Board {
647
657
  this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_suggestions_pending ON milestone_suggestions(kind,ref) WHERE state='pending'");
648
658
  this.db.run(`CREATE TABLE IF NOT EXISTS milestone_imports (
649
659
  repo TEXT NOT NULL, number INTEGER NOT NULL, milestone INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(repo,number))`);
660
+ // R2 (#1480): model-written decompositions, additive and outside the roadmap integrity digest like a suggestion: a lost
661
+ // answer is asked for again, and one pending answer per milestone is the newest run.
662
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decompositions (
663
+ id INTEGER PRIMARY KEY AUTOINCREMENT, milestone INTEGER NOT NULL, parts TEXT NOT NULL,
664
+ state TEXT NOT NULL, by TEXT NOT NULL, created INTEGER NOT NULL, settled INTEGER, settled_by TEXT)`);
665
+ this.db.run("CREATE UNIQUE INDEX IF NOT EXISTS milestone_decompositions_pending ON milestone_decompositions(milestone) WHERE state='pending'");
666
+ // R2 part 2 (#1480): which parts of a pending answer are already held as intake drafts. Keyed by the answer and the part's
667
+ // 1-based position, so accepting the same part twice finds this row instead of making a second draft.
668
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decomposition_accepts (
669
+ decomposition INTEGER NOT NULL, milestone INTEGER NOT NULL, part INTEGER NOT NULL, task INTEGER NOT NULL,
670
+ intake TEXT NOT NULL, by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(decomposition,part))`);
671
+ // R2 part 3 (#1480): the one issue a published part created, additive like the accept row. A lost row publishes the part
672
+ // again; the issue's own marker names the draft it came from.
673
+ this.db.run(`CREATE TABLE IF NOT EXISTS milestone_decomposition_publishes (
674
+ decomposition INTEGER NOT NULL, milestone INTEGER NOT NULL, part INTEGER NOT NULL, issue INTEGER NOT NULL,
675
+ by TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY(decomposition,part))`);
650
676
 
651
677
  this.db.run(`CREATE TABLE IF NOT EXISTS research_campaigns (
652
678
  id TEXT NOT NULL, project TEXT NOT NULL, parent_task_id INTEGER NOT NULL, revision INTEGER NOT NULL,
@@ -2438,7 +2464,7 @@ export class Board {
2438
2464
  }
2439
2465
  const now = Date.now(), planner = plannerValue(t.planner);
2440
2466
  const chosen = Object.hasOwn(t, "planner") || t.plannerReason !== undefined ? plannerMetadata(planner, t.plannerReason) : {};
2441
- const history: HistoryEntry[] = [{ at: now, by, ...chosen, event: t.backlog ? "backlogged" : "proposed", ...(this.trackPlanRevisions?.() && t.plan && Object.keys(t.plan).length ? { planRevision: { revision: 1, fingerprint: planFingerprint(t.plan) } } : {}) }];
2467
+ const history: HistoryEntry[] = [{ at: now, by, ...instructedHistory(by), ...chosen, event: t.backlog ? "backlogged" : "proposed", ...(this.trackPlanRevisions?.() && t.plan && Object.keys(t.plan).length ? { planRevision: { revision: 1, fingerprint: planFingerprint(t.plan) } } : {}) }];
2442
2468
  const { lastInsertRowid } = this.taskWrite(() => {
2443
2469
  const inserted = this.db
2444
2470
  .query("INSERT INTO tasks (title, detail, class, state, refs, plan, deps, reserved, signals, history, created, updated, project_profile, task_role, external_repo, external_issue, planner, draft) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
@@ -2612,6 +2638,15 @@ export class Board {
2612
2638
  if (!/^[a-z_]{1,64}:#[1-9][0-9]{0,9}:log$/.test(marker)) throw new Error("invalid band notice marker");
2613
2639
  return this.db.query("INSERT OR IGNORE INTO band_notices(marker, at) VALUES(?, ?)").run(marker, Date.now()).changes > 0;
2614
2640
  }
2641
+
2642
+ hasRoadmapNotice(marker: string): boolean {
2643
+ if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker");
2644
+ return !!this.db.query("SELECT 1 FROM roadmap_notices WHERE marker=?").get(marker);
2645
+ }
2646
+ recordRoadmapNotice(marker: string): boolean {
2647
+ if (!/^[a-f0-9]{64}$/.test(marker)) throw new Error("invalid roadmap notice marker");
2648
+ return this.db.query("INSERT OR IGNORE INTO roadmap_notices(marker,at) VALUES(?,?)").run(marker, Date.now()).changes > 0;
2649
+ }
2615
2650
  /** True when the (id, version, planner) marker was new and is now recorded; false when it was announced before. */
2616
2651
  recordAgentDriftNotice(marker: string): boolean {
2617
2652
  if (!/^[a-z][a-z0-9-]{0,31}:[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}@[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(marker)) throw new Error("invalid agent drift marker");
@@ -2701,6 +2736,8 @@ export class Board {
2701
2736
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
2702
2737
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
2703
2738
  update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "requestHead" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2739
+ const instruction = instructedExecution.getStore();
2740
+ if (instruction?.active && instruction.taskId === id) instruction.current();
2704
2741
  if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
2705
2742
  const task = this.get(id);
2706
2743
  if (!task) throw new Error(`no task #${id}`);
@@ -2798,7 +2835,7 @@ export class Board {
2798
2835
  && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
2799
2836
  const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
2800
2837
  ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
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 } : {}) }];
2838
+ const history = [...previousHistory, { at: Date.now(), by, event, ...instructedHistory(by), ...(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 } : {}) }];
2802
2839
  this.taskWrite(() => {
2803
2840
  if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
2804
2841
  if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
@@ -2828,7 +2865,7 @@ export class Board {
2828
2865
  if (next.plannedStart != null && next.due != null && next.plannedStart > next.due) throw new Error("planned start must not follow due");
2829
2866
  if (next.release != null && !this.release(next.release)) throw new Error("no such release");
2830
2867
  const fields = Object.keys(patch) as (keyof PlanningFields)[], previous = Object.fromEntries(fields.map(key => [key, key === "sdlc" ? { repo: task.sdlc?.repo ?? null, issue: task.sdlc?.issue ?? null } : task[key] ?? (key === "pinned" || key === "needsPerson" ? false : key === "deps" ? [] : null)])) as PlanningFields;
2831
- const now = Date.now(), entry: HistoryEntry = { at: now, by, event: "planned", planning: { revision: revision + 1, fields, previous }, ...(note ? { note } : {}), ...(withheld && note ? { withheld: true as const } : {}) };
2868
+ const now = Date.now(), entry: HistoryEntry = { at: now, by, ...instructedHistory(by), event: "planned", planning: { revision: revision + 1, fields, previous }, ...(note ? { note } : {}), ...(withheld && note ? { withheld: true as const } : {}) };
2832
2869
  const result = this.taskWrite(() => this.db.query(`UPDATE tasks SET rank=?, priority=?, "release"=?, planned_start=?, due=?, pinned=?, needs_person=?, deps=?, reserved=?, planning_revision=planning_revision+1, history=?, updated=?, sdlc=? WHERE id=? AND planning_revision=?`)
2833
2870
  .run(next.rank ?? null, next.priority ?? null, next.release ?? null, next.plannedStart ?? null, next.due ?? null, next.pinned ? 1 : 0, next.needsPerson ? 1 : 0, JSON.stringify(next.deps ?? []), next.reserved ?? null, JSON.stringify([...task.history, entry]), now, next.sdlc === undefined ? null : JSON.stringify(next.sdlc), id, revision));
2834
2871
  if (result.changes !== 1) throw new Error("planning revision changed");
@@ -2841,7 +2878,7 @@ export class Board {
2841
2878
  if (!task || (task.planningRevision ?? 0) !== revision || task.state !== "backlog" || task.owner || !taskCanPlan(task)) throw new Error("planner pull changed or already started");
2842
2879
  if (task.draft) throw new Error(`task #${id} is an intake draft; the person approves it first`);
2843
2880
  const selected = binding ? plannerMetadata(binding.planner, binding.plannerReason) : {};
2844
- const now = Date.now(), entry: HistoryEntry = { at: now, by, ...selected, event: "backlog pulled", planning: { revision: revision + 1, fields: ["reserved"], previous: { reserved: task.reserved ?? null }, pull: true }, note, ...(withheld ? { withheld: true as const } : {}) };
2881
+ const now = Date.now(), entry: HistoryEntry = { at: now, by, ...instructedHistory(by), ...selected, event: "backlog pulled", planning: { revision: revision + 1, fields: ["reserved"], previous: { reserved: task.reserved ?? null }, pull: true }, note, ...(withheld ? { withheld: true as const } : {}) };
2845
2882
  const result = this.taskWrite(() => this.db.query("UPDATE tasks SET state='proposed',owner=NULL,reviewer=NULL,offer=NULL,reserved=?,planning_revision=planning_revision+1,history=?,updated=?,planner=? WHERE id=? AND planning_revision=? AND state='backlog' AND owner IS NULL")
2846
2883
  .run(reserved, JSON.stringify([...task.history, entry]), now, binding ? selected.planner ?? null : task.planner ?? null, id, revision));
2847
2884
  if (result.changes !== 1) throw new Error("planner pull changed");
@@ -2972,6 +3009,12 @@ export class Board {
2972
3009
  ref: milestoneLinkRef(row.kind as MilestoneLinkKind, row.ref), by: milestoneActor(row.by), at: milestoneId(row.at) }));
2973
3010
  }
2974
3011
 
3012
+ /** #1622 family 4: whether any milestone history holds an instructed entry; a daemon without `roadmap_instructed` cannot read such a row. */
3013
+ hasInstructedMilestoneHistory(): boolean {
3014
+ const row = this.db.query("SELECT EXISTS(SELECT 1 FROM milestones WHERE history LIKE '%\"instructed\"%') AS present").get() as { present: number };
3015
+ return row.present === 1;
3016
+ }
3017
+
2975
3018
  hasMilestoneState(): boolean {
2976
3019
  const row = this.db.query("SELECT EXISTS(SELECT 1 FROM milestones) OR EXISTS(SELECT 1 FROM milestone_links) AS present").get() as { present: number };
2977
3020
  return row.present === 1;
@@ -3046,6 +3089,72 @@ export class Board {
3046
3089
  this.db.query("UPDATE milestone_suggestions SET created_milestone=? WHERE id=? AND state='pending' AND created_milestone IS NULL").run(milestoneId(milestone), milestoneId(id));
3047
3090
  }
3048
3091
 
3092
+ /** R2: one pending decomposition per milestone. A newer answer supersedes the older one in the same transaction, never doubles it. */
3093
+ addDecomposition(row: { milestone: number; parts: DecomposePart[] }, by: string, now = Date.now()): MilestoneDecomposition {
3094
+ const actor = milestoneActor(by), at = milestoneId(now), milestone = milestoneId(row.milestone);
3095
+ return this.db.transaction(() => {
3096
+ this.db.query("UPDATE milestone_decompositions SET state='superseded', settled=?, settled_by=? WHERE milestone=? AND state='pending'").run(at, actor, milestone);
3097
+ const inserted = this.db.query("INSERT INTO milestone_decompositions(milestone,parts,state,by,created) VALUES(?,?,'pending',?,?)").run(milestone, JSON.stringify(row.parts), actor, at);
3098
+ // Settled rows are history, not storage: keep the newest 200.
3099
+ this.db.query("DELETE FROM milestone_decompositions WHERE state<>'pending' AND id NOT IN (SELECT id FROM milestone_decompositions WHERE state<>'pending' ORDER BY id DESC LIMIT 200)").run();
3100
+ return this.decomposition(Number(inserted.lastInsertRowid))!;
3101
+ })();
3102
+ }
3103
+
3104
+ decomposition(id: number): MilestoneDecomposition | undefined {
3105
+ milestoneId(id);
3106
+ const row = this.db.query("SELECT * FROM milestone_decompositions WHERE id=?").get(id) as Record<string, unknown> | null;
3107
+ return row ? parseDecomposition(row) : undefined;
3108
+ }
3109
+
3110
+ decompositions(state?: DecompositionState): MilestoneDecomposition[] {
3111
+ const rows = (state === undefined ? this.db.query("SELECT * FROM milestone_decompositions ORDER BY id").all() : this.db.query("SELECT * FROM milestone_decompositions WHERE state=? ORDER BY id").all(state)) as Record<string, unknown>[];
3112
+ return rows.map(parseDecomposition);
3113
+ }
3114
+
3115
+ /** R2 part 2: the answer an accept reads its parts from. A superseded one is not pending, so an accept cannot land on it. */
3116
+ pendingDecomposition(milestone: number): MilestoneDecomposition | undefined {
3117
+ const row = this.db.query("SELECT * FROM milestone_decompositions WHERE milestone=? AND state='pending'").get(milestoneId(milestone)) as Record<string, unknown> | null;
3118
+ return row ? parseDecomposition(row) : undefined;
3119
+ }
3120
+
3121
+ /** R2 part 2: the draft one part already made, if it was accepted before. */
3122
+ decompositionAccept(decomposition: number, part: number): DecompositionAccept | undefined {
3123
+ const row = this.db.query("SELECT * FROM milestone_decomposition_accepts WHERE decomposition=? AND part=?").get(milestoneId(decomposition), milestoneId(part)) as Record<string, unknown> | null;
3124
+ return row ? parseDecompositionAccept(row) : undefined;
3125
+ }
3126
+
3127
+ /**
3128
+ * R2 part 2: record that a part is held as a draft. The insert is ignored on a repeated accept, so the row that already names
3129
+ * the first draft is the one a retry reads, and no second draft is ever keyed here.
3130
+ */
3131
+ acceptDecompositionPart(row: { decomposition: number; milestone: number; part: number; task: number; intake: DecomposeIntake }, by: string, now = Date.now()): DecompositionAccept {
3132
+ const actor = milestoneActor(by), at = milestoneId(now);
3133
+ this.db.query("INSERT OR IGNORE INTO milestone_decomposition_accepts(decomposition,milestone,part,task,intake,by,at) VALUES(?,?,?,?,?,?,?)")
3134
+ .run(milestoneId(row.decomposition), milestoneId(row.milestone), milestoneId(row.part), milestoneId(row.task), row.intake, actor, at);
3135
+ return this.decompositionAccept(row.decomposition, row.part)!;
3136
+ }
3137
+
3138
+ /** R2 part 3: every part held for one milestone, oldest answer and lowest position first, whatever answer it came from. */
3139
+ decompositionAcceptsFor(milestone: number): DecompositionAccept[] {
3140
+ const rows = this.db.query("SELECT * FROM milestone_decomposition_accepts WHERE milestone=? ORDER BY decomposition, part").all(milestoneId(milestone)) as Record<string, unknown>[];
3141
+ return rows.map(parseDecompositionAccept);
3142
+ }
3143
+
3144
+ /** R2 part 3: the issue a published part created, if an earlier apply made one. */
3145
+ decompositionPublish(decomposition: number, part: number): number | undefined {
3146
+ const row = this.db.query("SELECT issue FROM milestone_decomposition_publishes WHERE decomposition=? AND part=?").get(milestoneId(decomposition), milestoneId(part)) as Record<string, unknown> | null;
3147
+ return row ? milestoneId(row.issue) : undefined;
3148
+ }
3149
+
3150
+ /** R2 part 3: record the issue one apply created. A repeated apply of the same part keeps the first row. */
3151
+ recordDecompositionPublish(row: { decomposition: number; milestone: number; part: number; issue: number }, by: string, now = Date.now()): number {
3152
+ const actor = milestoneActor(by), at = milestoneId(now);
3153
+ this.db.query("INSERT OR IGNORE INTO milestone_decomposition_publishes(decomposition,milestone,part,issue,by,at) VALUES(?,?,?,?,?,?)")
3154
+ .run(milestoneId(row.decomposition), milestoneId(row.milestone), milestoneId(row.part), milestoneId(row.issue), actor, at);
3155
+ return this.decompositionPublish(row.decomposition, row.part)!;
3156
+ }
3157
+
3049
3158
  /** Compare-and-set from pending: a second settle of the same suggestion changes nothing. */
3050
3159
  settleSuggestion(id: number, state: "accepted" | "rejected" | "superseded", by: string, now = Date.now()): MilestoneSuggestion {
3051
3160
  const actor = milestoneActor(by), at = milestoneId(now);
@@ -3063,6 +3172,24 @@ export class Board {
3063
3172
  return row?.milestone;
3064
3173
  }
3065
3174
 
3175
+ /** R4 uses the same durable marks as R3 imports; conflicting legacy marks are never guessed. */
3176
+ mirrorMilestone(repo: string, id: number): number | undefined {
3177
+ const rows = this.db.query("SELECT number FROM milestone_imports WHERE repo=? AND milestone=? ORDER BY number LIMIT 2").all(githubRepo(repo), milestoneId(id)) as { number: number }[];
3178
+ if (rows.length > 1) throw new PreEffectToolRefusal("roadmap milestone has conflicting GitHub bindings; inspect imports before syncing");
3179
+ return rows[0]?.number;
3180
+ }
3181
+
3182
+ bindMirrorMilestone(repo: string, id: number, number: number, now = Date.now()): void {
3183
+ const key = githubRepo(repo), local = milestoneId(id), remote = milestoneId(number), at = milestoneId(now);
3184
+ this.db.transaction(() => {
3185
+ if (!this.milestone(local)) throw new PreEffectToolRefusal("roadmap milestone no longer exists; inspect ahub roadmap list");
3186
+ const prior = this.mirrorMilestone(key, local), owner = this.importedMilestone(key, remote);
3187
+ if (prior !== undefined && prior !== remote || owner !== undefined && owner !== local) throw new PreEffectToolRefusal("roadmap GitHub binding conflicts with an existing milestone; inspect imports before syncing");
3188
+ if (prior === remote && owner === local) return;
3189
+ this.db.query("INSERT INTO milestone_imports(repo,number,milestone,at) VALUES(?,?,?,?)").run(key, remote, local, at);
3190
+ })();
3191
+ }
3192
+
3066
3193
  /** One transaction: the milestone and its import mark exist together or not at all, so a repeat finds the mark. */
3067
3194
  importMilestone(repo: string, number: number, input: MilestoneInput, by: string, now = Date.now()): { milestone: Milestone; created: boolean } {
3068
3195
  const key = repo.toLowerCase();
@@ -3095,6 +3222,7 @@ export class Board {
3095
3222
  const current = this.currentMilestone(id, revision), next = { ...current, ...patch };
3096
3223
  this.milestoneParent(id, next.parent);
3097
3224
  const settling = current.state !== next.state && (next.state === "done" || next.state === "dropped");
3225
+ if (event.instructed && !(settling && event.event === "state")) throw new PreEffectToolRefusal("instructed provenance is recorded only on a done or dropped verdict; ask the person to run ahub roadmap state");
3098
3226
  if (current.history.length >= MILESTONE_HISTORY_LIMIT - 1 && !settling)
3099
3227
  throw new PreEffectToolRefusal(`roadmap history reserves its last slot for settlement; ask the person to run ahub roadmap state ${id} done or ahub roadmap state ${id} dropped`);
3100
3228
  const history = milestoneHistory([...current.history, event]);
@@ -3246,6 +3374,17 @@ function parseSuggestion(row: Record<string, unknown>): MilestoneSuggestion {
3246
3374
  settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
3247
3375
  }
3248
3376
 
3377
+ function parseDecomposition(row: Record<string, unknown>): MilestoneDecomposition {
3378
+ return { id: milestoneId(row.id), milestone: milestoneId(row.milestone), parts: JSON.parse(String(row.parts)) as DecomposePart[],
3379
+ state: row.state as DecompositionState, by: milestoneActor(row.by), created: milestoneId(row.created),
3380
+ settled: row.settled == null ? null : milestoneId(row.settled), settledBy: row.settled_by == null ? null : milestoneActor(row.settled_by) };
3381
+ }
3382
+
3383
+ function parseDecompositionAccept(row: Record<string, unknown>): DecompositionAccept {
3384
+ return { decomposition: milestoneId(row.decomposition), milestone: milestoneId(row.milestone), part: milestoneId(row.part), task: milestoneId(row.task),
3385
+ intake: row.intake as DecomposeIntake, by: milestoneActor(row.by), at: milestoneId(row.at) };
3386
+ }
3387
+
3249
3388
  function parseRelease(row: Record<string, unknown>): Release {
3250
3389
  return { ...(row.train == null ? {} : { train: JSON.parse(String(row.train)) }), planner: row.planner == null ? null : String(row.planner), id: Number(row.id), name: String(row.name), goal: String(row.goal), order: Number(row.release_order), state: row.state as ReleaseState,
3251
3390
  plannedStart: row.planned_start as number | null, cut: row.cut as number | null, ship: row.ship as number | null,
@@ -0,0 +1,99 @@
1
+ // #1513 AC1: when a quota window reaches its limit, at the burn rate seen over a lookback. Pure: the clock, the
2
+ // roll-up and the window all arrive as arguments, so a fixture needs no daemon and no database.
3
+
4
+ /**
5
+ * One hour of burn inside the window. `at` is epoch ms of the bucket's **start**, so a bucket holds everything burned
6
+ * from `at` until the next one and the last bucket is a partial hour; `tokens` is that bucket's whole burn. The rate is
7
+ * therefore measured to `now`, never to the last `at`.
8
+ */
9
+ export interface ProjectionPoint {
10
+ at: number;
11
+ tokens: number;
12
+ }
13
+
14
+ /**
15
+ * `projected`: the window reaches its limit at `at`. `basis` says which span the rate was measured over — the whole
16
+ * lookback, or the window itself when it opened inside the lookback (a reset) and only that much history exists.
17
+ * `unknown`: no time is claimed, and `cause` says why. It is never rendered as a date.
18
+ */
19
+ export type ExhaustionProjection =
20
+ | { state: "projected"; at: number; basis: "lookback" | "window" }
21
+ | { state: "unknown"; cause: "few_points" | "no_burn" | "reset_first" | "unknown_usage" };
22
+
23
+ export interface ProjectionInput {
24
+ /** The window's used fraction, 0..1. */
25
+ used: number | null;
26
+ /** When the current window opened, epoch ms. */
27
+ windowStart: number | null;
28
+ /** When it resets, epoch ms; a window without one has no bound to project against. */
29
+ resetsAt: number | null;
30
+ now: number;
31
+ /** How far back the rate is measured; the current window may be shorter than this. */
32
+ lookbackMs: number;
33
+ /** The reading behind this window is older than the hub's freshness bound, so none of these numbers describe it now. */
34
+ stale?: boolean;
35
+ points: readonly ProjectionPoint[];
36
+ }
37
+
38
+ const finite = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v);
39
+
40
+ /**
41
+ * A steady burn projects a time; too few points, no burn at all, an unbounded or already stale window, and a
42
+ * projection that lands after the window's own reset each answer `unknown` with the cause named, never a time.
43
+ */
44
+ export function projectExhaustion(input: ProjectionInput): ExhaustionProjection {
45
+ const { used, windowStart, resetsAt, now, lookbackMs, points, stale } = input;
46
+ // A stale reading is no usable reading, exactly like a window whose reset has passed: the numbers it still carries
47
+ // describe an earlier window, so no time is claimed from them.
48
+ if (stale === true || !finite(used) || used < 0 || used > 1) return { state: "unknown", cause: "unknown_usage" };
49
+ if (!finite(windowStart) || !finite(resetsAt) || windowStart >= now || resetsAt <= now) return { state: "unknown", cause: "unknown_usage" };
50
+ if (!finite(lookbackMs) || lookbackMs <= 0) return { state: "unknown", cause: "few_points" };
51
+ // A reset inside the lookback: the window opened after the lookback did, so the rate is measured from the window
52
+ // start and never across the reset. The projection says which span it used.
53
+ const lookbackFrom = now - lookbackMs;
54
+ const from = Math.max(windowStart, lookbackFrom);
55
+ const basis: "lookback" | "window" = from > lookbackFrom ? "window" : "lookback";
56
+ const inside = points.filter(p => finite(p.at) && finite(p.tokens) && p.tokens >= 0 && p.at >= from && p.at <= now).sort((a, b) => a.at - b.at);
57
+ const total = points.filter(p => finite(p.at) && finite(p.tokens) && p.tokens > 0 && p.at >= windowStart && p.at <= now).reduce((sum, p) => sum + p.tokens, 0);
58
+ if (used >= 1) return { state: "projected", at: now, basis };
59
+ if (inside.length < 2) return { state: "unknown", cause: "few_points" };
60
+ // The points are buckets stamped at their start, so their burn covers the time from the first bucket's start to `now`,
61
+ // the partial last hour included. Measuring between the two stamps would count n buckets over n-1 hours and overstate
62
+ // the rate (two points, the minimum: doubled, and the forecast an hour early).
63
+ const elapsed = now - inside[0]!.at;
64
+ if (elapsed <= 0) return { state: "unknown", cause: "few_points" };
65
+ const burned = inside.reduce((sum, p) => sum + p.tokens, 0);
66
+ // No tokens at all in the window is no data, not a zero rate: a window nobody used cannot be projected either way.
67
+ if (total <= 0 || burned <= 0) return { state: "unknown", cause: "no_burn" };
68
+ // The window's own numbers give its capacity: what is burnt now is `used` of it.
69
+ const capacity = total / used, remaining = (1 - used) * capacity;
70
+ const at = now + remaining / (burned / elapsed);
71
+ if (!Number.isFinite(at)) return { state: "unknown", cause: "few_points" };
72
+ if (at > resetsAt) return { state: "unknown", cause: "reset_first" };
73
+ return { state: "projected", at: Math.round(at), basis };
74
+ }
75
+
76
+ const CAUSE_TEXT: Record<Extract<ExhaustionProjection, { state: "unknown" }>["cause"], string> = {
77
+ few_points: "too few points yet",
78
+ no_burn: "no burn yet",
79
+ reset_first: "it resets first",
80
+ unknown_usage: "no usable reading",
81
+ };
82
+
83
+ /**
84
+ * #1513 AC2: one sentence every surface renders, so the dashboard, the console and `ahub budget` say the same thing.
85
+ * A projected window names the time; an unknown one names why, never a date.
86
+ */
87
+ export function projectionText(projection: ExhaustionProjection, when: (at: number) => string): string {
88
+ return projection.state === "projected"
89
+ ? `reaches its limit ${when(projection.at)}${projection.basis === "window" ? " (rate since the window opened)" : ""}`
90
+ : `no forecast: ${CAUSE_TEXT[projection.cause]}`;
91
+ }
92
+
93
+ /** The window's own length, for the lookback cap: a 5 h window is never measured over more than 5 h. */
94
+ export const WINDOW_MINS: Record<string, number> = { "5h": 300, week: 10_080, tokens: 300 };
95
+
96
+ /** The left fraction of a window, or null when the reading is not a usable number. Never a negative or a faked zero. */
97
+ export function windowLeft(used: number | null | undefined): number | null {
98
+ return finite(used) && used >= 0 && used <= 1 ? 1 - used : null;
99
+ }
@@ -40,6 +40,8 @@ export interface RunnerOptions {
40
40
  projectDir: string; stateDir: string; storageDir: string; projectKey: string;
41
41
  enabled: boolean | (() => boolean); isDenied: (path: string) => boolean;
42
42
  onResult?: (receipt: RunReceipt) => void | Promise<void>;
43
+ /** #1555 AC6: whether the task is approved or cancelled, so a run that settles after its task closed is compacted when it leaves the queue. */
44
+ taskClosed?: (task: number) => boolean;
43
45
  /** Daemon authority fence, re-evaluated across every asynchronous stage. */
44
46
  isCurrent?: (request: CheckRequest) => boolean;
45
47
  /** Test seams; never supplied from a tool request or config. */
@@ -262,7 +264,10 @@ export class ContainerRunner {
262
264
  const entry = this.queue.shift(); if (!entry) return;
263
265
  this.active = entry;
264
266
  try { await this.execute(entry); }
265
- finally { this.active = undefined; this.entries.delete(entry.receipt.run); entry.resolve({ ...entry.receipt }); void this.drain(); }
267
+ finally { this.active = undefined; this.entries.delete(entry.receipt.run); entry.resolve({ ...entry.receipt }); void this.compactIfClosed(entry.receipt.task); void this.drain(); }
268
+ }
269
+ private async compactIfClosed(task: number): Promise<void> {
270
+ try { if (this.options.taskClosed?.(task)) await this.compactTask(task); } catch { /* retention only: the files stay */ }
266
271
  }
267
272
  private async heavy(entry: Entry): Promise<() => Promise<void>> {
268
273
  const lock = join(this.common, "ahub-heavy.lock");
@@ -497,6 +502,25 @@ export class ContainerRunner {
497
502
  }
498
503
  }
499
504
  async consumeOutput(run: string): Promise<void> { if (/^[a-f0-9-]{36}$/.test(run)) await rm(join(this.root, run, "output.log"), { force: true }); }
505
+ /**
506
+ * #1555 AC6: a task reached approved or cancelled. Its finished receipts keep every field the verdict and the metrics read, but lose the output tail, and the staged output
507
+ * file goes with it (nobody reads either once the task is closed). A run still queued or running is left alone, and each rewrite goes through the receipt's own save turn.
508
+ */
509
+ async compactTask(task: number): Promise<number> {
510
+ const names = await readdir(this.records).catch(error => { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; });
511
+ let compacted = 0;
512
+ for (const name of names) {
513
+ const run = name.endsWith(".json") ? name.slice(0, -5) : "";
514
+ if (!/^[a-f0-9-]{36}$/.test(run) || this.entries.has(run)) continue;
515
+ let receipt: RunReceipt | undefined;
516
+ try { receipt = await this.result(run); } catch { continue; }
517
+ if (!receipt || receipt.task !== task || (receipt.status !== "finished" && receipt.status !== "stale")) continue;
518
+ if (receipt.tail !== "") { receipt.tail = ""; await this.save(receipt); }
519
+ await this.consumeOutput(run);
520
+ compacted++;
521
+ }
522
+ return compacted;
523
+ }
500
524
  async cancel(run: string): Promise<void> {
501
525
  const entry = this.entries.get(run); if (!entry) return;
502
526
  entry.receipt.cancelled = true; entry.abort.abort();
@@ -8,6 +8,8 @@ import type { PeerAdapter } from "./peers.ts";
8
8
 
9
9
  export interface ClaudeLaunchRecordProof {
10
10
  launchId: string;
11
+ launcherPid?: number;
12
+ launcherSignature?: string;
11
13
  executionCwd?: string;
12
14
  privateRecord: boolean;
13
15
  permissionHook: boolean;
@@ -28,7 +30,9 @@ export function readClaudeLaunchProof(stateDir: string, peer: string, instanceId
28
30
  if (count > 16 * 1024) return;
29
31
  const row = JSON.parse(bytes.subarray(0, count).toString("utf8"));
30
32
  if (row?.instanceId !== instanceId || typeof row.launchId !== "string" || !row.launchId || row.launchId.length > 128) return;
31
- return { launchId: row.launchId, privateRecord: stat.nlink === 1 && (stat.mode & 0o777) === 0o600 && !!process.getuid && stat.uid === process.getuid(),
33
+ return { launchId: row.launchId,
34
+ ...(Number.isSafeInteger(row.launcherPid) && row.launcherPid > 0 ? { launcherPid: row.launcherPid } : {}),
35
+ ...(typeof row.launcherSignature === "string" && row.launcherSignature.length > 0 && row.launcherSignature.length <= 256 && !/[\p{Cc}\p{Cf}]/u.test(row.launcherSignature) ? { launcherSignature: row.launcherSignature } : {}), privateRecord: stat.nlink === 1 && (stat.mode & 0o777) === 0o600 && !!process.getuid && stat.uid === process.getuid(),
32
36
  ...(typeof row.executionCwd === "string" && row.executionCwd.length <= 4096 && isAbsolute(row.executionCwd) ? { executionCwd: row.executionCwd } : {}),
33
37
  permissionHook: row.permissionHook === true, unattended: row.unattended === true,
34
38
  ...(typeof row.hookPurpose === "string" ? { hookPurpose: row.hookPurpose } : {}) };
@@ -21,12 +21,15 @@ export function conductorProgressSink(record: (event: HubEvent) => void, feed: P
21
21
  }
22
22
 
23
23
  /** What `Budget.status` returns, with the fields added after it optional so an older shape still projects. */
24
- type PublicBudgetStatus = Record<string, { windows: (Omit<ReturnType<Budget["status"]>[string]["windows"][number], "kind" | "superseded"> & { kind?: WindowKind; superseded?: boolean })[]; paused?: ReturnType<Budget["status"]>[string]["paused"]; accountUsage?: QuotaAccountReading }>;
24
+ type PublicBudgetStatus = Record<string, { windows: (Omit<ReturnType<Budget["status"]>[string]["windows"][number], "kind" | "superseded"> & { kind?: WindowKind; superseded?: boolean; left?: number | null; projection?: unknown })[]; paused?: ReturnType<Budget["status"]>[string]["paused"]; accountUsage?: QuotaAccountReading }>;
25
25
  export function publicPeerBudget(status: PublicBudgetStatus, nameable: (text: string) => boolean): Record<string, unknown> {
26
26
  return Object.fromEntries(Object.entries(status).map(([peer, value]) => [peer, {
27
27
  windows: value.windows.map(window => ({ id: window.id, kind: windowKind(window), used: window.used, at: window.at, stale: window.stale, ...(window.superseded ? { superseded: true } : {}),
28
28
  ...(window.resetsAt === undefined ? {} : { resetsAt: window.resetsAt }),
29
29
  ...(window.windowMins === undefined ? {} : { windowMins: window.windowMins }),
30
+ // #1513 AC2: the window's remainder and its forecast travel with it, so the console, `ahub budget --json` and the page agree.
31
+ ...(window.left === undefined ? {} : { left: window.left }),
32
+ ...(window.projection === undefined ? {} : { projection: window.projection }),
30
33
  source: nameable(window.source) ? window.source : "[quota source withheld]",
31
34
  })),
32
35
  ...(value.paused ? { paused: { since: value.paused.since, resetsAt: value.paused.resetsAt, reason: "quota" } } : {}),
@@ -132,7 +135,7 @@ export function conductorStart(peer: unknown, mode: unknown, preview: (peer: str
132
135
 
133
136
  const numberOrNull = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;
134
137
  export interface ConductorStatusInput {
135
- peers: Array<{ peer: string; state?: string; attached?: boolean; queued?: number; needsReview?: number; manualHeld?: boolean; hold?: ConductorHold | null; budgetPause?: { since?: number; resetsAt?: number } | null; windows?: Array<{ id: string; used?: number; resetsAt?: number; at?: number; source?: string }>; doing?: PeerDoing | null }>;
138
+ peers: Array<{ peer: string; state?: string; attached?: boolean; queued?: number; needsReview?: number; manualHeld?: boolean; hold?: ConductorHold | null; budgetPause?: { since?: number; resetsAt?: number } | null; windows?: Array<{ id: string; used?: number; resetsAt?: number; at?: number; source?: string; left?: number | null; projection?: unknown }>; doing?: PeerDoing | null }>;
136
139
  taskCounts: Record<string, number>;
137
140
  approvals: Array<{ peer: string; tool?: string; at?: number }>;
138
141
  }
@@ -146,7 +149,9 @@ export function publicConductorStatus(input: ConductorStatusInput, now = Date.no
146
149
  manualHold: p.manualHeld === undefined ? null : { held: p.manualHeld, actor: p.manualHeld ? "user" : null },
147
150
  conductorHold: p.hold ? { actor: p.hold.actor, since: numberOrNull(p.hold.since) } : null,
148
151
  budgetPause: p.budgetPause ? { since: numberOrNull(p.budgetPause.since), resetsAt: numberOrNull(p.budgetPause.resetsAt) } : null,
149
- windows: p.windows === undefined ? null : p.windows.map((w) => ({ id: w.id, used: numberOrNull(w.used), resetsAt: numberOrNull(w.resetsAt), at: numberOrNull(w.at), source: w.source ?? null })),
152
+ // #1513 AC2: hub_status reports the same remainder and forecast the dashboard and the console render.
153
+ windows: p.windows === undefined ? null : p.windows.map((w) => ({ id: w.id, used: numberOrNull(w.used), resetsAt: numberOrNull(w.resetsAt), at: numberOrNull(w.at), source: w.source ?? null,
154
+ ...(w.left === undefined ? {} : { left: numberOrNull(w.left) }), ...(w.projection === undefined ? {} : { projection: w.projection }) })),
150
155
  // Native reports retain peer authorship; incoming message labels carry their own display provenance.
151
156
  doing: !p.doing ? null : p.doing.text === DOING_STUB ? { text: DOING_STUB, source: p.doing.source, at: numberOrNull(p.doing.at) }
152
157
  : p.doing.source === "label" ? { text: sanitize(p.doing.text), source: "label", at: numberOrNull(p.doing.at), note: INCOMING_LABEL_NOTE, untrusted: true }
@@ -189,9 +189,10 @@ shapes.set(researchRunners, { item: block({ publicKey: text, projects: strings,
189
189
  const schema: Record<string, Check> = {
190
190
  _autonomy: v => { autonomyOwnership(v); },
191
191
  ...Object.assign({}, ...ADAPTERS.map(adapter => adapter.configuration?.schema?.(nativeValidators) ?? {})),
192
- watchdog_ms: number(1, 2_147_483_647), kimi_cmd: argv, qwen_cmd: argv, jcode_cmd: argv, codex_bin: text, jcode_home: text, jcode_provider_profile: text,
192
+ watchdog_ms: number(1, 2_147_483_647), kimi_cmd: argv, qwen_cmd: argv, jcode_cmd: argv, codex_bin: text, jcode_home: text, jcode_mcp_allow: strings, jcode_provider_profile: text,
193
193
  action_policy: block({ enabled: bool, floor: bool, always_ask: (v, k) => { actionPolicyConfig({ always_ask: v }); }, budgets: map(number(0, 1000, true), ACTION_CLASSES) }),
194
194
  permission_modes: v => { permissionDefaults(v); }, protect_instruction_files: bool,
195
+ instructed: block({ mode: words(["off", "exact", "intent"]) }),
195
196
  adapter_modules: v => { adapterModuleDeclarations(v); },
196
197
  adapters: v => { createProjectAdapterCatalog(v); }, instances: v => { validateInstances(v, createProjectAdapterCatalog()); }, pet: validatePetConfig,
197
198
  batch_max: number(1, 100_000, true), batch_ms: number(0, 2_147_483_647), queue_cap: number(1, 1_000_000, true),
@@ -210,6 +211,8 @@ const schema: Record<string, Check> = {
210
211
  budget: block({ gate: number(0, 1), stale_min: timerMinutes, poll_min: timerMinutes, checkpoint_timeout_s: timerSeconds, kimi_tokens_5h: number(0), wait_max_min: number(0) }),
211
212
  context: block({ gate: number(0, 1), stale_min: timerMinutes, max_assignment_used: number(0, 1) }),
212
213
  supervision: block({ mode: words(["off", "shadow", "advisory"]) }),
214
+ edit_governance: block({ arm: words(["baseline", "route_guard", "occ_guard", "combined_guard"]) }),
215
+ roadmap: block({ github_mirror: bool, github_write: words(["off", "conductor"]) }),
213
216
  bus: block({ max_attempts: operationalNumberCheck("bus.max_attempts"), digest_max: operationalNumberCheck("bus.digest_max"), pull_budget_bytes: operationalNumberCheck("bus.pull_budget_bytes"), notes_kept: operationalNumberCheck("bus.notes_kept"), terminal_history_limit: operationalNumberCheck("bus.terminal_history_limit"), accepted_settle_ms: operationalNumberCheck("bus.accepted_settle_ms") }),
214
217
  adapter_timing: block({ acp_tool_ceiling_min: operationalNumberCheck("adapter_timing.acp_tool_ceiling_min"), acp_activity_batch_ms: operationalNumberCheck("adapter_timing.acp_activity_batch_ms"), jcode_steer_timeout_s: operationalNumberCheck("adapter_timing.jcode_steer_timeout_s") }),
215
218
  model_relay: block({ cooldown_failures: operationalNumberCheck("model_relay.cooldown_failures"), cooldown_s: operationalNumberCheck("model_relay.cooldown_s"), cooldown_cap_s: operationalNumberCheck("model_relay.cooldown_cap_s"), terminal_history_limit: operationalNumberCheck("model_relay.terminal_history_limit") }),
@@ -279,9 +282,9 @@ const restart: Record<string, string> = {
279
282
  checks: "Bounded runner and completion-check contracts are constructed together",
280
283
  pii: "Existing native sessions retain their startup privacy boundary", data: "Existing native sessions retain their startup read-only policy",
281
284
  profile: "Session tool schemas and profile contracts are bound at startup", profile_overrides: "Session tool schemas and profile contracts are bound at startup",
282
- text_projection: "Converter and cache ownership are bound at startup", corpus: "The corpus index is bound to its roots at startup", terminal: "Terminal provider is supplied by the daemon lifecycle", bench: "Benchmark execution environment is selected before work starts",
285
+ text_projection: "Converter and cache ownership are bound at startup", corpus: "The corpus index is bound to its roots at startup", roadmap: "GitHub mirror authority is bound at startup", terminal: "Terminal provider is supplied by the daemon lifecycle", bench: "Benchmark execution environment is selected before work starts",
283
286
  };
284
- const live = new Set(["visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs", "supervision"]);
287
+ const live = new Set(["instructed", "visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs", "supervision", "edit_governance"]);
285
288
  const nextMemory = new Set(["memory.inject_tokens", "memory.brief_items", "memory.suggest_edges", "memory.preface_unused_after"]);
286
289
  /** Closed top-level schema; leaf overrides retain the existing session/runtime boundaries. */
287
290
  export function configApply(key: string, scopes: readonly ConfigIdentityScope[] = []): ApplyRule {
@@ -15,7 +15,7 @@ const UNSAFE = new Set(["__proto__", "constructor", "prototype"]);
15
15
  /** Instance fields that choose no executable and no home. */
16
16
  export const TIER2_INSTANCE_FIELDS = ["kind", "roles", "start_mode", "review_mode", "readOnly", "worktree", "permission_mode"] as const;
17
17
  /** Instance fields that choose a native home, account or model, or widen what a reviewer verdict may skip (`review_scope`, #852): tier 3 (#685). */
18
- export const TIER3_INSTANCE_FIELDS = ["jcode_home", "provider", "model", "provider_profile", "review_scope"] as const;
18
+ export const TIER3_INSTANCE_FIELDS = ["jcode_home", "jcode_mcp_allow", "provider", "model", "provider_profile", "review_scope"] as const;
19
19
  /** Every NEVER_EDITABLE key except `instances`, which splits by field. */
20
20
  export const TIER3_PREFIXES: readonly string[] = NEVER_EDITABLE.filter(key => key !== "instances");
21
21
  const TIER2_BLOCKS: Readonly<Record<string, readonly string[]>> = {
@@ -37,7 +37,7 @@ export const MACHINE_LOCAL = [
37
37
  "invocation", // #445 C1: what another agent may be offered from this machine's agents (a digest-pinned allowlist); a committed config may not share a person's agents' commands with someone else's peers
38
38
  ] as const;
39
39
  /** Legacy exported field list stays compatible; new policies use the complete list below. */
40
- export const ALL_MACHINE_LOCAL = [...MACHINE_LOCAL, "research.runners", "rooms", "tasks.queue_backpressure", "context.max_assignment_used", "action_policy", "protect_instruction_files", "qwen_cmd", "jcode_cmd", "jcode_home", "jcode_provider_profile", "start.agents", "adapters", "adapter_modules", "text_projection", "instances"] as const;
40
+ export const ALL_MACHINE_LOCAL = [...MACHINE_LOCAL, "instructed", "edit_governance.arm", "roadmap.github_mirror", "roadmap.github_write", "research.runners", "rooms", "tasks.queue_backpressure", "context.max_assignment_used", "action_policy", "protect_instruction_files", "qwen_cmd", "jcode_cmd", "jcode_home", "jcode_mcp_allow", "jcode_provider_profile", "start.agents", "adapters", "adapter_modules", "text_projection", "instances"] as const;
41
41
  /** An empty list of these is a value (`start.agents` empty starts no agent), not "the default", so the empty-value drop below skips them. */
42
42
  const EMPTY_IS_VALUE: readonly string[] = ["start.agents"];
43
43
 
@@ -9,7 +9,7 @@ export function readNativeContext(definition: AdapterDefinition | undefined, val
9
9
 
10
10
  /** Native active-context occupancy, separate from accumulated billable usage (#185). */
11
11
  export interface ContextReading {
12
- source: "claude_statusline" | "codex_token_usage" | "acp_usage_update" | "jcode_usage_update";
12
+ source: "claude_statusline" | "codex_token_usage" | "acp_usage_update" | "jcode_usage_update" | "pi_usage";
13
13
  sessionId: string;
14
14
  measuredAt: number;
15
15
  tokens: number | null;
@@ -1,4 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { InstructedIpcSocket } from "./instructed-ipc.ts";
2
3
  import { join, resolve } from "node:path";
3
4
  import { projectContext } from "./project.ts";
4
5
  import { newToolRequestId, TOOL_WRITE_FEATURE, toolWriteOperation, toolWriteUnknownReply, toolWriteRefusedReply } from "./tool-request.ts";
@@ -22,7 +23,7 @@ export const PROTOCOL = 17;
22
23
  /** The descriptor's legacy protocol field remains this floor for previous published clients. */
23
24
  export const PROTOCOL_MIN = 16;
24
25
  // Literal metadata is read without executing a recovery target; consistency is pinned in tests.
25
- export const DAEMON_FEATURES = ["roadmap", "guidance_views", "guidance_variants", "guidance_probes", "guidance_probe_receipts", "execution_lineage", "model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "reviewer_quota", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "research_synthesis", "research_evidence_withdrawal", "advisor_surveys", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const;
26
+ export const DAEMON_FEATURES = ["instructed_intent", "instructed_exact", "roadmap", "roadmap_instructed", "guidance_views", "guidance_variants", "guidance_probes", "guidance_probe_receipts", "execution_lineage", "model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "reviewer_quota", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "research_synthesis", "research_evidence_withdrawal", "advisor_surveys", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const;
26
27
  /** Protocols a current coordinator may authenticate while upgrading a running source. */
27
28
  export const RECOVERY_SOURCE_PROTOCOLS = [9, 10, 11, 12, 13, 14, 15, 16, PROTOCOL] as const;
28
29
 
@@ -121,6 +122,8 @@ export function readControl(stateDir: string): ControlDescriptor | undefined {
121
122
  }
122
123
  }
123
124
 
125
+ let instructedIpcClaimed = false;
126
+
124
127
  const instancePins = new Map<string, { instanceId: string }>();
125
128
 
126
129
  /** Maximum supported 3600 s approval plus admission/transport margin; applies to every hub_invoke client path. */
@@ -204,8 +207,12 @@ export class ControlClient {
204
207
  }
205
208
  const expected = { projectId: hello.projectId ?? control.projectId, instanceId: pin?.instanceId ?? hello.instanceId ?? control.instanceId,
206
209
  projectRoot: hello.projectRoot ?? control.cwd };
210
+ const instructedIpc = process.env.AGENTHUB_INSTRUCTED_IPC;
211
+ if (instructedIpc !== undefined && (instructedIpc !== "1" || hello.role !== "console" || instructedIpcClaimed)) return Promise.reject(new Error("invalid or already used instructed control channel"));
212
+ if (instructedIpc !== undefined) instructedIpcClaimed = true;
207
213
  return new Promise((resolve, reject) => {
208
- const ws = new WebSocket(control.url);
214
+ // A daemon-launched instructed CLI can use only its inherited socket, never a WebSocket.
215
+ const ws = instructedIpc === undefined ? new WebSocket(control.url) : new InstructedIpcSocket(1024 * 1024) as unknown as WebSocket;
209
216
  const client = new ControlClient(ws);
210
217
  const timer = setTimeout(() => refuse(Object.assign(new Error(`hub connection timed out at ${control.url}`), { code: "AHUB_CONNECT_TIMEOUT" })), timeoutMs);
211
218
  const refuse = (error: Error) => { clearTimeout(timer); reject(error); ws.close(); };