@staix/agent-hub 0.43.0 → 0.45.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 (118) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +4 -4
  5. package/docs/agent-notes/local-worker.md +2 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +5 -2
  8. package/docs/agent-notes/tests.md +4 -3
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub-architecture.md +2 -0
  11. package/docs/design/agent-hub.md +1 -1
  12. package/docs/design/roadmap.md +75 -2
  13. package/docs/design/supervision.md +34 -2
  14. package/docs/design/task-board.md +36 -2
  15. package/docs/dogfood.md +20 -5
  16. package/docs/events.md +9 -3
  17. package/docs/influences.md +7 -0
  18. package/docs/memory.md +4 -4
  19. package/docs/operations.md +84 -31
  20. package/docs/quickstart.md +14 -2
  21. package/docs/research.md +18 -0
  22. package/docs/roadmap.json +4 -0
  23. package/docs/roadmap.md +9 -0
  24. package/docs/sdlc.md +19 -4
  25. package/docs/security.md +4 -4
  26. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  27. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  28. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  29. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  30. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  31. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  32. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  33. package/docs/verified.json +32 -26
  34. package/package.json +2 -2
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +585 -264
  37. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  38. package/plugins/agent-hub/server.js +629 -293
  39. package/scripts/check-docs.mjs +9 -1
  40. package/src/adapters/acp.ts +11 -1
  41. package/src/adapters/compat.ts +3 -3
  42. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  43. package/src/adapters/definitions/native-context.ts +10 -0
  44. package/src/adapters/jcode.ts +10 -0
  45. package/src/adapters/local-worker.ts +3 -2
  46. package/src/adapters/pi.ts +15 -4
  47. package/src/cli/console-state.ts +3 -1
  48. package/src/cli/help.ts +3 -1
  49. package/src/cli/identity.ts +2 -1
  50. package/src/cli/main.ts +12 -6
  51. package/src/cli/output.ts +2 -2
  52. package/src/cli/recovery-package.ts +16 -3
  53. package/src/cli/roadmap-write.ts +59 -0
  54. package/src/cli/roadmap.ts +81 -4
  55. package/src/cli/sdlc-output.ts +11 -1
  56. package/src/cli/upgrade-runtime.ts +10 -6
  57. package/src/cli/upgrade.ts +9 -3
  58. package/src/hub/agent-mem-range.ts +43 -0
  59. package/src/hub/board.ts +116 -2
  60. package/src/hub/bus.ts +4 -0
  61. package/src/hub/check-runner.ts +25 -1
  62. package/src/hub/claude-shell-wrapper.ts +2 -1
  63. package/src/hub/config-apply.ts +4 -2
  64. package/src/hub/config-trust.ts +1 -1
  65. package/src/hub/context-window.ts +1 -1
  66. package/src/hub/control-write-trace.ts +39 -2
  67. package/src/hub/cost-governance.ts +11 -7
  68. package/src/hub/daemon.ts +318 -53
  69. package/src/hub/dogfood-read.ts +4 -2
  70. package/src/hub/edit-guard.ts +100 -0
  71. package/src/hub/events.ts +79 -8
  72. package/src/hub/facts.ts +85 -2
  73. package/src/hub/hub-tools.ts +3 -1
  74. package/src/hub/lifecycle.ts +6 -1
  75. package/src/hub/log-rotation.ts +130 -0
  76. package/src/hub/memory-profile.ts +137 -21
  77. package/src/hub/no-writes.ts +1 -0
  78. package/src/hub/operational-authority.ts +3 -2
  79. package/src/hub/operational-settings.ts +2 -2
  80. package/src/hub/quota-events.ts +40 -0
  81. package/src/hub/recovery-store.ts +70 -24
  82. package/src/hub/report.ts +1 -1
  83. package/src/hub/research-experiments.ts +132 -0
  84. package/src/hub/research-quality.ts +13 -3
  85. package/src/hub/research-record.ts +38 -2
  86. package/src/hub/research.ts +128 -28
  87. package/src/hub/restart.ts +49 -2
  88. package/src/hub/roadmap-check.ts +65 -0
  89. package/src/hub/roadmap-decompose.ts +80 -0
  90. package/src/hub/roadmap-export.ts +27 -0
  91. package/src/hub/roadmap-sync.ts +97 -0
  92. package/src/hub/roadmap.ts +40 -0
  93. package/src/hub/runtime-capture-prune.ts +9 -1
  94. package/src/hub/runtime-prune-health.ts +5 -1
  95. package/src/hub/sdlc-branch-ci.ts +128 -0
  96. package/src/hub/sdlc-merge.ts +12 -5
  97. package/src/hub/sdlc-metrics.ts +33 -10
  98. package/src/hub/sdlc.ts +90 -10
  99. package/src/hub/settings.ts +1 -0
  100. package/src/hub/snapshots.ts +56 -1
  101. package/src/hub/startup-event-seeds.ts +21 -15
  102. package/src/hub/startup-timing.ts +3 -1
  103. package/src/hub/supervision-proposals.ts +10 -2
  104. package/src/hub/supervision-rules.ts +27 -4
  105. package/src/hub/supervision.ts +7 -0
  106. package/src/hub/task-pr.ts +47 -0
  107. package/src/hub/task-shell-command.ts +124 -0
  108. package/src/hub/task-worktree.ts +18 -11
  109. package/src/hub/tasks.ts +617 -45
  110. package/src/hub/usage-rollup.ts +35 -20
  111. package/src/hub/worktree-shelf.ts +2 -1
  112. package/src/local/sandbox.ts +2 -1
  113. package/src/local/shell-environment.ts +6 -0
  114. package/src/local/tools.ts +13 -1
  115. package/src/memory/brief.ts +10 -1
  116. package/src/memory/client.ts +3 -2
  117. package/src/pi/extension.ts +15 -3
  118. package/src/pi/tool-receipts.ts +26 -0
package/src/hub/sdlc.ts CHANGED
@@ -13,6 +13,7 @@ import { join } from "node:path";
13
13
  import { spawn } from "node:child_process";
14
14
  import { childEnv, stopOwnedProcess } from "./child-process.ts";
15
15
  import { hostExecutable } from "./host-executable.ts";
16
+ import { readBranchCi } from "./sdlc-branch-ci.ts";
16
17
 
17
18
  /** The off-mode default (#257). Off output, receipts and schemas keep this shape. */
18
19
  export const SDLC_STAGES = ["spec", "plan", "implement", "review", "verify", "merge", "release"] as const;
@@ -65,8 +66,14 @@ export interface MergeRecord {
65
66
  /** #481 S7: the merged PR's review and CI figures, read once at merge by the host. Absent when the PR could not be read; fields inside are null when unknown. */
66
67
  cost?: import("./cost-governance.ts").MergeCost;
67
68
  }
69
+ /** A merge observed by readback, with no locally executed merge or cleanup. */
70
+ export interface ReadbackMergeRecord {
71
+ repo: string; pr: number; head: string; at: number; state: "merged";
72
+ mergeCommit?: string; cost?: import("./cost-governance.ts").MergeCost;
73
+ }
68
74
  export interface SdlcReceipt {
69
75
  merge?: MergeRecord;
76
+ mergeReadback?: ReadbackMergeRecord;
70
77
  stage: SdlcStage;
71
78
  planReview?: PlanReviewReceipt;
72
79
  criteria?: CriteriaReceipt;
@@ -284,7 +291,7 @@ export function sdlcReceipt(value: unknown, previous: SdlcReceipt | undefined =
284
291
 
285
292
  function receiptIdentity(next: SdlcReceipt, previous: SdlcReceipt, raw: Record<string, unknown>): SdlcReceipt {
286
293
  const checklist = raw.criteria ?? raw.phase;
287
- if (next.repo !== previous.repo || next.pr !== previous.pr || next.head !== previous.head || next.reviewedHead !== previous.reviewedHead || next.localHead !== previous.localHead) delete next.merge;
294
+ if (next.repo !== previous.repo || next.pr !== previous.pr || next.head !== previous.head || next.reviewedHead !== previous.reviewedHead || next.localHead !== previous.localHead) { delete next.merge; delete next.mergeReadback; }
288
295
  // A test receipt never carries across a different linked issue or artifact.
289
296
  if (raw.redFirst === undefined && (next.repo !== previous.repo || next.issue !== previous.issue || next.pr !== previous.pr)) delete next.redFirst;
290
297
  // An acceptance names one spec issue; relinking the receipt to another drops it (#481 S1).
@@ -628,6 +635,8 @@ export function requiredCiBlocker(required: readonly string[], checks: PrEvidenc
628
635
  /** A complete resolved-thread snapshot already proves there is no pending unanswered bot thread. */
629
636
  export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[], repository?: string): ReviewReadiness | undefined {
630
637
  if (!evidence || evidence.unresolved !== 0) return undefined;
638
+ // A draft's failed aggregate needs job-step evidence, which this compact snapshot does not carry.
639
+ if (evidence.draft === true && evidence.checks.some(check => check.name === "check (macos-latest)" && check.state === "failed")) return undefined;
631
640
  const checks = requiredCheckNames(repository, required);
632
641
  if (!checks.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks };
633
642
  if (!checks.every(name => evidence.checks.some(check => check.name === name)) || evidence.checks.some(check => check.state === "unknown")) return undefined;
@@ -641,7 +650,30 @@ export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, ex
641
650
  }
642
651
 
643
652
  /** `checks` (#824) names the required checks that were judged, so a fresh reviewer can be told which ones passed at this head; absent when the read was unknown. */
644
- export interface ReviewReadiness { head?: string; ready: boolean; blockers: string[]; reusedRun?: number; checks?: string[] }
653
+ export interface ReviewReadiness { head?: string; ready: boolean; blockers: string[]; reusedRun?: number; checks?: string[]; deferred?: string[]; draftApprovalEligible?: boolean }
654
+
655
+ /** Only this repository's actual draft-deferral step can explain its failed macOS aggregate. */
656
+ async function draftMacosDeferred(repository: string, head: string, node: any, run: SdlcGh): Promise<boolean> {
657
+ if (repository.toLowerCase() !== "staixbwlb/agent-hub" || node?.name !== "check (macos-latest)"
658
+ || node.status !== "COMPLETED" || node.conclusion !== "FAILURE"
659
+ || node.checkSuite?.workflowRun?.workflow?.resourcePath !== "/STAIxBWLB/agent-hub/actions/workflows/check.yml") return false;
660
+ const url = typeof node.detailsUrl === "string" ? node.detailsUrl : "";
661
+ const match = /^https:\/\/github\.com\/STAIxBWLB\/agent-hub\/actions\/runs\/(\d+)\/job\/(\d+)$/.exec(url);
662
+ if (!match) return false;
663
+ const result = await run(["api", `repos/${repository}/actions/jobs/${match[2]}`], 10_000, undefined, 64 * 1024);
664
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) return false;
665
+ try {
666
+ const job = JSON.parse(result.stdout), steps = job.steps;
667
+ if (String(job.id) !== match[2] || String(job.run_id) !== match[1] || job.head_sha !== head
668
+ || job.name !== node.name || job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(steps)) return false;
669
+ const deferred = steps.filter((step: any) => step?.name === "macOS shards deferred for a draft PR");
670
+ const stacked = steps.filter((step: any) => step?.name === "macOS shards deferred for a stacked PR");
671
+ return deferred.length === 1 && deferred[0].status === "completed" && deferred[0].conclusion === "failure"
672
+ && stacked.length === 1 && stacked[0].conclusion === "skipped"
673
+ && steps.filter((step: any) => step?.conclusion === "failure").length === 1
674
+ && steps.every((step: any) => step?.status === "completed" && ["success", "skipped", "failure"].includes(step.conclusion));
675
+ } catch { return false; }
676
+ }
645
677
  /** Metadata-only pre-review admission; no remote body or comment text is requested. */
646
678
  export async function readReviewReadiness(receipt: SdlcReceipt, expected: string | undefined, run: SdlcGh = sdlcGh, requiredChecks: readonly string[] = []): Promise<ReviewReadiness> {
647
679
  const unknown = (): ReviewReadiness => ({ ready: false, blockers: ["review readiness unavailable"] });
@@ -649,7 +681,7 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
649
681
  const full = requiredCheckNames(receipt.repo, requiredChecks);
650
682
  if (!full.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks: full };
651
683
  const [owner, name] = receipt.repo.split("/");
652
- const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
684
+ const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state isDraft reviewDecision reviewRequests(first:100){nodes{__typename} pageInfo{hasNextPage}} commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt detailsUrl checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
653
685
  try {
654
686
  const deadline = performance.now() + 20_000;
655
687
  const bounded: SdlcGh = (args, timeout, cwd, cap) => performance.now() < deadline
@@ -682,6 +714,25 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
682
714
  }) : [];
683
715
  const ciBlocker = requiredCiBlocker(full, checkEvidence, completeChecks);
684
716
  if (ciBlocker) blockers.push(ciBlocker);
717
+ let deferred: string[] | undefined;
718
+ const mac = "check (macos-latest)";
719
+ const macNodes = requiredNodes.filter(node => (node as { name?: unknown })?.name === mac);
720
+ if (pr.isDraft === true && !blockers.some(blocker => blocker !== ciBlocker) && ciBlocker
721
+ && [mac, "check (ubuntu-latest)", "seeded guards"].every(name => full.includes(name)) && macNodes.length === 1
722
+ && !requiredCiBlocker(full.filter(name => name !== mac), checkEvidence, completeChecks)
723
+ && checkEvidence.filter(check => check.name === mac).length === 1
724
+ && checkEvidence.find(check => check.name === mac)?.state === "failed"
725
+ && await draftMacosDeferred(receipt.repo, pr.headRefOid, macNodes[0], bounded)) {
726
+ // The proof is fetched separately; the PR may have changed while it was read.
727
+ const after = await bounded(args, 10_000, undefined, 512 * 1024);
728
+ try {
729
+ const refreshed = JSON.parse(after.stdout);
730
+ if (after.code === 0 && !refreshed.errors && JSON.stringify(refreshed.data?.repository?.pullRequest) === JSON.stringify(pr)) {
731
+ blockers.splice(blockers.indexOf(ciBlocker), 1);
732
+ deferred = [mac];
733
+ }
734
+ } catch { /* Incomplete evidence never admits review. */ }
735
+ }
685
736
  if (ciBlocker && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
686
737
  && full.every(name => { const matches = (nodes as { name?: string; conclusion?: string }[]).filter(node => node?.name === name); return matches.length === 1 && matches[0]?.conclusion === "SKIPPED"; }) && sha(commit?.tree?.oid)) {
687
738
  reusedRun = await identicalTreeGate(receipt.repo, commit.tree.oid, bounded, full);
@@ -712,7 +763,12 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
712
763
  }
713
764
  if (unanswered) blockers.push("bot review threads unanswered");
714
765
  }
715
- return { head: pr.headRefOid, ready: blockers.length === 0, blockers: [...new Set(blockers)], checks: [...full], ...(reusedRun !== undefined ? { reusedRun } : {}) };
766
+ const requests = pr.reviewRequests;
767
+ const draftApprovalEligible = !!deferred && Object.hasOwn(pr, "reviewDecision")
768
+ && [null, "APPROVED", "REVIEW_REQUIRED"].includes(pr.reviewDecision)
769
+ && requests?.pageInfo?.hasNextPage === false && parsePrEvidence({ headRefOid: pr.headRefOid, state: pr.state, files: [], statusCheckRollup: [], reviewRequests: requests.nodes }).pendingReviews !== null
770
+ && threads?.pageInfo?.hasNextPage === false && Array.isArray(threads.nodes) && threads.nodes.every((thread: { isResolved?: unknown }) => thread?.isResolved === true);
771
+ return { head: pr.headRefOid, ready: blockers.length === 0, blockers: [...new Set(blockers)], checks: full.filter(name => !deferred?.includes(name)), ...(deferred ? { deferred, draftApprovalEligible } : {}), ...(reusedRun !== undefined ? { reusedRun } : {}) };
716
772
  } catch { return unknown(); }
717
773
  }
718
774
 
@@ -739,15 +795,21 @@ async function identicalTreeGate(repository: string, tree: string, run: SdlcGh,
739
795
  }
740
796
 
741
797
  /** PR cost evidence excludes titles, bodies and comment text; unknown/truncated coverage never becomes zero. */
742
- export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh): Promise<import("./cost-governance.ts").CostPr | undefined> {
798
+ export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh, snapshot?: unknown, expectedHead?: string, firstSubmittedHead?: string, recordedHeadInventory = false): Promise<import("./cost-governance.ts").CostPr | undefined> {
743
799
  if (!repo(repository) || !id(number)) return;
744
800
  const [owner, name] = repository.split("/");
745
801
  try {
746
802
  const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){number state headRefOid mergedAt commits(first:100){nodes{commit{oid}} pageInfo{hasNextPage}} reviews(first:100){nodes{databaseId commit{oid}} pageInfo{hasNextPage}}}}}";
747
- const reply = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${number}`], 10_000, undefined, 128 * 1024);
748
- if (reply.code !== 0) return;
749
- const parsed = JSON.parse(reply.stdout), pr = parsed.data?.repository?.pullRequest;
750
- if (parsed.errors || pr?.number !== number || !["OPEN", "CLOSED", "MERGED"].includes(pr.state)) return;
803
+ let pr: any;
804
+ if (snapshot !== undefined) pr = snapshot;
805
+ else {
806
+ const reply = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${number}`], 10_000, undefined, 128 * 1024);
807
+ if (reply.code !== 0) return;
808
+ const parsed = JSON.parse(reply.stdout);
809
+ if (parsed.errors) return;
810
+ pr = parsed.data?.repository?.pullRequest;
811
+ }
812
+ if (pr?.number !== number || !["OPEN", "CLOSED", "MERGED"].includes(pr.state) || (expectedHead !== undefined && pr.headRefOid !== expectedHead)) return;
751
813
  const result: import("./cost-governance.ts").CostPr = { repo: repository, pr: number, state: pr.state, complete: false,
752
814
  ...(typeof pr.mergedAt === "string" && Number.isFinite(Date.parse(pr.mergedAt)) ? { mergedAt: Date.parse(pr.mergedAt) } : {}) };
753
815
  if (pr.state !== "MERGED") return result; // Cost metrics count merged PRs, not an active work queue.
@@ -763,7 +825,25 @@ export async function readPrCostHistory(repository: string, number: number, run:
763
825
  const linked = runs.workflow_runs.filter((row: { head_sha?: string; pull_requests?: number[] }) => heads.has(row.head_sha ?? "") || Array.isArray(row.pull_requests) && row.pull_requests.includes(number));
764
826
  if (linked.some((row: { id?: number; run_attempt?: number }) => !id(row.id) || !id(row.run_attempt))) return result;
765
827
  result.ciRuns = linked.map((row: { id: number; run_attempt: number }) => ({ id: row.id, attempt: row.run_attempt }));
766
- result.complete = reviewComplete && commitComplete && runs.total_count === runs.workflow_runs.length;
828
+ // The dogfood reader supplies a separately validated, complete recorded-head inventory for its bounded time window.
829
+ if (recordedHeadInventory && runs.total_count === runs.workflow_runs.length) {
830
+ result.complete = reviewComplete && commitComplete;
831
+ return result;
832
+ }
833
+ const directComplete = runs.total_count === runs.workflow_runs.length && runs.workflow_runs.every((row: { pull_requests?: number[] }) => Array.isArray(row.pull_requests) && row.pull_requests.length > 0 && row.pull_requests.every(id));
834
+ if (directComplete) {
835
+ result.ciRuns = runs.workflow_runs.filter((row: { pull_requests: number[] }) => row.pull_requests.includes(number)).map((row: { id: number; run_attempt: number }) => ({ id: row.id, attempt: row.run_attempt }));
836
+ result.complete = reviewComplete && commitComplete;
837
+ }
838
+ const branch = await readBranchCi(repository, number, firstSubmittedHead, run);
839
+ const sameDirectRuns = !directComplete || branch && result.ciRuns?.length === branch.runs.length && result.ciRuns.every(row => branch.runs.some(candidate => candidate.id === row.id));
840
+ if (branch && sameDirectRuns) {
841
+ result.ciRuns = branch.runs;
842
+ result.fullGateRuns = branch.fullGateRuns; result.cancelledGateRuns = branch.cancelledGateRuns;
843
+ result.successfulGateRuns = branch.successfulGateRuns; result.failedGateRuns = branch.failedGateRuns; result.otherGateRuns = branch.otherGateRuns;
844
+ result.macosShardRuns = branch.macosShardRuns; result.firstPass = branch.firstPass;
845
+ result.complete = reviewComplete && commitComplete;
846
+ }
767
847
  return result;
768
848
  } catch { return; }
769
849
  }
@@ -67,6 +67,7 @@ export const SETTINGS: readonly SettingDef[] = [
67
67
  ...OPERATIONAL_NUMBERS.map(({ defaultValue, unit, inventory, ...def }): SettingDef => def),
68
68
  { key: "tasks.auto_pull", group: "Switches", label: "Auto-pull the top reserved ready card when a planner slot frees", type: "boolean", store: "config", applies: "live", risk: "raises", floor: false, path: ["tasks", "auto_pull"] },
69
69
  // #1221 T2: off evaluates nothing, shadow stores bounded proposals with no inbox row or notice, advisory may also show one in the inbox.
70
+ { key: "edit_governance.arm", group: "Switches", label: "Edit governance arm", type: "enum", values: ["baseline", "route_guard", "occ_guard", "combined_guard"], store: "config", applies: "live", risk: "raises", floor: "baseline", path: ["edit_governance", "arm"] },
70
71
  { key: "supervision.mode", group: "Switches", label: "Supervision proposals: off, shadow (stored, zero-effect) or advisory (also shown in the inbox)", type: "enum", values: ["off", "shadow", "advisory"], store: "config", applies: "live", risk: "raises", floor: "off", path: ["supervision", "mode"] },
71
72
  { key: "tasks.queue_backpressure.max_queued", group: "Routing", label: "Automatic offers: max queued envelopes (0 disables)", type: "integer", min: 0, max: QUEUE_BACKPRESSURE_LIMITS.max_queued, store: "config", applies: "live", risk: "raises", path: ["tasks", "queue_backpressure", "max_queued"] },
72
73
  { key: "tasks.queue_backpressure.max_oldest_s", group: "Routing", label: "Automatic offers: max oldest queued age in seconds (0 disables)", type: "integer", min: 0, max: QUEUE_BACKPRESSURE_LIMITS.max_oldest_s, store: "config", applies: "live", risk: "raises", path: ["tasks", "queue_backpressure", "max_oldest_s"] },
@@ -26,6 +26,49 @@ export const budgetNow = (budget: SnapshotBudget): number => budget.now ? budget
26
26
  export class SnapshotBudgetExceeded extends Error {
27
27
  constructor() { super("snapshot burst budget exhausted; boundary evidence is unknown"); }
28
28
  }
29
+ // ponytail: five consecutive exhausted bursts suspend a repository for ten minutes; an isolated capture worker is the upgrade path to avoiding this evidence-loss ceiling.
30
+ export const SNAPSHOT_COOLDOWN_FAILURES = 5;
31
+ export const SNAPSHOT_COOLDOWN_MS = 10 * 60_000;
32
+
33
+ /** In-memory, per-repository circuit breaker; a restart begins with no observations. */
34
+ export class SnapshotCooldown {
35
+ private readonly states = new Map<string, { failures: number; until: number }>();
36
+ private readonly observed = new WeakMap<SnapshotBudget, Set<string>>();
37
+ private readonly successful = new WeakMap<SnapshotBudget, Set<string>>();
38
+ blocked(repository: string, now: number): boolean {
39
+ const state = this.states.get(repository);
40
+ return !!state && now < state.until;
41
+ }
42
+ /** True only when this observation starts a cooldown and needs one diagnostic. */
43
+ exhausted(repository: string, budget: SnapshotBudget): boolean {
44
+ let repositories = this.observed.get(budget);
45
+ if (!repositories) { repositories = new Set(); this.observed.set(budget, repositories); }
46
+ if (repositories.has(repository)) return false;
47
+ repositories.add(repository);
48
+ const now = budgetNow(budget);
49
+ const state = this.states.get(repository) ?? { failures: 0, until: 0 };
50
+ state.failures = Math.min(SNAPSHOT_COOLDOWN_FAILURES, state.failures + 1);
51
+ if (state.failures >= SNAPSHOT_COOLDOWN_FAILURES) {
52
+ state.until = now + SNAPSHOT_COOLDOWN_MS;
53
+ this.states.set(repository, state);
54
+ return true;
55
+ }
56
+ this.states.set(repository, state);
57
+ return false;
58
+ }
59
+ success(repository: string, budget: SnapshotBudget): void {
60
+ let repositories = this.successful.get(budget);
61
+ if (!repositories) { repositories = new Set(); this.successful.set(budget, repositories); }
62
+ repositories.add(repository);
63
+ }
64
+ finish(budget: SnapshotBudget): void {
65
+ for (const repository of this.successful.get(budget) ?? []) {
66
+ if (!this.observed.get(budget)?.has(repository)) this.reset(repository);
67
+ }
68
+ this.successful.delete(budget);
69
+ }
70
+ reset(repository: string): void { this.states.delete(repository); }
71
+ }
29
72
  const SNAPSHOT_TIMEOUT_MS = 10_000;
30
73
  /**
31
74
  * The wall-clock timeout of one git child. Production (no `budget.now`): the remaining budget, between 1 ms and the 10 s ceiling, so a child is killed at the budget.
@@ -665,7 +708,7 @@ export class Turns {
665
708
  // Opened by a starting hub: a turn still open was cut short when the last run stopped. It has no end snapshot, and
666
709
  // it may have run until now, so its window ends now (other turns that overlapped it stay unknowable).
667
710
  this.db.query("UPDATE turns SET ended = ? WHERE ended IS NULL").run(Date.now());
668
- // ponytail: rows of finished tasks stay (a few per file per task); prune by task state if hub.db ever grows.
711
+ // Rows of a task that reached approved or cancelled are pruned by the daemon (#1555 AC6, `pruneTouches`).
669
712
  this.db.run("CREATE TABLE IF NOT EXISTS touches (task INTEGER NOT NULL, peer TEXT NOT NULL, path TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (task, peer, path))");
670
713
  this.db.run("CREATE INDEX IF NOT EXISTS touches_path ON touches (path)"); // the PreToolUse hook looks up one path
671
714
  this.db.run("CREATE TABLE IF NOT EXISTS turn_workspaces (turn TEXT PRIMARY KEY, root TEXT NOT NULL, start_tree TEXT, end_tree TEXT, changed TEXT NOT NULL DEFAULT '[]')");
@@ -793,6 +836,18 @@ export class Turns {
793
836
  if (!tasks.length) return [];
794
837
  return this.db.query(`SELECT * FROM touches WHERE task IN (${tasks.map(() => "?").join(",")})`).all(...tasks) as Touch[];
795
838
  }
839
+ /** #1555 AC6: a closed task's rows go. Every reader (conflicts, check-path, owner-write evidence) looks at open tasks only, and the counts the metrics read are frozen in history. */
840
+ pruneTouches(tasks: number[]): number {
841
+ if (!tasks.length) return 0;
842
+ let removed = 0;
843
+ this.db.transaction(() => { for (const id of tasks) removed += this.db.query("DELETE FROM touches WHERE task = ?").run(id).changes; })();
844
+ return removed;
845
+ }
846
+ /** Rows of tasks that closed while no hub ran, or before this pass existed: the ids with a row are asked about, and `closed` says which are terminal. */
847
+ pruneClosedTouches(closed: (task: number) => boolean): number {
848
+ const ids = (this.db.query("SELECT DISTINCT task FROM touches").all() as { task: number }[]).map(row => row.task).filter(closed);
849
+ return this.pruneTouches(ids);
850
+ }
796
851
  /** Other peers with a turn that was open at some point since `since`: their changes may be in this turn's diff. */
797
852
  busySince(peer: string, since: number): string[] {
798
853
  return (this.db.query("SELECT DISTINCT peer FROM turns WHERE peer != ? AND (ended IS NULL OR ended >= ?) ORDER BY peer").all(peer, since) as { peer: string }[]).map((r) => r.peer);
@@ -1,6 +1,7 @@
1
- import { closeSync, existsSync, openSync, readSync } from "node:fs";
1
+ import { closeSync, openSync, readSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { parseEventLine, type StampedEvent } from "./events.ts";
4
+ import { segmentsOf } from "./log-rotation.ts";
4
5
 
5
6
  const STARTUP_EVENT_BUFFER_BYTES = 64 * 1024;
6
7
  export interface StartupEventSeeds {
@@ -16,11 +17,12 @@ export interface StartupEventSeeds {
16
17
  /** One streaming pass, retaining every accepted row and every historical dedupe key. */
17
18
  export function readStartupEventSeeds(file: string, options: { bufferBytes?: number } = {}): StartupEventSeeds {
18
19
  const seeds: StartupEventSeeds = { events: [], complete: true, nativeStopsSeen: new Set(), claudeNativeUsageSeen: new Set(), readPasses: 0, readBytes: 0 };
19
- if (!existsSync(file)) return seeds;
20
+ const segments = segmentsOf(file); // #1546: rotated segments first, then the live file, so a restart still sees every dedupe key the kept history holds
21
+ if (!segments.length) return seeds;
20
22
  // Host-only chunk-boundary test seam, never a line, history or total-byte ceiling.
21
23
  const bufferBytes = options.bufferBytes ?? STARTUP_EVENT_BUFFER_BYTES;
22
24
  if (!Number.isSafeInteger(bufferBytes) || bufferBytes < 1) throw new Error("startup event buffer must be a positive integer; use the default reader buffer");
23
- const decoder = new StringDecoder("utf8"), buffer = Buffer.alloc(bufferBytes), fd = openSync(file, "r");
25
+ const decoder = new StringDecoder("utf8"), buffer = Buffer.alloc(bufferBytes);
24
26
  let parts: string[] = [];
25
27
  const accept = (line: string) => {
26
28
  const event = parseEventLine(line);
@@ -37,17 +39,21 @@ export function readStartupEventSeeds(file: string, options: { bufferBytes?: num
37
39
  }
38
40
  if (start < text.length) parts.push(text.slice(start));
39
41
  };
40
- try {
41
- seeds.readPasses++;
42
- for (;;) {
43
- const bytes = readSync(fd, buffer, 0, buffer.length, null);
44
- if (!bytes) break;
45
- seeds.readBytes += bytes;
46
- consume(decoder.write(buffer.subarray(0, bytes)));
47
- }
48
- consume(decoder.end());
42
+ seeds.readPasses++;
43
+ for (const segment of segments) {
44
+ let fd: number;
45
+ try { fd = openSync(segment.path, "r"); } catch { seeds.complete = false; continue; }
46
+ try {
47
+ for (;;) {
48
+ const bytes = readSync(fd, buffer, 0, buffer.length, null);
49
+ if (!bytes) break;
50
+ seeds.readBytes += bytes;
51
+ consume(decoder.write(buffer.subarray(0, bytes)));
52
+ }
53
+ consume(decoder.end());
54
+ } finally { closeSync(fd); }
49
55
  // readEvents also accepts a complete final JSON record without a newline.
50
- if (parts.length) { seeds.complete = false; accept(parts.join("")); }
51
- return seeds;
52
- } finally { closeSync(fd); }
56
+ if (parts.length) { seeds.complete = false; accept(parts.join("")); parts = []; }
57
+ }
58
+ return seeds;
53
59
  }
@@ -3,7 +3,9 @@ export const STARTUP_PHASES = [
3
3
  "schema", "source", "configuration", "control", "recovery", "journal", "bus", "memory", "model_runtime", "board",
4
4
  "task_checks", "task_ports", "task_board", "task_recovery",
5
5
  "task_runtime", "native_stop_seed", "budget", "usage_seed", "usage_rollup", "token_runtime", "token_seed",
6
- "services", "transcript_usage_seed", "ready", "post_ready",
6
+ "services", "transcript_usage_seed", "ready",
7
+ // #1445: the steps between ready and the end of start, each its own boundary; `post_ready` keeps what follows the last of them.
8
+ "post_ready_handoff", "post_ready_queue", "post_ready_watch", "post_ready_reconcile", "post_ready_goals", "post_ready_leases", "post_ready_crash", "post_ready_pi", "post_ready_drift", "post_ready",
7
9
  ] as const;
8
10
  export type StartupPhase = typeof STARTUP_PHASES[number];
9
11
 
@@ -243,6 +243,7 @@ export class SupervisionProposals {
243
243
  async observe(task: number): Promise<SupervisionProposal[]> {
244
244
  if (this.ports.isPrivate(task)) return [];
245
245
  const facts = await this.ports.facts(task);
246
+ if (this.ports.isPrivate(task)) return [];
246
247
  const side = facts.tasks.find((candidate) => candidate.id === task);
247
248
  if (!side) return [];
248
249
  const at = this.ports.now(), evaluation = evaluateSupervision(facts);
@@ -252,7 +253,11 @@ export class SupervisionProposals {
252
253
  const reading = evaluation.observations.filter((observation) => observation.task === task && !observation.limits.truncated);
253
254
  if (!clipped) {
254
255
  const fresh = new Set(reading.map(proposalKey));
255
- const stale = this.store.pendingFor(task).filter((proposal) => !fresh.has(proposal.key)).map((proposal) => proposal.id);
256
+ const covered = new Set(evaluation.evaluated.filter((entry) => entry.task === task).map((entry) => `${entry.rule}:${entry.revision}`));
257
+ const stale = this.store.pendingFor(task).filter((proposal) => {
258
+ const editRule = proposal.rule === "unverified_shell_write" || proposal.rule === "cascading_edit_after_failed_check";
259
+ return !fresh.has(proposal.key) && (!editRule || proposal.revision !== taskRevision(side).revision || covered.has(`${proposal.rule}:${proposal.revision}`));
260
+ }).map((proposal) => proposal.id);
256
261
  if (stale.length) this.store.expire(stale, "hub", at);
257
262
  }
258
263
  const added: SupervisionProposal[] = [];
@@ -330,7 +335,10 @@ export class SupervisionProposals {
330
335
  if (taskRevision(side).revision !== proposal.revision) return this.stale(proposal, "the task moved to another revision");
331
336
  if (this.ports.generation(proposal.task) !== proposal.generation) return this.stale(proposal, "the native session it was read under was replaced");
332
337
  // Recheck the input identity immediately before any effect: the same reading has to still hold now.
333
- if (!evaluateSupervision(facts).observations.some((observation) => proposalKey(observation) === proposal.key)) return this.stale(proposal, "the reading changed: new input replaced this proposal");
338
+ const reading = evaluateSupervision(facts);
339
+ if ((proposal.rule === "unverified_shell_write" || proposal.rule === "cascading_edit_after_failed_check")
340
+ && !reading.evaluated.some(entry => entry.task === proposal.task && entry.rule === proposal.rule && entry.revision === proposal.revision)) return { ok: false, error: "edit evidence unavailable; the proposal stays pending" };
341
+ if (!reading.observations.some((observation) => proposalKey(observation) === proposal.key)) return this.stale(proposal, "the reading changed: new input replaced this proposal");
334
342
  if (this.ports.held(proposal.task)) return { ok: false, error: "the owner has a needs_review delivery; resolve it before acting on this proposal" };
335
343
  // Authority is read again after the await: the board can move while the facts are being read, and a role or a
336
344
  // session that went away in that window must not run anything.
@@ -13,15 +13,18 @@ import type { DeliverableRecord } from "./deliverables.ts";
13
13
  */
14
14
 
15
15
  export const SUPERVISION_RULES = ["repeated_failure", "deliverable_invalidated_check", "declared_overlap_without_integration"] as const;
16
- export type SupervisionRuleId = (typeof SUPERVISION_RULES)[number];
16
+ /** Additive edit rules are evaluated only when a host supplies edit evidence. */
17
+ export const EDIT_SUPERVISION_RULES = ["unverified_shell_write", "cascading_edit_after_failed_check"] as const;
18
+ export const ALL_SUPERVISION_RULES = [...SUPERVISION_RULES, ...EDIT_SUPERVISION_RULES] as const;
19
+ export type SupervisionRuleId = (typeof ALL_SUPERVISION_RULES)[number];
17
20
  /** Bump one rule when its trigger, refs or reason codes change meaning: a stored observation names the version it was made under. */
18
- export const SUPERVISION_RULE_VERSION: Readonly<Record<SupervisionRuleId, number>> = { repeated_failure: 1, deliverable_invalidated_check: 1, declared_overlap_without_integration: 1 };
21
+ export const SUPERVISION_RULE_VERSION: Readonly<Record<SupervisionRuleId, number>> = { repeated_failure: 1, deliverable_invalidated_check: 2, declared_overlap_without_integration: 1, unverified_shell_write: 1, cascading_edit_after_failed_check: 1 };
19
22
 
20
23
  /** The existing hub operation an observation names. T1 names one; nothing in this module runs it. */
21
24
  export const SUPERVISION_ACTIONS = ["escalate", "recheck", "request_integration"] as const;
22
25
  export type SupervisionAction = (typeof SUPERVISION_ACTIONS)[number];
23
26
  /** Closed reason codes: an observation says why it fired in a token, never in prose. */
24
- export const SUPERVISION_REASONS = ["repeated_failure", "stale_check", "unintegrated_overlap"] as const;
27
+ export const SUPERVISION_REASONS = ["repeated_failure", "stale_check", "unintegrated_overlap", "unverified_shell_write", "cascading_edit_after_failed_check"] as const;
25
28
  export type SupervisionReasonCode = (typeof SUPERVISION_REASONS)[number];
26
29
  /** Why a rule could not decide for one task and revision. A gap is not a trigger and never a zero. */
27
30
  export const SUPERVISION_GAPS = ["no-history", "no-deliverable-measurement", "history-truncated"] as const;
@@ -96,10 +99,14 @@ export interface SupervisionEvaluation {
96
99
  evaluated: EvaluatedRevision[];
97
100
  }
98
101
 
102
+ /** Text-free, in-memory edit evidence bound to an owner revision. */
103
+ export interface EditRevisionFact { task: number; revision: string; unverified: number; cascading: number }
104
+
99
105
  export interface SupervisionFacts {
100
106
  tasks: readonly TaskRevisionFacts[];
101
107
  deliverables?: readonly DeliverableMeasurementFact[];
102
108
  overlaps?: readonly DeclaredOverlapFact[];
109
+ edits?: readonly EditRevisionFact[];
103
110
  }
104
111
 
105
112
  /** Records one rule reads from one revision. A longer revision is read as a prefix and the observation says `truncated`. */
@@ -213,7 +220,7 @@ function invalidatedCheck(side: Side, measurement: DeliverableMeasurementFact |
213
220
  let check: number | undefined;
214
221
  const recorded = new Set<string>();
215
222
  for (const [offset, entry] of side.window.entries()) {
216
- if (entry.event === "check passed") check = offset;
223
+ if (entry.event === "check passed" || entry.event === "check run passed") check = offset;
217
224
  for (const record of (entry.deliverables ?? []) as readonly DeliverableRecord[]) recorded.add(record.id);
218
225
  }
219
226
  if (check === undefined || !recorded.size) return {};
@@ -287,6 +294,22 @@ export function evaluateSupervision(facts: SupervisionFacts): SupervisionEvaluat
287
294
  if (!repeated.length) gaps.push(gapOf("repeated_failure", side.task.id, side.revision, "history-truncated"));
288
295
  if (!check.observation && !check.gap) gaps.push(gapOf("deliverable_invalidated_check", side.task.id, side.revision, "history-truncated"));
289
296
  }
297
+ for (const edit of facts.edits ?? []) {
298
+ const side = sides.get(edit.task);
299
+ if (!side || isClosedTaskState(side.task.state) || side.revision !== edit.revision) continue;
300
+ const rules = [
301
+ { rule: "unverified_shell_write" as const, count: edit.unverified },
302
+ { rule: "cascading_edit_after_failed_check" as const, count: edit.cascading },
303
+ ];
304
+ for (const item of rules) {
305
+ if (!Number.isSafeInteger(item.count) || item.count < 0) continue;
306
+ evaluated.push({ rule: item.rule, task: side.task.id, revision: side.revision });
307
+ if (side.limits.truncated) { gaps.push(gapOf(item.rule, side.task.id, side.revision, "history-truncated")); continue; }
308
+ if (item.count < REPEAT_FLOOR) continue;
309
+ observations.push({ rule: item.rule, version: SUPERVISION_RULE_VERSION[item.rule], task: side.task.id, revision: side.revision,
310
+ trigger: item.rule, refs: [], limits: side.limits, action: "recheck", reason: item.rule });
311
+ }
312
+ }
290
313
  for (const overlap of facts.overlaps ?? []) {
291
314
  const pair = unintegratedOverlap(overlap, sides);
292
315
  if (pair.evaluated) evaluated.push(pair.evaluated);
@@ -84,6 +84,13 @@ export class SupervisionFeed {
84
84
  return this.send(`task:${id}:${milestone}`, bits.join("; "), "status", id);
85
85
  }
86
86
 
87
+ /** R4: only ids and the fixed rule number enter the conductor's feed. */
88
+ roadmapFinding(taskId: number, milestone: number | null, rule: number, marker: string): boolean {
89
+ const task = this.d.tasks().find(row => row.id === taskId);
90
+ if (!task || !this.includes(task) || this.d.isPrivate(task) || milestone !== null && (!Number.isSafeInteger(milestone) || milestone < 1) || !Number.isSafeInteger(rule) || rule < 1 || rule > 8 || !/^[a-f0-9]{64}$/.test(marker)) return false;
91
+ return this.send(`roadmap:${marker}`, `roadmap${milestone === null ? "" : ` milestone ${milestone}`}, task ${taskId}: drift rule ${rule}; inspect ahub roadmap check`, "status", taskId);
92
+ }
93
+
87
94
  /** Only structured history metadata is read; notes may contain private content. */
88
95
  taskChanged(task: Task, entry: HistoryEntry, metadata: SupervisionFields = {}): void {
89
96
  const fields: SupervisionFields = { by: entry.by, owner: task.owner, ...(entry.reason ? { reason: entry.reason } : {}), ...metadata };
@@ -0,0 +1,47 @@
1
+ import type { SdlcGh } from "./sdlc.ts";
2
+ import { GITHUB_PAGE_SIZE, GITHUB_READ_DEADLINE_MS } from "./github-import.ts";
3
+
4
+ /** Create or recover one PR for a previously pushed, host-verified managed branch. */
5
+ export async function managedTaskPullRequest(input: { repo: string; branch: string; commit: string; task: number; title?: string; issue?: number; current: () => void }, run: SdlcGh): Promise<number> {
6
+ const { repo, branch, commit, task, title, issue, current } = input;
7
+ if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/.test(repo) || !Number.isSafeInteger(task) || task < 1 || !/^task\/[1-9][0-9]*-[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(branch) || !branch.startsWith(`task/${task}-`) || !/^[a-f0-9]{40}$/.test(commit) || issue !== undefined && (!Number.isSafeInteger(issue) || issue < 1)) throw new Error("managed PR identity is invalid; inspect the task and retry");
8
+ const target = `github.com/${repo}`;
9
+ const deadline = performance.now() + GITHUB_READ_DEADLINE_MS;
10
+ const call: SdlcGh = async (args, timeout, cwd, cap) => {
11
+ current(); const remaining = deadline - performance.now();
12
+ if (remaining <= 0) throw new Error("managed PR operation timed out; inspect GitHub before retrying hub_task_done");
13
+ const result = await run(args, Math.min(timeout ?? remaining, remaining), cwd, cap); current();
14
+ if (performance.now() > deadline) throw new Error("managed PR operation timed out; inspect GitHub before retrying hub_task_done");
15
+ return result;
16
+ };
17
+ const lookup = async (): Promise<{ number: number; draft: boolean } | undefined> => {
18
+ const reply = await call(["pr", "list", "--repo", target, "--state", "open", "--head", branch, "--limit", String(GITHUB_PAGE_SIZE), "--json", "number,headRefName,headRefOid,headRepository,isCrossRepository,isDraft,state"], 10_000, undefined, 256 * 1024);
19
+ if (reply.code !== 0) throw new Error("managed PR lookup unavailable; inspect GitHub and retry hub_task_done");
20
+ let rows: unknown; try { rows = JSON.parse(reply.stdout); } catch { throw new Error("managed PR lookup malformed; inspect GitHub and retry hub_task_done"); }
21
+ if (!Array.isArray(rows) || rows.length >= GITHUB_PAGE_SIZE) throw new Error("managed PR lookup incomplete; inspect GitHub and retry hub_task_done");
22
+ if (!rows.length) return undefined;
23
+ if (rows.length !== 1) throw new Error("managed branch has multiple open PRs; inspect GitHub before retrying");
24
+ const row = rows[0];
25
+ const name = (value: unknown) => value && typeof value === "object" && typeof (value as { nameWithOwner?: unknown }).nameWithOwner === "string" ? (value as { nameWithOwner: string }).nameWithOwner.toLowerCase() : undefined;
26
+ if (!Number.isSafeInteger(row?.number) || row.number < 1 || row.state !== "OPEN" || row.headRefName !== branch || row.headRefOid !== commit || typeof row.isDraft !== "boolean" || row.isCrossRepository !== false || name(row.headRepository) !== repo.toLowerCase()) throw new Error("managed PR identity or head is unavailable; inspect GitHub before retrying");
27
+ return { number: row.number, draft: row.isDraft };
28
+ };
29
+ let found = await lookup();
30
+ if (!found) {
31
+ const meta = await call(["api", `repos/${repo}`, "--hostname", "github.com", "--jq", ".default_branch"], 10_000, undefined, 4096);
32
+ const base = meta.stdout.trim();
33
+ if (meta.code !== 0 || !/^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/.test(base) || base.includes("..") || base.endsWith("/")) throw new Error("managed PR base branch unavailable; inspect GitHub before retrying");
34
+ const body = [`hub task ${task}`, ...(issue === undefined ? [] : [`Refs #${issue}`])].join("\n\n");
35
+ const created = await call(["pr", "create", "--repo", target, "--head", branch, "--base", base, "--title", title || `hub task ${task}`, "--body", body, "--draft"], 10_000, undefined, 4096);
36
+ if (created.code !== 0) throw new Error("managed PR creation was not confirmed; inspect GitHub before retrying hub_task_done");
37
+ found = await lookup();
38
+ if (!found) throw new Error("managed PR creation was not found; inspect GitHub before retrying hub_task_done");
39
+ }
40
+ if (found.draft) {
41
+ const ready = await call(["pr", "ready", String(found.number), "--repo", target], 10_000, undefined, 4096);
42
+ if (ready.code !== 0) throw new Error("managed PR readiness was not confirmed; inspect GitHub before retrying hub_task_done");
43
+ const verified = await lookup();
44
+ if (!verified || verified.number !== found.number || verified.draft) throw new Error("managed PR readiness or head changed; inspect GitHub before retrying hub_task_done");
45
+ }
46
+ return found.number;
47
+ }