@staix/agent-hub 0.35.0 → 0.37.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 (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
@@ -2,7 +2,8 @@ import { releaseTrackedClean } from "./release-worktree.ts";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { USER, type PeerId } from "./envelope.ts";
4
4
  import { hubGitEnv, hubGitSync } from "./git.ts";
5
- import { readDocEvidenceDetailed, type DocEvidence, type ReleaseGit, type ReleaseReadiness } from "./sdlc-release.ts";
5
+ import { readDocEvidenceDetailed, type DocEvidence, type ReleaseGit, type ReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
6
+ import { DEFAULT_RELEASE_POLICY, hasCommittedReleaseNotes, type ReleasePolicy } from "./sdlc-release-policy.ts";
6
7
  import type { SdlcGh } from "./sdlc.ts";
7
8
  import type { ReleaseGuardRequest, ReleasePushUpdate } from "../cli/sdlc-release-guard.ts";
8
9
 
@@ -13,9 +14,12 @@ const SHA = /^[0-9a-f]{40}$/;
13
14
  const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
14
15
  export const validReleaseVersion = (value: unknown): value is string => typeof value === "string" && value.length <= 128 && VERSION.test(value);
15
16
  export interface ReleaseDocsVerdict { fresh: true; errors: 0; documents: number; digest: string }
16
- export interface ReleaseAuthorization { schemaVersion: 1; id: string; by: PeerId; commit: string; version: string; at: number; docs: ReleaseDocsVerdict }
17
+ export type ReleaseDocsReceipt = ReleaseDocsVerdict | ({ source: "none" } & { fresh?: never; errors?: never; documents?: never; digest?: never });
18
+ export interface ReleaseAuthorization { schemaVersion: 1; id: string; by: PeerId; commit: string; version: string; at: number; docs: ReleaseDocsReceipt }
17
19
  export interface ReleaseAuthorizationPorts {
18
20
  git?: ReleaseGit;
21
+ /** Host reader for policy committed at the candidate; absence preserves legacy package/checker policy for existing callers. */
22
+ policy?: (commit: string, git: ReleaseGit) => ReleasePolicy;
19
23
  docs?: (root: string) => Promise<DocEvidence | undefined>;
20
24
  /** Test seam: the checker program the default reader spawns (#1120). Never set from configuration. */
21
25
  checker?: string;
@@ -28,7 +32,7 @@ export interface ReleaseAuthorizationPorts {
28
32
  }
29
33
  export type ReleaseGuardVerdict = { ok: true; receipts: ReleaseAuthorization[] } | { ok: false; error: string };
30
34
  interface Origin { hash: string; urls: string[]; repo?: string }
31
- interface Entry { receipt: ReleaseAuthorization; origin: Origin }
35
+ interface Entry { receipt: ReleaseAuthorization; origin: Origin; policy: ReleasePolicy; order: number }
32
36
  const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
33
37
  function docsVerdict(value: DocEvidence | undefined, commit: string, version: string): ReleaseDocsVerdict | undefined {
34
38
  if (!value || value.schemaVersion !== 1 || value.head !== commit || value.version !== version || value.fresh !== true || value.errors !== 0
@@ -46,6 +50,7 @@ function githubRepo(url: string): string | undefined {
46
50
  export class ReleaseAuthorizations {
47
51
  private readonly entries = new Map<string, Entry>();
48
52
  private latest?: Entry;
53
+ private authorizationOrder = 0;
49
54
  constructor(private readonly root: string, private readonly ports: ReleaseAuthorizationPorts) {}
50
55
  private current(): void { if (this.ports.current?.() === false) throw new ReleaseAuthorizationError("release authorization unavailable during lifecycle transition"); }
51
56
  /** #1120: a checker that is missing or failed is its own refusal; only evidence that is read and not fresh is "stale documentation". An injected reader keeps its undefined meaning (no evidence). */
@@ -75,6 +80,13 @@ export class ReleaseAuthorizations {
75
80
  if (result.code !== 0 || Buffer.byteLength(result.stdout) > 256 * 1024) throw new ReleaseAuthorizationError("release target evidence unavailable");
76
81
  return result.stdout.trim();
77
82
  }
83
+ private policy(git: ReleaseGit, commit: string): ReleasePolicy {
84
+ try { return structuredClone(this.ports.policy ? this.ports.policy(commit, git) : DEFAULT_RELEASE_POLICY); }
85
+ catch (error) {
86
+ const detail = error instanceof Error && error.message.length <= 300 ? `: ${error.message}` : "";
87
+ throw new ReleaseAuthorizationError(`committed release policy unavailable${detail}`);
88
+ }
89
+ }
78
90
  private origin(git: ReleaseGit, remote = "origin"): Origin {
79
91
  if (!/^[A-Za-z0-9_.-]{1,128}$/.test(remote) || remote.startsWith("-")) throw new ReleaseAuthorizationError("release guard requires a configured named remote");
80
92
  const urls = this.read(git, ["remote", "get-url", "--push", "--all", remote]).split("\n");
@@ -91,36 +103,111 @@ export class ReleaseAuthorizations {
91
103
  if (!SHA.test(commit)) throw new ReleaseAuthorizationError("release commit unavailable");
92
104
  return commit;
93
105
  }
94
- private version(git: ReleaseGit, commit: string): string {
106
+ private packageVersion(git: ReleaseGit, commit: string, policy?: ReleasePolicy, purpose: "authorization" | "npm" = "authorization"): string {
95
107
  if (!SHA.test(commit)) throw new ReleaseAuthorizationError("invalid release commit");
96
108
  let value: unknown;
97
- try { value = JSON.parse(this.read(git, ["show", `${commit}:package.json`])).version; } catch { throw new ReleaseAuthorizationError("committed package version unavailable"); }
98
- if (!validReleaseVersion(value)) throw new ReleaseAuthorizationError("committed package version unavailable");
109
+ try { value = JSON.parse(this.read(git, ["show", `${commit}:package.json`])).version; } catch {
110
+ if (!this.ports.policy) throw new ReleaseAuthorizationError("committed package version unavailable");
111
+ throw new ReleaseAuthorizationError(purpose === "npm"
112
+ ? "npm publish needs a committed package.json version to identify its target; add package.json with the target version"
113
+ : `committed package version unavailable; set release.version to release-notes or none in .agenthub/config.json and commit it${policy ? ` (current source: ${policy.version.source})` : ""}`);
114
+ }
115
+ if (!validReleaseVersion(value)) {
116
+ if (!this.ports.policy) throw new ReleaseAuthorizationError("committed package version unavailable");
117
+ throw new ReleaseAuthorizationError(purpose === "npm"
118
+ ? "npm publish needs a valid committed package.json version to identify its target; add package.json with the target version"
119
+ : "committed package version unavailable; set release.version to release-notes or none in .agenthub/config.json and commit it");
120
+ }
99
121
  return value;
100
122
  }
123
+ private version(git: ReleaseGit, commit: string, policy: ReleasePolicy, requested?: string): string {
124
+ if (policy.version.source === "package.json") return this.packageVersion(git, commit, policy);
125
+ if (policy.version.source === "none") {
126
+ if (!requested || !validReleaseVersion(requested)) throw new ReleaseAuthorizationError("release.version is none; provide the requested semantic version and exact candidate commit");
127
+ return requested;
128
+ }
129
+ if (!requested || !validReleaseVersion(requested)) throw new ReleaseAuthorizationError("release.version is release-notes; provide the requested semantic version and exact candidate commit");
130
+ const path = policy.version.notesPath.replace("{version}", requested);
131
+ if (!hasCommittedReleaseNotes(git, commit, path)) throw new ReleaseAuthorizationError(`committed release notes missing: ${path}; add ${path} at the candidate commit`);
132
+ return requested;
133
+ }
134
+ private docsPolicy(commit: string, policy: ReleasePolicy, version: string): Promise<ReleaseDocsReceipt | undefined> {
135
+ return policy.docs.source === "none" ? Promise.resolve({ source: "none" }) : this.docs(commit, version);
136
+ }
101
137
  async authorize(by: string, version: unknown, expectedCommit: unknown): Promise<ReleaseAuthorization> {
102
138
  this.actor(by);
103
139
  if (!validReleaseVersion(version) || typeof expectedCommit !== "string" || !SHA.test(expectedCommit)) throw new ReleaseAuthorizationError("authorization needs an exact version and candidate commit");
104
140
  this.current();
105
- const git = this.git(), commit = this.commit(git, "HEAD"), origin = this.origin(git);
106
- if (commit !== expectedCommit || this.version(git, commit) !== version) throw new ReleaseAuthorizationError("candidate commit or version differs from the person's request");
107
- const docs = await this.docs(commit, version);
141
+ const git = this.git(), commit = this.commit(git, "HEAD"), origin = this.origin(git), policy = this.policy(git, commit);
142
+ if (commit !== expectedCommit) throw new ReleaseAuthorizationError("candidate commit differs from the person's request");
143
+ const sourceVersion = this.version(git, commit, policy, version);
144
+ if (sourceVersion !== version) throw new ReleaseAuthorizationError(policy.version.source === "package.json" && this.ports.policy
145
+ ? `committed package.json version is ${sourceVersion}, not ${version}; set release.version in .agenthub/config.json to release-notes or none, or update package.json and commit it`
146
+ : "candidate version differs from the person's request for the configured source");
147
+ const docs = await this.docsPolicy(commit, policy, version);
108
148
  if (!docs) throw new ReleaseAuthorizationError("release authorization requires fresh committed documentation evidence: run `node scripts/check-docs.mjs --committed` in the candidate checkout, restamp the stale documents in a committed change, then authorize again");
109
149
  this.current(); this.actor(by);
110
- if (this.commit(git, "HEAD") !== commit || this.version(git, commit) !== version || this.origin(git).hash !== origin.hash) throw new ReleaseAuthorizationError("release candidate changed during authorization");
150
+ const currentPolicy = this.policy(git, commit);
151
+ if (this.commit(git, "HEAD") !== commit || JSON.stringify(currentPolicy) !== JSON.stringify(policy) || this.version(git, commit, currentPolicy, version) !== version || this.origin(git).hash !== origin.hash) throw new ReleaseAuthorizationError("release candidate or committed release policy changed during authorization");
111
152
  this.current(); this.actor(by);
112
153
  const receipt: ReleaseAuthorization = { schemaVersion: 1, id: randomUUID(), by, commit, version, at: (this.ports.now ?? Date.now)(), docs };
113
154
  if (!this.ports.record(structuredClone(receipt))) throw new ReleaseAuthorizationError("release approval audit could not be recorded");
114
- const entry = { receipt, origin };
155
+ const entry = { receipt, origin, policy: structuredClone(policy), order: ++this.authorizationOrder };
115
156
  this.entries.set(`${version}:${commit}`, entry); this.latest = entry;
116
157
  // ponytail: retain at most 64 approvals in this daemon generation; older candidates need a new person approval.
117
158
  if (this.entries.size > 64) this.entries.delete(this.entries.keys().next().value!);
118
159
  return structuredClone(receipt);
119
160
  }
161
+ /** Host-only report source selector. It reads no caller-selected version and never writes the ledger. */
162
+ reportPolicy(head: string, repo: string): ReleaseReportPolicy | undefined {
163
+ const unavailable = (versionSource: ReleaseReportPolicy["versionSource"] = "unknown", docsSource: ReleaseReportPolicy["docsSource"] = "unknown"): ReleaseReportPolicy => ({ versionSource, docsSource, authorization: "unavailable" });
164
+ if (!SHA.test(head) || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) return unavailable();
165
+ const git = this.git();
166
+ let policy: ReleasePolicy;
167
+ try { policy = this.policy(git, head); } catch { return unavailable(); }
168
+ if (policy.version.source === "package.json" && policy.docs.source === "checker") return;
169
+ let packageVersion: string | undefined;
170
+ if (policy.version.source === "package.json") {
171
+ try { packageVersion = this.packageVersion(git, head, policy); } catch { return unavailable(policy.version.source, policy.docs.source); }
172
+ }
173
+ let origin: Origin;
174
+ try {
175
+ if (this.commit(git, "HEAD") !== head) return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "stale", ...(packageVersion ? { version: packageVersion } : {}) };
176
+ origin = this.origin(git);
177
+ } catch { return unavailable(policy.version.source, policy.docs.source); }
178
+ const candidates = [...this.entries.values()].filter(entry => entry.receipt.commit === head
179
+ && entry.origin.hash === origin.hash && entry.origin.repo?.toLowerCase() === repo.toLowerCase()
180
+ && JSON.stringify(entry.policy) === JSON.stringify(policy)
181
+ && (packageVersion === undefined || entry.receipt.version === packageVersion));
182
+ const entry = candidates.reduce<Entry | undefined>((latest, current) => !latest || current.order > latest.order ? current : latest, undefined);
183
+ if (!entry) return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "missing", ...(packageVersion ? { version: packageVersion } : {}) };
184
+ const version = policy.version.source === "package.json" ? packageVersion : entry.receipt.version;
185
+ if (!version || !validReleaseVersion(version) || entry.receipt.version !== version) return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "stale" };
186
+ if (policy.version.source === "release-notes") {
187
+ const notes = policy.version.notesPath.replace("{version}", version);
188
+ if (!hasCommittedReleaseNotes(git, head, notes)) return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "stale" };
189
+ }
190
+ if (policy.docs.source === "none" ? !("source" in entry.receipt.docs) : !("digest" in entry.receipt.docs)) {
191
+ return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "stale" };
192
+ }
193
+ try {
194
+ if (this.commit(git, "HEAD") !== head || this.origin(git).hash !== origin.hash) return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "stale" };
195
+ } catch { return unavailable(policy.version.source, policy.docs.source); }
196
+ return { versionSource: policy.version.source, docsSource: policy.docs.source, authorization: "matched", version };
197
+ }
120
198
  private matched(git: ReleaseGit, version: string, commit: string, remote?: string, url?: string): ReleaseAuthorization {
121
199
  this.current();
122
200
  const entry = this.entries.get(`${version}:${commit}`);
123
- if (!entry || this.version(git, commit) !== version) throw new ReleaseAuthorizationError("no matching person release authorization; ask the person to authorize this commit and version");
201
+ if (!entry) throw new ReleaseAuthorizationError("no matching person release authorization; ask the person to authorize this commit and version");
202
+ const policy = this.policy(git, commit);
203
+ if (JSON.stringify(policy) !== JSON.stringify(entry.policy)) throw new ReleaseAuthorizationError("committed release policy differs from the authorized candidate");
204
+ const candidateVersion = this.version(git, commit, policy, version);
205
+ if (candidateVersion !== version) {
206
+ if (!this.ports.policy) throw new ReleaseAuthorizationError("no matching person release authorization; ask the person to authorize this commit and version");
207
+ throw new ReleaseAuthorizationError(policy.version.source === "package.json"
208
+ ? `committed package.json version is ${candidateVersion}, not ${version}; update package.json and commit the requested release version`
209
+ : `committed ${policy.version.source} source identifies ${candidateVersion}, not ${version}; update the committed release source`);
210
+ }
124
211
  const origin = this.origin(git);
125
212
  if (origin.hash !== entry.origin.hash || remote && this.origin(git, remote).hash !== origin.hash || url !== undefined && !origin.urls.includes(url)) throw new ReleaseAuthorizationError("release remote differs from the authorized project");
126
213
  return structuredClone(entry.receipt);
@@ -134,11 +221,13 @@ export class ReleaseAuthorizations {
134
221
  }
135
222
  if (request.kind === "npm-publish") {
136
223
  if (!releaseTrackedClean(this.root, git)) throw new ReleaseAuthorizationError("npm publish requires a clean tracked worktree");
137
- const commit = this.commit(git, "HEAD"), version = this.version(git, commit);
224
+ const commit = this.commit(git, "HEAD"), version = this.packageVersion(git, commit, undefined, "npm");
138
225
  const receipt = this.matched(git, version, commit);
139
- const docs = await this.docs(commit, version);
226
+ const policy = this.policy(git, commit), docs = await this.docsPolicy(commit, policy, version);
140
227
  this.current();
141
- if (!docs || docs.digest !== receipt.docs.digest || this.commit(git, "HEAD") !== commit || !releaseTrackedClean(this.root, git)) throw new ReleaseAuthorizationError("publish checkout or documentation evidence changed");
228
+ const docsMatch = !!docs && ("source" in docs ? "source" in receipt.docs && receipt.docs.source === "none"
229
+ : "digest" in receipt.docs && docs.digest === receipt.docs.digest);
230
+ if (!docsMatch || this.commit(git, "HEAD") !== commit || JSON.stringify(this.policy(git, commit)) !== JSON.stringify(policy) || !releaseTrackedClean(this.root, git)) throw new ReleaseAuthorizationError("publish checkout, release policy or documentation evidence changed");
142
231
  return { ok: true, receipts: [this.matched(git, version, commit)] };
143
232
  }
144
233
  const origin = this.origin(git), repo = origin.repo;
@@ -177,10 +266,43 @@ export class ReleaseAuthorizations {
177
266
  } catch (error) { return { ok: false, error: releaseAuthorizationError(error) }; }
178
267
  }
179
268
  report<T extends ReleaseReadiness>(report: T): T & { authorization?: { state: "matched" | "stale"; receipt: ReleaseAuthorization } } {
269
+ if (report.releasePolicy) {
270
+ const policy = report.releasePolicy;
271
+ if (policy.authorization !== "matched" || !report.head || !report.version) return report;
272
+ let current: ReleaseReportPolicy | undefined;
273
+ try { current = this.reportPolicy(report.head, report.repo); }
274
+ catch { current = { versionSource: policy.versionSource, docsSource: policy.docsSource, authorization: "unavailable" }; }
275
+ const entry = this.entries.get(`${report.version}:${report.head}`);
276
+ let matched = !!entry && current?.authorization === "matched" && current.version === report.version
277
+ && current.versionSource === policy.versionSource && current.docsSource === policy.docsSource;
278
+ try {
279
+ if (matched) {
280
+ const git = this.git(), candidatePolicy = this.policy(git, entry!.receipt.commit);
281
+ const verdict = report.documents ? docsVerdict(report.documents, report.head, report.version) : undefined;
282
+ matched = JSON.stringify(candidatePolicy) === JSON.stringify(entry!.policy)
283
+ && ("source" in entry!.receipt.docs ? candidatePolicy.docs.source === "none" : !!verdict && verdict.digest === entry!.receipt.docs.digest)
284
+ && this.origin(git).hash === entry!.origin.hash;
285
+ }
286
+ } catch { matched = false; }
287
+ const releasePolicy = { ...policy, authorization: matched ? "matched" as const : "stale" as const };
288
+ if (!matched) return { ...report, releasePolicy, sourceReady: false, ready: false,
289
+ blockers: [...new Set([...report.blockers, "release authorization source is stale; authorize the exact candidate version again"])],
290
+ ...(entry ? { authorization: { state: "stale" as const, receipt: structuredClone(entry.receipt) } } : {}) };
291
+ const blockers = report.blockers.map(item => item === "native acceptance and person release decision unverified" ? "native acceptance unverified" : item);
292
+ return { ...report, releasePolicy, blockers, authorization: { state: "matched", receipt: structuredClone(entry!.receipt) } };
293
+ }
180
294
  if (!this.latest) return report;
181
295
  const entry = this.entries.get(`${report.version}:${report.head}`), verdict = report.head && report.version ? docsVerdict(report.documents, report.head, report.version) : undefined;
182
- let matched = !!entry && !!entry.origin.repo && entry.origin.repo.toLowerCase() === report.repo.toLowerCase() && !!verdict && verdict.digest === entry.receipt.docs.digest;
183
- try { matched &&= this.origin(this.git()).hash === entry!.origin.hash; } catch { matched = false; }
296
+ let matched = !!entry && !!entry.origin.repo && entry.origin.repo.toLowerCase() === report.repo.toLowerCase();
297
+ try {
298
+ if (matched) {
299
+ const git = this.git(), policy = this.policy(git, entry!.receipt.commit);
300
+ matched = JSON.stringify(policy) === JSON.stringify(entry!.policy)
301
+ && this.version(git, entry!.receipt.commit, policy, report.version) === report.version
302
+ && ("source" in entry!.receipt.docs ? policy.docs.source === "none" : !!verdict && verdict.digest === entry!.receipt.docs.digest)
303
+ && this.origin(git).hash === entry!.origin.hash;
304
+ }
305
+ } catch { matched = false; }
184
306
  const receipt = structuredClone((matched ? entry! : this.latest).receipt);
185
307
  const blockers = matched ? report.blockers.map(item => item === "native acceptance and person release decision unverified" ? "native acceptance unverified" : item) : report.blockers;
186
308
  return { ...report, blockers, authorization: { state: matched ? "matched" : "stale", receipt } };
@@ -0,0 +1,100 @@
1
+ import type { ReleaseGit } from "./sdlc-release.ts";
2
+
3
+ export type ReleaseVersionPolicy =
4
+ | { source: "package.json" }
5
+ | { source: "release-notes"; notesPath: string }
6
+ | { source: "none" };
7
+ export type ReleaseDocsPolicy = { source: "checker" } | { source: "none" };
8
+ export interface ReleasePolicy { version: ReleaseVersionPolicy; docs: ReleaseDocsPolicy }
9
+
10
+ export const DEFAULT_RELEASE_POLICY: ReleasePolicy = {
11
+ version: { source: "package.json" },
12
+ docs: { source: "checker" },
13
+ };
14
+ export const DEFAULT_RELEASE_NOTES_PATH = "docs/releases/v{version}.md";
15
+
16
+ const record = (value: unknown): Record<string, unknown> | undefined =>
17
+ !!value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
18
+
19
+ function checkedNotesPath(value: unknown): string {
20
+ if (typeof value !== "string" || value.length > 1024 || !value.includes("{version}")
21
+ || (value.match(/\{version\}/g)?.length ?? 0) !== 1 || /[\p{Cc}\\:*?\[\]]/u.test(value)
22
+ || value.startsWith("/") || value.startsWith("-") || /^[A-Za-z]:/.test(value)
23
+ || value.split("/").some(part => !part || part === "." || part === ".." || part.startsWith("-"))) {
24
+ throw new Error("release.notesPath must be a safe repository-relative path with exactly one {version} placeholder");
25
+ }
26
+ return value;
27
+ }
28
+
29
+ /** Parse only the release contract; unrelated project configuration is deliberately outside this policy reader. */
30
+ export function parseReleasePolicy(config: unknown): ReleasePolicy {
31
+ const root = record(config);
32
+ if (!root) throw new Error("committed .agenthub/config.json must be a JSON object");
33
+ if (root.release === undefined) return DEFAULT_RELEASE_POLICY;
34
+ const release = record(root.release);
35
+ if (!release || Object.keys(release).some(key => !["version", "notesPath", "docs"].includes(key))) {
36
+ throw new Error("committed release config must contain only version, notesPath and docs");
37
+ }
38
+ const rawVersion = release.version === undefined ? "package.json" : release.version;
39
+ if (rawVersion !== "package.json" && rawVersion !== "release-notes" && rawVersion !== "none") {
40
+ throw new Error("release.version in committed .agenthub/config.json must be package.json, release-notes or none");
41
+ }
42
+ const rawDocs = release.docs === undefined ? "checker" : release.docs;
43
+ if (rawDocs !== "checker" && rawDocs !== "none") throw new Error("release.docs in committed .agenthub/config.json must be checker or none");
44
+ const notesPath = checkedNotesPath(release.notesPath === undefined ? DEFAULT_RELEASE_NOTES_PATH : release.notesPath);
45
+ return {
46
+ version: rawVersion === "release-notes" ? { source: rawVersion, notesPath }
47
+ : rawVersion === "none" ? { source: rawVersion } : { source: rawVersion },
48
+ docs: rawDocs === "none" ? { source: rawDocs } : { source: rawDocs },
49
+ };
50
+ }
51
+
52
+ interface TreeEntry { mode: string; type: string; oid: string; path: string }
53
+ function treeEntry(git: ReleaseGit, commit: string, path: string): TreeEntry | undefined {
54
+ const result = git(["--literal-pathspecs", "ls-tree", "-z", "--full-tree", commit, "--", path]);
55
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 16 * 1024) throw new Error("committed release policy tree is unreadable");
56
+ const rows = result.stdout.split("\0").filter(Boolean);
57
+ if (rows.length > 1) throw new Error("committed release policy path is ambiguous");
58
+ if (!rows.length) return undefined;
59
+ const match = rows[0]!.match(/^(\d{6}) (blob|tree|commit) ([0-9a-f]{40})\t([^\0]+)$/);
60
+ if (!match || match[4] !== path) throw new Error("committed release policy tree is malformed");
61
+ return { mode: match[1]!, type: match[2]!, oid: match[3]!, path: match[4]! };
62
+ }
63
+
64
+ function regularBlob(git: ReleaseGit, commit: string, path: string): boolean {
65
+ const parts = path.split("/");
66
+ for (let index = 1; index < parts.length; index++) {
67
+ const parent = parts.slice(0, index).join("/");
68
+ const entry = treeEntry(git, commit, parent);
69
+ if (!entry || entry.mode !== "040000" || entry.type !== "tree") return false;
70
+ }
71
+ const file = treeEntry(git, commit, path);
72
+ return !!file && (file.mode === "100644" || file.mode === "100755") && file.type === "blob";
73
+ }
74
+
75
+ /** Read policy only from the candidate commit. Missing shared config means the legacy defaults; unreadable data fails closed. */
76
+ export function readCommittedReleasePolicy(git: ReleaseGit, commit: string): ReleasePolicy {
77
+ const agentHub = treeEntry(git, commit, ".agenthub");
78
+ if (!agentHub) return DEFAULT_RELEASE_POLICY;
79
+ if (agentHub.mode !== "040000" || agentHub.type !== "tree") throw new Error("committed .agenthub is not a regular directory");
80
+ const path = ".agenthub/config.json";
81
+ const configEntry = treeEntry(git, commit, path);
82
+ if (!configEntry) return DEFAULT_RELEASE_POLICY;
83
+ if ((configEntry.mode !== "100644" && configEntry.mode !== "100755") || configEntry.type !== "blob") {
84
+ throw new Error("committed .agenthub/config.json is not a regular file");
85
+ }
86
+ const result = git(["show", `${commit}:${path}`]);
87
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 256 * 1024) throw new Error("committed .agenthub/config.json is unreadable");
88
+ let parsed: unknown;
89
+ try { parsed = JSON.parse(result.stdout); } catch { throw new Error("committed .agenthub/config.json is malformed JSON"); }
90
+ const policy = parseReleasePolicy(parsed);
91
+ if (policy.docs.source === "none" && regularBlob(git, commit, "docs/verified.json")) {
92
+ throw new Error("release.docs is none but the candidate commits docs/verified.json; remove release.docs from .agenthub/config.json or delete the manifest, then authorize again");
93
+ }
94
+ return policy;
95
+ }
96
+
97
+ /** Ensure every directory component and the final notes path are committed as non-symlink tree/blob entries. */
98
+ export function hasCommittedReleaseNotes(git: ReleaseGit, commit: string, path: string): boolean {
99
+ try { return regularBlob(git, commit, path); } catch { return false; }
100
+ }
@@ -22,9 +22,18 @@ const sdlcGh: SdlcGh = async (...args) => {
22
22
  catch { return { code: 1, stdout: "" }; }
23
23
  };
24
24
  export interface DocEvidence { schemaVersion: 1; head?: string; version?: string; documents: { path?: string; state: "fresh" | "stale" | "nonancestor" | "unknown"; verifiedAgainst?: string; commits?: number; dirty?: boolean }[]; errors: number; fresh: boolean; }
25
- export interface ReleaseReadiness { /** #481 AC12: interval, approval-to-release lead time and hotfix rate over shipped releases, filled by Tasks.releaseReadiness. */ releaseMetrics?: ReturnType<typeof releaseMetrics>; repo: string; head?: string; version?: string; tag?: string; tagCommit?: string; commits: string[]; mergedPrs: { pr: number; commit: string }[]; documents?: DocEvidence; liveIssues: { id: number; state: "open" | "closed" | "unknown" }[]; blockers: string[]; sourceReady: boolean; native: "unverified"; ready: false; }
25
+ export type ReleaseReportSource = "package.json" | "release-notes" | "none" | "unknown";
26
+ export type ReleaseReportDocsSource = "checker" | "none" | "unknown";
27
+ export type ReleaseReportAuthorizationState = "matched" | "missing" | "stale" | "unavailable";
28
+ export interface ReleaseReportPolicy {
29
+ versionSource: ReleaseReportSource;
30
+ docsSource: ReleaseReportDocsSource;
31
+ authorization: ReleaseReportAuthorizationState;
32
+ version?: string;
33
+ }
34
+ export interface ReleaseReadiness { /** #481 AC12: interval, approval-to-release lead time and hotfix rate over shipped releases, filled by Tasks.releaseReadiness. */ releaseMetrics?: ReturnType<typeof releaseMetrics>; releasePolicy?: ReleaseReportPolicy; repo: string; head?: string; version?: string; tag?: string; tagCommit?: string; commits: string[]; mergedPrs: { pr: number; commit: string }[]; documents?: DocEvidence; liveIssues: { id: number; state: "open" | "closed" | "unknown" }[]; blockers: string[]; sourceReady: boolean; native: "unverified"; ready: false; }
26
35
  export type ReleaseGit = (args: string[]) => { code: number; stdout: string };
27
- export interface ReleaseReaders { gh?: SdlcGh; git?: ReleaseGit; docs?: (root: string, timeoutMs: number) => Promise<DocEvidence | undefined>; /** Test seam (#1120): the checker program the default docs reader spawns. */ checker?: string; }
36
+ export interface ReleaseReaders { gh?: SdlcGh; git?: ReleaseGit; docs?: (root: string, timeoutMs: number) => Promise<DocEvidence | undefined>; /** Host-only selected authorization/config metadata; absent preserves standalone package.json behavior. */ reportPolicy?: (head: string, repo: string) => ReleaseReportPolicy | undefined; /** Test seam (#1120): the checker program the default docs reader spawns. */ checker?: string; }
28
37
  const SHA = /^[0-9a-f]{40}$/;
29
38
  const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
30
39
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
@@ -72,7 +81,34 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
72
81
  const git: ReleaseGit = readers.git ?? (args => { const r = hubGitSync(args, { cwd: root, encoding: "utf8", timeout: Math.max(1, Math.min(1000, deadline - performance.now())), maxBuffer: 256 * 1024 }); return { code: r.status ?? 1, stdout: r.stdout ?? "" }; });
73
82
  const first = git(["rev-parse","--verify","HEAD"]); const head = first.stdout.trim();
74
83
  if (first.code !== 0 || !SHA.test(head)) { report.blockers.push("local HEAD unknown"); return report; } report.head = head;
75
- try { const r = git(["show",`${head}:package.json`]), pkg = JSON.parse(r.stdout); if (r.code === 0 && typeof pkg.version === "string" && VERSION.test(pkg.version)) report.version = pkg.version; else report.blockers.push("package version unknown"); } catch { report.blockers.push("package version unknown"); }
84
+ let releasePolicy: ReleaseReportPolicy | undefined;
85
+ if (readers.reportPolicy) {
86
+ try { releasePolicy = readers.reportPolicy(head, repo); } catch { releasePolicy = { versionSource: "unknown", docsSource: "unknown", authorization: "unavailable" }; }
87
+ if (releasePolicy) {
88
+ report.releasePolicy = { versionSource: releasePolicy.versionSource, docsSource: releasePolicy.docsSource, authorization: releasePolicy.authorization };
89
+ if (releasePolicy.versionSource === "package.json") {
90
+ try { const r = git(["show",`${head}:package.json`]), pkg = JSON.parse(r.stdout); if (r.code === 0 && typeof pkg.version === "string" && VERSION.test(pkg.version)) report.version = pkg.version; else report.blockers.push("package version unknown"); } catch { report.blockers.push("package version unknown"); }
91
+ if (releasePolicy.authorization === "unavailable") report.blockers.push("committed release policy unavailable; commit a valid release policy and authorize the candidate");
92
+ else if (releasePolicy.authorization === "stale") report.blockers.push("release authorization source is stale; authorize the exact candidate version again");
93
+ else if (releasePolicy.authorization === "missing") report.blockers.push("release authorization not recorded for the committed package.json version; run ahub sdlc authorize-release <version>");
94
+ } else if (releasePolicy.authorization === "matched" && typeof releasePolicy.version === "string" && VERSION.test(releasePolicy.version)) {
95
+ report.version = releasePolicy.version;
96
+ } else if (releasePolicy.authorization === "unavailable" || releasePolicy.versionSource === "unknown") {
97
+ report.blockers.push("committed release policy unavailable; commit a valid release policy and authorize the candidate");
98
+ } else if (releasePolicy.authorization === "stale") {
99
+ report.blockers.push(releasePolicy.versionSource === "release-notes"
100
+ ? "release-notes source is stale; commit the configured notes file and authorize the exact version"
101
+ : "release authorization source is stale; authorize the exact candidate version again");
102
+ } else {
103
+ report.blockers.push(`release version undetermined from configured ${releasePolicy.versionSource} source; run ahub sdlc authorize-release <version>`);
104
+ }
105
+ } else {
106
+ // The committed package.json/checker default keeps its existing report shape.
107
+ try { const r = git(["show",`${head}:package.json`]), pkg = JSON.parse(r.stdout); if (r.code === 0 && typeof pkg.version === "string" && VERSION.test(pkg.version)) report.version = pkg.version; else report.blockers.push("package version unknown"); } catch { report.blockers.push("package version unknown"); }
108
+ }
109
+ } else {
110
+ try { const r = git(["show",`${head}:package.json`]), pkg = JSON.parse(r.stdout); if (r.code === 0 && typeof pkg.version === "string" && VERSION.test(pkg.version)) report.version = pkg.version; else report.blockers.push("package version unknown"); } catch { report.blockers.push("package version unknown"); }
111
+ }
76
112
  const published = await gh(["release","list","--repo",repo,"--exclude-drafts","--order","desc","--limit","1","--json","tagName,isDraft,isPrerelease"]);
77
113
  let tag: string | undefined;
78
114
  try { const rows = JSON.parse(published.stdout), p = Array.isArray(rows) && rows.length === 1 ? rows[0] : undefined; if (published.code === 0 && p && typeof p.tagName === "string" && p.tagName.startsWith("v") && VERSION.test(p.tagName.slice(1)) && p.isDraft === false && typeof p.isPrerelease === "boolean") tag = p.tagName; } catch { /* unknown metadata */ }
@@ -91,7 +127,8 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
91
127
  if (work.code !== 0 || commits.length > 1000 || commits.some(c => !SHA.test(c))) report.blockers.push("merged work coverage unknown or truncated"); else report.commits = commits;
92
128
  let advanced = false;
93
129
  try { advanced = !!report.version && Bun.semver.order(report.version, tag.slice(1)) > 0; } catch { /* invalid version remains blocked */ }
94
- if (!advanced) report.blockers.push("package version has not advanced past published release");
130
+ if (!advanced && (!report.releasePolicy || report.releasePolicy.versionSource === "package.json")) report.blockers.push("package version has not advanced past published release");
131
+ else if (!advanced && report.version) report.blockers.push("release version has not advanced past published release");
95
132
  }
96
133
  }
97
134
  if (report.tagCommit) {
@@ -112,10 +149,13 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
112
149
  } catch { report.blockers.push("merged PR coverage unknown or truncated"); break; }
113
150
  }
114
151
  }
115
- const left = deadline - performance.now(); report.documents = left > 0 ? await (readers.docs ?? ((dir, ms) => readDocEvidenceDetailed(dir, ms, readers.checker).then(read => "evidence" in read ? read.evidence : undefined)))(root,Math.min(10_000,left)) : undefined;
116
- const checkerMissing = !readers.docs && !existsSync(readers.checker ?? CHECKER_PATH); // #1120: a hub without the checker says so instead of calling the documents stale
152
+ const skipDocs = report.releasePolicy?.docsSource === "none" || report.releasePolicy?.authorization === "unavailable"
153
+ || !!report.releasePolicy && report.releasePolicy.versionSource !== "package.json" && report.releasePolicy.authorization !== "matched";
154
+ const left = deadline - performance.now();
155
+ report.documents = !skipDocs && left > 0 ? await (readers.docs ?? ((dir, ms) => readDocEvidenceDetailed(dir, ms, readers.checker).then(read => "evidence" in read ? read.evidence : undefined)))(root,Math.min(10_000,left)) : undefined;
156
+ const checkerMissing = !skipDocs && !readers.docs && !existsSync(readers.checker ?? CHECKER_PATH); // #1120: a hub without the checker says so instead of calling the documents stale
117
157
  if (checkerMissing) report.blockers.push("documentation checker unavailable in the running hub: " + CHECKER_MISSING);
118
- else if (!report.documents || report.documents.head !== head || !report.documents.fresh || report.documents.errors || report.documents.documents.some(d => d.state !== "fresh")) report.blockers.push("documentation freshness or ancestry is unknown or stale");
158
+ else if (!skipDocs && (!report.documents || report.documents.head !== head || !report.documents.fresh || report.documents.errors || report.documents.documents.some(d => d.state !== "fresh"))) report.blockers.push("documentation freshness or ancestry is unknown or stale");
119
159
  if (!liveIssues.length) report.blockers.push("native verification ledger unspecified");
120
160
  for (const id of liveIssues) {
121
161
  const reply = await gh(["issue","view",String(id),"--repo",repo,"--json","number,state"]); let state: "open"|"closed"|"unknown" = "unknown";
@@ -148,6 +188,18 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
148
188
  if (!issuesStable) report.blockers.push("live issue states changed or could not be reverified");
149
189
  }
150
190
  const last = git(["rev-parse","--verify","HEAD"]); if (last.code !== 0 || last.stdout.trim() !== head) report.blockers.push("local HEAD changed during release readback");
191
+ if (report.releasePolicy?.authorization === "matched" && readers.reportPolicy) {
192
+ let current: ReleaseReportPolicy | undefined;
193
+ try { current = readers.reportPolicy(head, repo); } catch { /* a report recheck failure is stale authorization */ }
194
+ const prior = report.releasePolicy;
195
+ if (!current || current.authorization !== "matched" || current.versionSource !== prior.versionSource
196
+ || current.docsSource !== prior.docsSource || current.version !== report.version) {
197
+ report.releasePolicy = { ...prior, authorization: "stale" };
198
+ if (prior.versionSource !== "package.json") report.version = undefined;
199
+ report.sourceReady = false;
200
+ report.blockers.push("release authorization source changed during release readback; authorize the exact candidate version again");
201
+ }
202
+ }
151
203
  report.blockers = [...new Set(report.blockers)]; report.sourceReady = report.blockers.length === 0;
152
204
  // Closed issue metadata is not a native receipt or permission to publish.
153
205
  report.blockers.push("native acceptance and person release decision unverified");
@@ -254,7 +306,7 @@ export function releaseMetrics(releases: Release[], tasks: Task[]) {
254
306
  const scope = train.scope ?? [...train.history].reverse().find(row => row.event === "cut")?.scope;
255
307
  if (!scope) { unknown.add(release.id); continue; }
256
308
  for (const id of scope) {
257
- const task = byTask.get(id), approved = task?.history.findLast(row => row.at <= event.at && (row.event === "approved" || row.event === "done" && task.state === "approved" && task.reviewer === null))?.at ?? null;
309
+ const task = byTask.get(id), approved = task?.history.findLast(row => row.at <= event.at && (row.event === "approved" || row.event === "merged outside the hub" || row.event === "done" && task.state === "approved" && task.reviewer === null))?.at ?? null;
258
310
  const ms = approved !== null && approved <= event.at ? event.at - approved : null;
259
311
  if (ms === null) unknown.add(release.id);
260
312
  approvalToReleaseMs.push({ release: release.id, task: id, ms });
package/src/hub/sdlc.ts CHANGED
@@ -350,6 +350,30 @@ export function parsePrEvidence(value: unknown): PrEvidence {
350
350
  /** Issue identity and edit times only; no body is fetched or stored. `lastEditedAt` moves on a body edit, not on comments. */
351
351
  export interface SpecEdit { lastEditedAt: string | null; updatedAt: string }
352
352
  export interface SpecAcceptance extends SpecEdit { repo: string; issue: number; acceptedAt: number }
353
+ /** Consent references are complete local task tokens, never numbers extracted from prose. */
354
+ export function localSupersedingTask(value: unknown): number | undefined {
355
+ if (typeof value !== "string") return undefined;
356
+ const match = /^(?:task #|#)?([1-9][0-9]*)$/.exec(value);
357
+ const task = match?.[0] === value ? Number(match[1]) : NaN;
358
+ return Number.isSafeInteger(task) ? task : undefined;
359
+ }
360
+
361
+ /** Validate host-stored consent without importing any other source receipt fields. */
362
+ export function storedSpecAcceptance(value: unknown): SpecAcceptance | undefined {
363
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
364
+ const record = value as Record<string, unknown>;
365
+ const stamp = (v: unknown): v is string => typeof v === "string" && v.length <= 40 && !Number.isNaN(Date.parse(v));
366
+ if (!repo(record.repo) || !id(record.issue) || !stamp(record.updatedAt) || record.lastEditedAt !== null && !stamp(record.lastEditedAt)
367
+ || typeof record.acceptedAt !== "number" || !Number.isFinite(record.acceptedAt)) return undefined;
368
+ return { repo: record.repo, issue: record.issue, updatedAt: record.updatedAt, lastEditedAt: record.lastEditedAt as string | null, acceptedAt: record.acceptedAt };
369
+ }
370
+
371
+ /** Only a host observation of the same issue/body permits copying existing person consent. */
372
+ export function carriedSpecAcceptance(source: SpecAcceptance, destination: { repo: string; issue: number }, edit: SpecEdit | undefined): SpecAcceptance | undefined {
373
+ if (!edit || source.repo.toLowerCase() !== destination.repo.toLowerCase() || source.issue !== destination.issue || source.lastEditedAt !== edit.lastEditedAt) return undefined;
374
+ return { repo: destination.repo, issue: destination.issue, lastEditedAt: source.lastEditedAt, updatedAt: source.updatedAt, acceptedAt: source.acceptedAt };
375
+ }
376
+
353
377
  export type SpecState = "missing" | "current" | "changed" | "unknown";
354
378
  /** Whether the receipt's spec issue is accepted at its current body. `edit` undefined means the readback failed. */
355
379
  export function specState(receipt: SdlcReceipt | undefined, edit: SpecEdit | undefined): SpecState {
@@ -546,16 +570,34 @@ export async function readPlanIssueMetadata(repository: string, number: number,
546
570
  } catch { return undefined; }
547
571
  }
548
572
 
573
+ /** The native CI floor belongs only to this repository; other projects must name their own checks. */
574
+ export function requiredCheckNames(repository: string | undefined, required: readonly string[]): string[] {
575
+ return required.length ? [...new Set(required)] : repository?.toLowerCase() === "staixbwlb/agent-hub" ? ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"] : [];
576
+ }
577
+
578
+ /** Names each non-green required check. Incomplete inventories cannot prove either presence or success. */
579
+ export function requiredCiBlocker(required: readonly string[], checks: PrEvidence["checks"], complete = true): string | undefined {
580
+ const problems = required.flatMap(name => {
581
+ const matches = checks.filter(check => check.name === name);
582
+ const state = !complete ? "unknown" : !matches.length ? "missing" : matches.some(check => check.state === "failed") ? "failed"
583
+ : matches.some(check => check.state === "pending") ? "pending" : matches.length !== 1 ? "duplicate" : matches[0]!.state !== "passed" ? "unknown" : undefined;
584
+ return state ? [`${state} ${name}`] : [];
585
+ });
586
+ return problems.length ? `exact-head full CI is not green: ${problems.join("; ")}` : undefined;
587
+ }
588
+
549
589
  /** A complete resolved-thread snapshot already proves there is no pending unanswered bot thread. */
550
- export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[]): ReviewReadiness | undefined {
590
+ export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[], repository?: string): ReviewReadiness | undefined {
551
591
  if (!evidence || evidence.unresolved !== 0) return undefined;
552
- const checks = required.length ? [...required] : ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
592
+ const checks = requiredCheckNames(repository, required);
593
+ if (!checks.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks };
553
594
  if (!checks.every(name => evidence.checks.some(check => check.name === name)) || evidence.checks.some(check => check.state === "unknown")) return undefined;
554
595
  const blockers: string[] = [];
555
596
  if (!expected || !sha(expected)) blockers.push("review head missing");
556
597
  else if (evidence.head !== expected) blockers.push("review head changed");
557
598
  if (evidence.state !== "OPEN") blockers.push("review PR is not open");
558
- if (!checks.every(name => { const matched = evidence.checks.filter(check => check.name === name); return matched.length === 1 && matched[0]?.state === "passed"; })) blockers.push("exact-head full CI is not green");
599
+ const ciBlocker = requiredCiBlocker(checks, evidence.checks);
600
+ if (ciBlocker) blockers.push(ciBlocker);
559
601
  return { head: evidence.head, ready: blockers.length === 0, blockers, checks };
560
602
  }
561
603
 
@@ -565,6 +607,8 @@ export interface ReviewReadiness { head?: string; ready: boolean; blockers: stri
565
607
  export async function readReviewReadiness(receipt: SdlcReceipt, expected: string | undefined, run: SdlcGh = sdlcGh, requiredChecks: readonly string[] = []): Promise<ReviewReadiness> {
566
608
  const unknown = (): ReviewReadiness => ({ ready: false, blockers: ["review readiness unavailable"] });
567
609
  if (!repo(receipt.repo) || !id(receipt.pr)) return unknown();
610
+ const full = requiredCheckNames(receipt.repo, requiredChecks);
611
+ if (!full.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks: full };
568
612
  const [owner, name] = receipt.repo.split("/");
569
613
  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} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
570
614
  try {
@@ -585,14 +629,21 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
585
629
  if (!commit || commit.oid !== pr.headRefOid) blockers.push("review head changed");
586
630
  const contexts = commit?.statusCheckRollup?.contexts;
587
631
  const nodes: unknown[] | undefined = contexts?.nodes;
588
- const full = requiredChecks.length ? [...requiredChecks] : ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
589
632
  let reusedRun: number | undefined;
590
- if (contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(nodes) || nodes.length > 100
591
- || !full.every(name => {
592
- const matches = (nodes as { name?: string; context?: string; status?: string; conclusion?: string; state?: string }[]).filter(node => (node?.name ?? node?.context) === name);
593
- return matches.length === 1 && (matches[0]?.name ? matches[0].status === "COMPLETED" && matches[0].conclusion === "SUCCESS" : matches[0]?.state === "SUCCESS");
594
- })) blockers.push("exact-head full CI is not green");
595
- if (blockers.includes("exact-head full CI is not green") && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
633
+ const completeChecks = !(contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(nodes) || nodes.length > 100);
634
+ const requiredNodes = completeChecks ? nodes!.filter(node => {
635
+ const raw = node as { name?: unknown; context?: unknown } | null | undefined;
636
+ return full.some(name => (raw?.name ?? raw?.context) === name);
637
+ }) : [];
638
+ const checkEvidence = completeChecks ? parsePrEvidence({ headRefOid: pr.headRefOid, state: pr.state, files: [], statusCheckRollup: requiredNodes }).checks.map((check, index) => {
639
+ const raw = requiredNodes[index] as { name?: unknown; status?: unknown; conclusion?: unknown; state?: unknown } | undefined;
640
+ // Fresh GraphQL admission keeps its original success proof, even when common normalization accepts a legacy shape.
641
+ const success = raw?.name ? raw.status === "COMPLETED" && raw.conclusion === "SUCCESS" : raw?.state === "SUCCESS";
642
+ return check.state === "passed" && !success ? { ...check, state: "unknown" as const } : check;
643
+ }) : [];
644
+ const ciBlocker = requiredCiBlocker(full, checkEvidence, completeChecks);
645
+ if (ciBlocker) blockers.push(ciBlocker);
646
+ if (ciBlocker && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
596
647
  && 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)) {
597
648
  reusedRun = await identicalTreeGate(receipt.repo, commit.tree.oid, bounded, full);
598
649
  if (reusedRun !== undefined) {
@@ -600,7 +651,7 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
600
651
  const after = await bounded(args, 10_000, undefined, 512 * 1024);
601
652
  try { if (after.code !== 0 || JSON.stringify(JSON.parse(after.stdout)?.data?.repository?.pullRequest) !== JSON.stringify(pr)) reusedRun = undefined; }
602
653
  catch { reusedRun = undefined; }
603
- if (reusedRun !== undefined) blockers.splice(blockers.indexOf("exact-head full CI is not green"), 1);
654
+ if (reusedRun !== undefined) blockers.splice(blockers.indexOf(ciBlocker!), 1);
604
655
  }
605
656
  }
606
657
  const threads = pr.reviewThreads;
@@ -64,6 +64,8 @@ export const SETTINGS: readonly SettingDef[] = [
64
64
  { key: "tasks.escalate_after", group: "Routing", label: "Escalate after N consecutive changes_requested", type: "integer", min: 1, max: 10, store: "config", applies: "live", risk: "raises", path: ["tasks", "escalate_after"] },
65
65
  ...OPERATIONAL_NUMBERS.map(({ defaultValue, unit, inventory, ...def }): SettingDef => def),
66
66
  { 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"] },
67
+ // #1221 T2: off evaluates nothing, shadow stores bounded proposals with no inbox row or notice, advisory may also show one in the inbox.
68
+ { 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"] },
67
69
  { 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"] },
68
70
  { 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"] },
69
71
  { key: "planner", group: "Roles", label: "Planners (task-local selection)", type: "peers", values: PLANNER_PEERS, store: "config", applies: "live", risk: "raises", path: ["planner"] },