@staix/agent-hub 0.34.1 → 0.36.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 (213) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +53 -7
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/addons/claude-mem.md +4 -4
  5. package/docs/addons/open-code-review.md +1 -1
  6. package/docs/agent-notes/README.md +66 -0
  7. package/docs/agent-notes/adapters.md +14 -7
  8. package/docs/agent-notes/budget.md +1 -1
  9. package/docs/agent-notes/bus.md +2 -1
  10. package/docs/agent-notes/daemon.md +9 -7
  11. package/docs/agent-notes/local-worker.md +1 -1
  12. package/docs/agent-notes/models.md +5 -2
  13. package/docs/agent-notes/tasks.md +9 -2
  14. package/docs/agent-notes/tests.md +6 -0
  15. package/docs/design/adapters.md +182 -2
  16. package/docs/design/agent-hub-architecture.md +64 -2
  17. package/docs/design/agent-hub.md +6 -0
  18. package/docs/design/bus.md +26 -0
  19. package/docs/design/execution-reference.md +306 -0
  20. package/docs/design/guidance-experiments.md +438 -0
  21. package/docs/design/model-routes.md +628 -0
  22. package/docs/design/supervision.md +121 -0
  23. package/docs/design/task-board.md +121 -0
  24. package/docs/dogfood.md +45 -13
  25. package/docs/events.md +38 -20
  26. package/docs/memory.md +21 -7
  27. package/docs/operations.md +824 -40
  28. package/docs/profiles.md +2 -2
  29. package/docs/quickstart.md +117 -4
  30. package/docs/research.md +73 -13
  31. package/docs/roles.md +1 -1
  32. package/docs/sdlc.md +117 -11
  33. package/docs/security.md +153 -15
  34. package/docs/smoke.md +14 -0
  35. package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
  36. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  37. package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
  38. package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
  39. package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
  40. package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
  41. package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
  42. package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
  43. package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
  44. package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
  45. package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
  46. package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
  47. package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
  48. package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
  49. package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
  50. package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
  51. package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
  52. package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
  53. package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
  54. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
  55. package/docs/verification/2026-11-09-0.35.0.md +129 -0
  56. package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
  57. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  58. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  59. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  60. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  61. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  62. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  63. package/docs/verification/claude-permission-transport-native.py +10 -3
  64. package/docs/verification/claude-shell-wrapper-native.py +8 -8
  65. package/docs/verified.json +245 -15
  66. package/package.json +3 -3
  67. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  68. package/plugins/agent-hub/kimi-hook.js +21230 -0
  69. package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
  70. package/plugins/agent-hub/server.js +4359 -1071
  71. package/scripts/check-docs.mjs +12 -1
  72. package/src/adapters/acp-model-policy.ts +56 -0
  73. package/src/adapters/acp.ts +175 -5
  74. package/src/adapters/agy/entry.ts +8 -5
  75. package/src/adapters/agy/hooks.ts +65 -15
  76. package/src/adapters/channel-peer.ts +33 -1
  77. package/src/adapters/claude-channel.ts +7 -4
  78. package/src/adapters/claude-implementer.ts +16 -3
  79. package/src/adapters/codex-appserver.ts +118 -8
  80. package/src/adapters/codex-review-isolation.ts +3 -1
  81. package/src/adapters/compat.ts +18 -13
  82. package/src/adapters/definitions/builtin-metadata.ts +8 -1
  83. package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
  84. package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
  85. package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
  86. package/src/adapters/definitions/reviewer-variants.ts +3 -1
  87. package/src/adapters/kimi-review-policy-worker.js +2 -0
  88. package/src/adapters/kimi-review-policy-worker.ts +85 -0
  89. package/src/adapters/kimi-review-policy.ts +68 -0
  90. package/src/adapters/kimi-review.ts +41 -41
  91. package/src/adapters/kimi-tui-facts.ts +153 -0
  92. package/src/adapters/kimi-wire-usage.ts +33 -8
  93. package/src/adapters/local-worker.ts +60 -21
  94. package/src/adapters/model-token.ts +3 -0
  95. package/src/adapters/pi.ts +27 -5
  96. package/src/adapters/qwen-dual.ts +324 -44
  97. package/src/adapters/registry-types.ts +34 -3
  98. package/src/adapters/registry.ts +1 -0
  99. package/src/adapters/reviewer-policy-watch.ts +86 -0
  100. package/src/adapters/reviewer-print.ts +80 -18
  101. package/src/cli/agents.ts +1 -1
  102. package/src/cli/facts-hook.ts +4 -2
  103. package/src/cli/guidance.ts +67 -0
  104. package/src/cli/help.ts +13 -5
  105. package/src/cli/identity.ts +13 -3
  106. package/src/cli/init-prompt.ts +15 -2
  107. package/src/cli/init-required-checks.ts +122 -0
  108. package/src/cli/init-settings.ts +10 -4
  109. package/src/cli/init.ts +39 -3
  110. package/src/cli/kimi-facts-hook.ts +11 -0
  111. package/src/cli/kimi-plugin.ts +157 -0
  112. package/src/cli/lineage.ts +78 -0
  113. package/src/cli/main.ts +159 -19
  114. package/src/cli/model.ts +52 -0
  115. package/src/cli/output.ts +23 -1
  116. package/src/cli/reset.ts +1 -1
  117. package/src/cli/setup-research.ts +10 -0
  118. package/src/cli/status-lines.ts +8 -4
  119. package/src/hub/autonomy-defaults.ts +20 -9
  120. package/src/hub/board.ts +346 -4
  121. package/src/hub/budget.ts +1 -1
  122. package/src/hub/build-entry.ts +11 -0
  123. package/src/hub/bus.ts +52 -2
  124. package/src/hub/ci-watch.ts +4 -4
  125. package/src/hub/code-facts.ts +10 -3
  126. package/src/hub/completions.ts +3 -1
  127. package/src/hub/config-apply.ts +3 -1
  128. package/src/hub/config-trust.ts +1 -0
  129. package/src/hub/control-client.ts +1 -1
  130. package/src/hub/daemon.ts +1387 -121
  131. package/src/hub/deliverable-files.ts +38 -5
  132. package/src/hub/delivery-hints.ts +4 -2
  133. package/src/hub/delivery-journal.ts +50 -2
  134. package/src/hub/delivery-public.ts +51 -0
  135. package/src/hub/dogfood-profile.ts +9 -5
  136. package/src/hub/envelope.ts +1 -1
  137. package/src/hub/events.ts +28 -18
  138. package/src/hub/execution-lineage-owner.ts +272 -0
  139. package/src/hub/execution-lineage.ts +164 -0
  140. package/src/hub/execution-links.ts +85 -0
  141. package/src/hub/execution-reference.ts +36 -0
  142. package/src/hub/guidance-variants.ts +398 -0
  143. package/src/hub/handoff.ts +1 -0
  144. package/src/hub/hub-tools.ts +62 -2
  145. package/src/hub/instances.ts +4 -3
  146. package/src/hub/kimi-events.ts +46 -0
  147. package/src/hub/kimi-usage.ts +132 -29
  148. package/src/hub/lifecycle.ts +31 -15
  149. package/src/hub/limits.ts +13 -4
  150. package/src/hub/manager.ts +58 -3
  151. package/src/hub/memory-policy.ts +4 -3
  152. package/src/hub/memory-sync-attestation.ts +54 -0
  153. package/src/hub/memory-sync-state.ts +20 -5
  154. package/src/hub/model-overrides.ts +115 -0
  155. package/src/hub/native-hook-launch.ts +12 -3
  156. package/src/hub/operational-view.ts +2 -2
  157. package/src/hub/peers.ts +28 -1
  158. package/src/hub/permission-mode.ts +1 -1
  159. package/src/hub/person-figures.ts +88 -0
  160. package/src/hub/planning.ts +1 -1
  161. package/src/hub/progress.ts +24 -7
  162. package/src/hub/report.ts +38 -4
  163. package/src/hub/research-dataset.ts +158 -0
  164. package/src/hub/research-memory.ts +68 -0
  165. package/src/hub/research-quality.ts +118 -0
  166. package/src/hub/research-record.ts +279 -0
  167. package/src/hub/research.ts +126 -27
  168. package/src/hub/restart.ts +27 -0
  169. package/src/hub/roles.ts +26 -0
  170. package/src/hub/routing.ts +4 -1
  171. package/src/hub/sdlc-merge.ts +39 -1
  172. package/src/hub/sdlc-release.ts +1 -1
  173. package/src/hub/sdlc.ts +62 -11
  174. package/src/hub/settings.ts +5 -0
  175. package/src/hub/startup-event-seeds.ts +51 -0
  176. package/src/hub/startup-readiness.ts +65 -0
  177. package/src/hub/startup-timing.ts +38 -0
  178. package/src/hub/supervision-proposals.ts +405 -0
  179. package/src/hub/supervision-rules.ts +388 -0
  180. package/src/hub/supervision.ts +2 -0
  181. package/src/hub/task-approval.ts +2 -2
  182. package/src/hub/task-repository.ts +5 -0
  183. package/src/hub/tasks.ts +632 -59
  184. package/src/hub/ui.ts +9 -5
  185. package/src/hub/visual-assets.ts +50 -0
  186. package/src/hub/visual.ts +257 -0
  187. package/src/memory/brief.ts +169 -14
  188. package/src/memory/capture.ts +4 -3
  189. package/src/memory/recall.ts +46 -5
  190. package/src/memory/record-provenance.ts +82 -0
  191. package/src/memory/records.ts +116 -0
  192. package/src/models/relay.ts +9 -2
  193. package/src/models/route/adec.ts +190 -0
  194. package/src/models/route/config.ts +64 -3
  195. package/src/models/route/decision-evidence.ts +83 -0
  196. package/src/models/route/decision.ts +215 -0
  197. package/src/models/route/relay-selector.ts +8 -7
  198. package/src/models/route/runtime.ts +35 -22
  199. package/src/models/route/stage-diagnostics.ts +22 -0
  200. package/src/models/route/stage-evidence.ts +55 -0
  201. package/src/models/route/stage-fallback.ts +58 -0
  202. package/src/models/route/stage-input.ts +155 -0
  203. package/src/models/route/stage.ts +5 -147
  204. package/src/ui/guidance-panel.ts +156 -0
  205. package/src/ui/guidance-view.ts +43 -0
  206. package/src/ui/index.html +134 -6
  207. package/src/ui/lineage-view.ts +34 -0
  208. package/src/ui/plugin.ts +136 -11
  209. package/templates/AGENTS.block.md +1 -1
  210. package/templates/config.json +1 -1
  211. package/templates/profiles/general.json +1 -1
  212. package/templates/profiles/research.json +1 -1
  213. package/templates/profiles/writing.json +1 -1
@@ -0,0 +1,398 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ import { sanitize } from "./envelope.ts";
3
+ import { types } from "node:util";
4
+ import { executionReferenceKey, executionText, parseExecutionReference, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
5
+ import { executionLinkActor, executionLinkInteger } from "./execution-links.ts";
6
+ import { parseRoleDocument, roleIdentity, taskRoleText, type CatalogRole, type RoleDocument } from "./roles.ts";
7
+
8
+ /** Immutable V1 data bounds, not tunable host policy or execution permissions. */
9
+ export const GUIDANCE_ROLE_MAX_BYTES = 8192;
10
+ export const GUIDANCE_RATIONALE_MAX_BYTES = 2000;
11
+ export const GUIDANCE_RECORD_MAX_BYTES = 32768;
12
+ export const GUIDANCE_EVIDENCE_MAX_REFS = 16;
13
+ export const GUIDANCE_EXPERIMENT_MAX_VARIANTS = 16;
14
+ export const GUIDANCE_HASH_HEX_LENGTH = 64;
15
+ export const GUIDANCE_VARIANT_LIMITS = Object.freeze({ roleBytes: GUIDANCE_ROLE_MAX_BYTES, rationaleBytes: GUIDANCE_RATIONALE_MAX_BYTES,
16
+ recordBytes: GUIDANCE_RECORD_MAX_BYTES, evidenceRefs: GUIDANCE_EVIDENCE_MAX_REFS, variants: GUIDANCE_EXPERIMENT_MAX_VARIANTS });
17
+ export interface GuidanceBaselineV1 {
18
+ readonly roleId: string; readonly layer: CatalogRole["layer"]; readonly sha256: string; readonly bytes: string;
19
+ }
20
+ export interface GuidanceCandidateV1 { readonly sha256: string; readonly bytes: string }
21
+ export interface GuidanceRationaleV1 { readonly problemHypothesis: string; readonly expectedObservableDifference: string }
22
+ export interface GuidanceVariantPayloadV1 {
23
+ readonly v: 1; readonly projectKey: string; readonly experimentId: string;
24
+ readonly taskId: number; readonly taskCreated: number; readonly flowRevision: number;
25
+ readonly baseline: GuidanceBaselineV1; readonly candidate: GuidanceCandidateV1; readonly author: string;
26
+ readonly rationale: GuidanceRationaleV1; readonly evidenceRefs: readonly Readonly<ExecutionReferenceV1>[];
27
+ }
28
+ export interface GuidanceVariantV1 extends GuidanceVariantPayloadV1 { readonly id: string }
29
+ /** The host preserves baseline at experiment creation; currentBaseline is a separate fresh catalog identity. */
30
+ export interface GuidanceVariantContext {
31
+ readonly projectKey: string; readonly experimentId: string; readonly taskId: number; readonly taskCreated: number;
32
+ readonly flowRevision: number; readonly actor: string; readonly baseline: GuidanceBaselineV1;
33
+ readonly currentBaseline: Readonly<ReturnType<typeof roleIdentity>>;
34
+ /** Every historical variant key, including withdrawn records. */
35
+ readonly variantIds: readonly string[];
36
+ }
37
+ export class GuidanceVariantError extends Error {
38
+ constructor(readonly code: "invalid" | "protected" | "prose" | "changed" | "limit") {
39
+ super({
40
+ invalid: "invalid guidance variant fields, hashes or bounds; use the closed V1 contract and current admitted role snapshots before retrying",
41
+ protected: "guidance variant changes protected role bytes; restore the baseline metadata, prefix, headings and protected sections before retrying",
42
+ prose: "guidance variant requires bounded prose-shaped sentences; remove command/code/header syntax and retry without changing protected bytes",
43
+ changed: "guidance variant context changed; reload the current task and catalog identity and start a new experiment when its frozen baseline differs",
44
+ limit: "guidance experiment already has sixteen variants; reuse an identical recorded variant or start a separate experiment before proposing another",
45
+ }[code]);
46
+ this.name = "GuidanceVariantError";
47
+ }
48
+ }
49
+ const invalid = (): never => { throw new GuidanceVariantError("invalid"); };
50
+ const HASH = /^[a-f0-9]{64}$/;
51
+ const PAYLOAD_KEYS = ["v", "projectKey", "experimentId", "taskId", "taskCreated", "flowRevision", "baseline", "candidate", "author", "rationale", "evidenceRefs"] as const;
52
+ const EDITABLE = new Set(["Scope", "Deliverables", "Evidence"]);
53
+
54
+ /** Inspect inert own data only. Never invoke a producer getter, iterator or toJSON. */
55
+ function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
56
+ if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)
57
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return invalid();
58
+ const own = Reflect.ownKeys(value);
59
+ if (own.length > keys.length) return invalid();
60
+ const out: Record<string, unknown> = Object.create(null);
61
+ for (const key of own) {
62
+ if (typeof key !== "string" || !keys.includes(key)) return invalid();
63
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
64
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return invalid();
65
+ out[key] = descriptor.value;
66
+ }
67
+ return out;
68
+ }
69
+ function array(value: unknown, maximum: number): unknown[] {
70
+ if (!value || typeof value !== "object" || types.isProxy(value) || !Array.isArray(value)
71
+ || Object.getPrototypeOf(value) !== Array.prototype || value.length > maximum) return invalid();
72
+ const keys = Reflect.ownKeys(value);
73
+ if (keys.length !== value.length + 1 || keys.some(key => typeof key !== "string")) return invalid();
74
+ const out: unknown[] = [];
75
+ for (let index = 0; index < value.length; index++) {
76
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
77
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return invalid();
78
+ out.push(descriptor.value);
79
+ }
80
+ return out;
81
+ }
82
+ function boundedText(value: unknown, maximum: number): string {
83
+ if (typeof value !== "string" || value.length === 0 || value.length > maximum || Buffer.byteLength(value, "utf8") > maximum) return invalid();
84
+ return value;
85
+ }
86
+ function hash(value: unknown): string { return typeof value === "string" && value.length === GUIDANCE_HASH_HEX_LENGTH && HASH.test(value) ? value : invalid(); }
87
+ function identity(value: unknown): string { return executionText(value, EXECUTION_REFERENCE_LIMITS.id) ? value : invalid(); }
88
+ const actor = (value: unknown): value is string => executionText(value, EXECUTION_REFERENCE_LIMITS.id) && executionLinkActor(value);
89
+ function roleDocument(bytes: unknown, roleId: unknown, layer: unknown): RoleDocument {
90
+ const text = boundedText(bytes, GUIDANCE_VARIANT_LIMITS.roleBytes);
91
+ if (typeof roleId !== "string" || (layer !== "shipped" && layer !== "project")) return invalid();
92
+ try {
93
+ const document = parseRoleDocument(text, roleId, layer);
94
+ taskRoleText(document.role); // Preserve the existing complete rendered UTF-16 limit, including its header.
95
+ return document;
96
+ } catch { return invalid(); }
97
+ }
98
+ function baseline(value: unknown): { value: GuidanceBaselineV1; document: RoleDocument } {
99
+ const fields = object(value, ["roleId", "layer", "sha256", "bytes"]);
100
+ const document = roleDocument(fields.bytes, fields.roleId, fields.layer), sha256 = hash(fields.sha256);
101
+ if (document.role.hash !== sha256) return invalid();
102
+ return { value: Object.freeze({ roleId: document.role.id, layer: document.role.layer, sha256, bytes: fields.bytes as string }), document };
103
+ }
104
+
105
+ /** A deliberately narrow lexical ceiling. It does not establish semantic safety or host authority. */
106
+ function prose(text: string): void {
107
+ let meaningful = false;
108
+ for (const raw of text.split("\n")) {
109
+ if (!/^[\p{L}\p{M}\p{N} .,:;!?'"()\/\-]*$/u.test(raw) || raw.includes("--")
110
+ || /\[agent-hub\b|<channel\b/i.test(raw) || /[\p{L}\p{N}_]\(/u.test(raw)) throw new GuidanceVariantError("prose");
111
+ if (!raw.trim()) continue;
112
+ const line = raw.startsWith("- ") ? raw.slice(2) : raw;
113
+ if (!/^\p{L}/u.test(line) || !/[.!?]$/.test(line)
114
+ || /^(?:bun|npm|npx|git|ssh|curl|wget|rm|bash|sh|python[0-9.]*|node|pnpm|yarn|zsh|sudo|env|exec|eval|echo|printf|cat|tee|chmod)(?:\s|$)/i.test(line)
115
+ || /^(?:import|export|def|function|class|const|let|var|await|return|throw|raise|yield)(?:\s|$)/i.test(line)) throw new GuidanceVariantError("prose");
116
+ meaningful = true;
117
+ }
118
+ if (!meaningful) throw new GuidanceVariantError("prose");
119
+ }
120
+ function restricted(baselineDocument: RoleDocument, candidateDocument: RoleDocument): void {
121
+ if (baselineDocument.rawHeader !== candidateDocument.rawHeader || baselineDocument.bodyPrefix !== candidateDocument.bodyPrefix) throw new GuidanceVariantError("protected");
122
+ for (const [index, original] of baselineDocument.sections.entries()) {
123
+ const candidate = candidateDocument.sections[index]!;
124
+ if (original.headingRaw !== candidate.headingRaw || !EDITABLE.has(original.name) && original.raw !== candidate.raw) throw new GuidanceVariantError("protected");
125
+ if (EDITABLE.has(original.name)) prose(candidate.contentRaw);
126
+ }
127
+ }
128
+ function rationale(value: unknown): GuidanceRationaleV1 {
129
+ const fields = object(value, ["problemHypothesis", "expectedObservableDifference"]);
130
+ const result = { problemHypothesis: boundedText(fields.problemHypothesis, GUIDANCE_VARIANT_LIMITS.rationaleBytes),
131
+ expectedObservableDifference: boundedText(fields.expectedObservableDifference, GUIDANCE_VARIANT_LIMITS.rationaleBytes) };
132
+ if (Buffer.byteLength(JSON.stringify(result), "utf8") > GUIDANCE_VARIANT_LIMITS.rationaleBytes) return invalid();
133
+ prose(result.problemHypothesis); prose(result.expectedObservableDifference);
134
+ return Object.freeze(result);
135
+ }
136
+ function payload(fields: Record<string, unknown>): GuidanceVariantPayloadV1 {
137
+ if (fields.v !== 1 || !executionText(fields.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey)
138
+ || !executionLinkInteger(fields.taskId, 1) || !executionLinkInteger(fields.taskCreated) || !executionLinkInteger(fields.flowRevision)
139
+ || !actor(fields.author)) return invalid();
140
+ const original = baseline(fields.baseline), proposed = object(fields.candidate, ["sha256", "bytes"]);
141
+ const candidateDocument = roleDocument(proposed.bytes, original.value.roleId, original.value.layer), sha256 = hash(proposed.sha256);
142
+ if (candidateDocument.role.hash !== sha256) return invalid();
143
+ restricted(original.document, candidateDocument);
144
+ let refs: ExecutionReferenceV1[];
145
+ try {
146
+ refs = array(fields.evidenceRefs, GUIDANCE_VARIANT_LIMITS.evidenceRefs).map(value => {
147
+ const ref = parseExecutionReference(object(value, ["v", "tool", "projectKey", "kind", "id", "revision", "sha256"]));
148
+ if (ref.sha256 !== undefined) hash(ref.sha256);
149
+ return ref;
150
+ });
151
+ }
152
+ catch { return invalid(); }
153
+ if (new Set(refs.map(executionReferenceKey)).size !== refs.length) return invalid();
154
+ return Object.freeze({ v: 1, projectKey: fields.projectKey, experimentId: identity(fields.experimentId),
155
+ taskId: fields.taskId, taskCreated: fields.taskCreated, flowRevision: fields.flowRevision,
156
+ baseline: original.value, candidate: Object.freeze({ sha256, bytes: proposed.bytes as string }), author: fields.author,
157
+ rationale: rationale(fields.rationale), evidenceRefs: Object.freeze(refs.map(ref => Object.freeze(ref))) });
158
+ }
159
+ function contentKey(value: GuidanceVariantPayloadV1): string {
160
+ return createHash("sha256").update(JSON.stringify(["agent-hub.guidance-variant/v1", value]), "utf8").digest("hex");
161
+ }
162
+ function record(value: GuidanceVariantPayloadV1, id: string): Readonly<GuidanceVariantV1> {
163
+ const result = Object.freeze({ id, ...value });
164
+ if (Buffer.byteLength(JSON.stringify(result), "utf8") > GUIDANCE_VARIANT_LIMITS.recordBytes) return invalid();
165
+ return result;
166
+ }
167
+ /** Content-addressing is not admission, provenance, testing or approval. */
168
+ export function guidanceVariantKey(value: GuidanceVariantPayloadV1): string {
169
+ const normalized = payload(object(value, PAYLOAD_KEYS)), id = contentKey(normalized);
170
+ record(normalized, id);
171
+ return id;
172
+ }
173
+ export function parseGuidanceVariantV1(value: unknown): Readonly<GuidanceVariantV1> {
174
+ const fields = object(value, [...PAYLOAD_KEYS, "id"]), normalized = payload(fields), id = hash(fields.id);
175
+ if (contentKey(normalized) !== id) return invalid();
176
+ return record(normalized, id);
177
+ }
178
+ /** Compare supplied host snapshots only; Tasks must separately check live authority, privacy and currentness. */
179
+ export function validateGuidanceVariantV1(value: unknown, context: GuidanceVariantContext): Readonly<GuidanceVariantV1> {
180
+ const result = parseGuidanceVariantV1(value);
181
+ const fields = object(context, ["projectKey", "experimentId", "taskId", "taskCreated", "flowRevision", "actor", "baseline", "currentBaseline", "variantIds"]);
182
+ if (!executionText(fields.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey) || !executionLinkInteger(fields.taskId, 1)
183
+ || !executionLinkInteger(fields.taskCreated) || !executionLinkInteger(fields.flowRevision) || !actor(fields.actor)) return invalid();
184
+ const experimentId = identity(fields.experimentId), frozen = baseline(fields.baseline).value;
185
+ const current = object(fields.currentBaseline, ["id", "layer", "hash"]);
186
+ if (typeof current.id !== "string" || (current.layer !== "shipped" && current.layer !== "project")) return invalid();
187
+ hash(current.hash);
188
+ const ids = array(fields.variantIds, GUIDANCE_VARIANT_LIMITS.variants).map(hash);
189
+ if (new Set(ids).size !== ids.length) return invalid();
190
+ if (result.projectKey !== fields.projectKey || result.experimentId !== experimentId || result.taskId !== fields.taskId
191
+ || result.taskCreated !== fields.taskCreated || result.flowRevision !== fields.flowRevision || result.author !== fields.actor
192
+ || result.baseline.roleId !== frozen.roleId || result.baseline.layer !== frozen.layer || result.baseline.sha256 !== frozen.sha256 || result.baseline.bytes !== frozen.bytes
193
+ || current.id !== frozen.roleId || current.layer !== frozen.layer || current.hash !== frozen.sha256) throw new GuidanceVariantError("changed");
194
+ if (ids.length === GUIDANCE_VARIANT_LIMITS.variants && !ids.includes(result.id)) throw new GuidanceVariantError("limit");
195
+ return result;
196
+ }
197
+ /** Historical rendering is advisory data, never a current-catalog or authorized-handoff receipt. */
198
+ export function renderGuidanceVariantV1(value: unknown, review = false): string {
199
+ const parsed = parseGuidanceVariantV1(value);
200
+ return taskRoleText(parseRoleDocument(parsed.candidate.bytes, parsed.baseline.roleId, parsed.baseline.layer).role, review);
201
+ }
202
+
203
+ /** Local storage metadata never changes the immutable V1 payload or confers execution provenance. */
204
+ export interface GuidanceExperimentRecord {
205
+ readonly projectKey: string; readonly taskId: number; readonly taskCreated: number; readonly experimentId: string;
206
+ readonly baseline: GuidanceBaselineV1;
207
+ }
208
+ export interface GuidanceStoredRecord {
209
+ readonly variant: Readonly<GuidanceVariantV1>; readonly createdBy: string; readonly createdAt: number;
210
+ readonly withdrawn?: Readonly<{ by: string; at: number }>;
211
+ }
212
+ export interface GuidanceSelector { readonly taskId: number; readonly taskCreated: number; readonly experimentId: string; readonly id?: string; readonly flowRevision?: number }
213
+ export interface GuidanceWriteFence {
214
+ readonly by: string; readonly at: number; readonly taskId: number; readonly taskCreated: number; readonly flowRevision: number;
215
+ readonly owner: string | null; readonly state: string; readonly roleId: string | undefined;
216
+ }
217
+ export interface GuidanceWriteReceipt { readonly id: string; readonly taskId: number; readonly experimentId: string; readonly status: "declared" | "withdrawn"; readonly already: boolean }
218
+ export interface GuidanceVariantMetadata {
219
+ readonly id: string; readonly experimentId: string; readonly taskId: number; readonly taskCreated: number; readonly flowRevision: number;
220
+ readonly roleId: string; readonly layer: CatalogRole["layer"]; readonly baselineSha256: string; readonly candidateSha256: string;
221
+ readonly changedSections: readonly ("Scope" | "Deliverables" | "Evidence")[];
222
+ readonly bytes: Readonly<{ baseline: number; candidate: number; record: number }>;
223
+ readonly author: string;
224
+ }
225
+ export type GuidanceReadResult = { state: "unavailable" } | { state: "available"; records: (GuidanceVariantMetadata & {
226
+ status: "declared" | "withdrawn"; applicable: boolean; rationale: GuidanceRationaleV1;
227
+ evidence: { key: string; status: "declared" | "unavailable" }[];
228
+ })[] };
229
+ /** Structural metadata only: Tasks field-screens the opaque experiment id before public use. No raw snapshots or evidence addresses. */
230
+ export function guidanceVariantMetadata(value: unknown): GuidanceVariantMetadata {
231
+ const variant = parseGuidanceVariantV1(value), original = parseRoleDocument(variant.baseline.bytes, variant.baseline.roleId, variant.baseline.layer);
232
+ const candidate = parseRoleDocument(variant.candidate.bytes, variant.baseline.roleId, variant.baseline.layer);
233
+ const changedSections = original.sections.flatMap((section, index) => EDITABLE.has(section.name) && section.contentRaw !== candidate.sections[index]!.contentRaw
234
+ ? [section.name as "Scope" | "Deliverables" | "Evidence"] : []);
235
+ return Object.freeze({ id: variant.id, experimentId: variant.experimentId, taskId: variant.taskId, taskCreated: variant.taskCreated,
236
+ flowRevision: variant.flowRevision, roleId: variant.baseline.roleId, layer: variant.baseline.layer,
237
+ baselineSha256: variant.baseline.sha256, candidateSha256: variant.candidate.sha256, changedSections: Object.freeze(changedSections),
238
+ bytes: Object.freeze({ baseline: Buffer.byteLength(variant.baseline.bytes), candidate: Buffer.byteLength(variant.candidate.bytes), record: Buffer.byteLength(JSON.stringify(variant)) }),
239
+ author: variant.author });
240
+ }
241
+ export function parseGuidanceSelector(value: unknown, withdraw = false): GuidanceSelector {
242
+ const fields = object(value, withdraw ? ["taskId", "taskCreated", "experimentId", "id", "flowRevision"] : ["taskId", "taskCreated", "experimentId", "id"]);
243
+ if (!executionLinkInteger(fields.taskId, 1) || !executionLinkInteger(fields.taskCreated)
244
+ || withdraw && !executionLinkInteger(fields.flowRevision)) return invalid();
245
+ return Object.freeze({ taskId: fields.taskId, taskCreated: fields.taskCreated, experimentId: identity(fields.experimentId),
246
+ ...(fields.id === undefined && !withdraw ? {} : { id: hash(fields.id) }), ...(withdraw ? { flowRevision: fields.flowRevision as number } : {}) });
247
+ }
248
+ export function parseGuidanceExperiment(value: unknown): GuidanceExperimentRecord {
249
+ const fields = object(value, ["projectKey", "taskId", "taskCreated", "experimentId", "baseline"]);
250
+ if (!executionText(fields.projectKey, EXECUTION_REFERENCE_LIMITS.projectKey) || !executionLinkInteger(fields.taskId, 1)
251
+ || !executionLinkInteger(fields.taskCreated)) return invalid();
252
+ return Object.freeze({ projectKey: fields.projectKey, taskId: fields.taskId, taskCreated: fields.taskCreated,
253
+ experimentId: identity(fields.experimentId), baseline: baseline(fields.baseline).value });
254
+ }
255
+ export function parseGuidanceStoredRecord(value: unknown): GuidanceStoredRecord {
256
+ const fields = object(value, ["variant", "createdBy", "createdAt", "withdrawn"]), variant = parseGuidanceVariantV1(fields.variant);
257
+ if (!actor(fields.createdBy) || fields.createdBy !== variant.author || !executionLinkInteger(fields.createdAt)) return invalid();
258
+ let withdrawn: GuidanceStoredRecord["withdrawn"];
259
+ if (fields.withdrawn !== undefined) {
260
+ const item = object(fields.withdrawn, ["by", "at"]);
261
+ if (!actor(item.by) || !executionLinkInteger(item.at) || item.at < fields.createdAt) return invalid();
262
+ withdrawn = Object.freeze({ by: item.by, at: item.at });
263
+ }
264
+ return Object.freeze({ variant, createdBy: fields.createdBy, createdAt: fields.createdAt, ...(withdrawn ? { withdrawn } : {}) });
265
+ }
266
+
267
+
268
+ /** Published T3 reply and cursor shapes, separate from private record bounds. */
269
+ export const GUIDANCE_PAGE_MAX_RECORDS = 32;
270
+ export const GUIDANCE_REPLY_MAX_BYTES = 262144;
271
+ export const GUIDANCE_CURSOR_MAX_BYTES = 512;
272
+ export type GuidancePublicRecord = Extract<GuidanceReadResult, { state: "available" }>["records"][number];
273
+ export interface GuidanceCurrent { readonly taskId: number; readonly taskCreated: number; readonly flowRevision: number }
274
+ export type GuidancePageResult = { state: "unavailable" } | { state: "available"; current: GuidanceCurrent; records: GuidancePublicRecord[]; truncated: boolean; cursor?: string };
275
+ export type GuidanceEditableSection = "Scope" | "Deliverables" | "Evidence";
276
+ export interface GuidanceSectionDiff { readonly section: GuidanceEditableSection; readonly before: string; readonly after: string }
277
+ export type GuidanceDiffResult = { state: "unavailable" } | { state: "available"; current: GuidanceCurrent; record: GuidancePublicRecord;
278
+ sections: readonly GuidanceSectionDiff[]; protectedSections: readonly string[] };
279
+ const EDITABLE_NAMES: readonly GuidanceEditableSection[] = ["Scope", "Deliverables", "Evidence"];
280
+ const PROTECTED_NAMES = ["Not in scope", "Hub use", "Review duties"] as const;
281
+ export function guidanceVariantSectionDiff(value: unknown, allowed: (text: string) => boolean): readonly GuidanceSectionDiff[] {
282
+ const variant = parseGuidanceVariantV1(value), original = parseRoleDocument(variant.baseline.bytes, variant.baseline.roleId, variant.baseline.layer);
283
+ const candidate = parseRoleDocument(variant.candidate.bytes, variant.baseline.roleId, variant.baseline.layer);
284
+ const field = (text: string) => {
285
+ try { if (Buffer.byteLength(text) <= GUIDANCE_ROLE_MAX_BYTES && allowed(text)) {
286
+ const rendered = sanitize(text); if (Buffer.byteLength(rendered) <= GUIDANCE_ROLE_MAX_BYTES) return rendered;
287
+ } } catch { /* Unknown policy withholds one whole field. */ }
288
+ return "withheld";
289
+ };
290
+ return Object.freeze(original.sections.flatMap((section, index) => EDITABLE.has(section.name)
291
+ ? [Object.freeze({ section: section.name as GuidanceEditableSection, before: field(section.contentRaw), after: field(candidate.sections[index]!.contentRaw) })] : []));
292
+ }
293
+ export const guidanceProtectedSectionNames = (): readonly string[] => Object.freeze([...PROTECTED_NAMES]);
294
+ function currentBinding(value: unknown): GuidanceCurrent {
295
+ const fields = object(value, ["taskId", "taskCreated", "flowRevision"]);
296
+ if (!executionLinkInteger(fields.taskId, 1) || !executionLinkInteger(fields.taskCreated) || !executionLinkInteger(fields.flowRevision)) return invalid();
297
+ return Object.freeze({ taskId: fields.taskId, taskCreated: fields.taskCreated, flowRevision: fields.flowRevision });
298
+ }
299
+ function publicText(value: unknown, maximum: number): string {
300
+ const text = boundedText(value, maximum);
301
+ if (!executionText(text.replaceAll("\n", "").replaceAll("\t", ""), maximum)) return invalid();
302
+ return text;
303
+ }
304
+ export function parseGuidancePublicRecord(value: unknown): GuidancePublicRecord {
305
+ const f = object(value, ["id", "experimentId", "taskId", "taskCreated", "flowRevision", "roleId", "layer", "baselineSha256", "candidateSha256", "changedSections", "bytes", "author", "status", "applicable", "rationale", "evidence"]);
306
+ const current = currentBinding({ taskId: f.taskId, taskCreated: f.taskCreated, flowRevision: f.flowRevision });
307
+ if (!executionText(f.roleId, EXECUTION_REFERENCE_LIMITS.id) || !/^[a-z][a-z0-9-]{0,47}$/.test(f.roleId) || !actor(f.author)
308
+ || !["shipped", "project"].includes(f.layer as string) || !["declared", "withdrawn"].includes(f.status as string)
309
+ || typeof f.applicable !== "boolean" || f.status === "withdrawn" && f.applicable) return invalid();
310
+ const changed = array(f.changedSections, EDITABLE_NAMES.length);
311
+ if (changed.some(name => !EDITABLE_NAMES.includes(name as GuidanceEditableSection)) || new Set(changed).size !== changed.length) return invalid();
312
+ const size = object(f.bytes, ["baseline", "candidate", "record"]);
313
+ if (!executionLinkInteger(size.baseline, 1) || size.baseline > GUIDANCE_ROLE_MAX_BYTES || !executionLinkInteger(size.candidate, 1)
314
+ || size.candidate > GUIDANCE_ROLE_MAX_BYTES || !executionLinkInteger(size.record, 1) || size.record > GUIDANCE_RECORD_MAX_BYTES) return invalid();
315
+ const why = object(f.rationale, ["problemHypothesis", "expectedObservableDifference"]);
316
+ const evidence = array(f.evidence, GUIDANCE_EVIDENCE_MAX_REFS).map((item): { key: string; status: "declared" | "unavailable" } => {
317
+ const entry = object(item, ["key", "status"]);
318
+ if (entry.status !== "declared" && entry.status !== "unavailable") return invalid();
319
+ return { key: hash(entry.key), status: entry.status };
320
+ });
321
+ if (new Set(evidence.map(entry => entry.key)).size !== evidence.length) return invalid();
322
+ return { id: hash(f.id), experimentId: identity(f.experimentId), ...current, roleId: f.roleId, layer: f.layer as CatalogRole["layer"],
323
+ baselineSha256: hash(f.baselineSha256), candidateSha256: hash(f.candidateSha256), changedSections: changed as GuidanceEditableSection[],
324
+ bytes: { baseline: size.baseline, candidate: size.candidate, record: size.record }, author: f.author,
325
+ status: f.status as "declared" | "withdrawn", applicable: f.applicable,
326
+ rationale: { problemHypothesis: publicText(why.problemHypothesis, GUIDANCE_RATIONALE_MAX_BYTES), expectedObservableDifference: publicText(why.expectedObservableDifference, GUIDANCE_RATIONALE_MAX_BYTES) }, evidence };
327
+ }
328
+ function replyBytes<T>(value: T): T { const text = JSON.stringify(value); if (typeof text !== "string" || Buffer.byteLength(text) > GUIDANCE_REPLY_MAX_BYTES) return invalid(); return value; }
329
+ function inCurrent(record: GuidancePublicRecord, current: GuidanceCurrent): void {
330
+ if (record.taskId !== current.taskId || record.taskCreated !== current.taskCreated || record.applicable && record.flowRevision !== current.flowRevision) return invalid();
331
+ }
332
+ function unavailable(fields: Record<string, unknown>): { state: "unavailable" } | undefined {
333
+ if (fields.state !== "unavailable") return undefined;
334
+ if (Object.keys(fields).length !== 1) return invalid();
335
+ return { state: "unavailable" };
336
+ }
337
+ export function parseGuidancePageResult(value: unknown, expected?: Pick<GuidanceCurrent, "taskId" | "taskCreated">): GuidancePageResult {
338
+ const f = object(value, ["state", "current", "records", "truncated", "cursor"]), hidden = unavailable(f); if (hidden) return hidden;
339
+ if (f.state !== "available" || typeof f.truncated !== "boolean") return invalid();
340
+ const current = currentBinding(f.current), records = array(f.records, GUIDANCE_PAGE_MAX_RECORDS).map(parseGuidancePublicRecord);
341
+ if (expected && (current.taskId !== expected.taskId || current.taskCreated !== expected.taskCreated)) return invalid();
342
+ for (const record of records) inCurrent(record, current);
343
+ if (new Set(records.map(record => record.id)).size !== records.length) return invalid();
344
+ if (f.truncated ? !guidanceCursorText(f.cursor) || !records.length : f.cursor !== undefined) return invalid();
345
+ return replyBytes({ state: "available", current, records, truncated: f.truncated, ...(f.truncated ? { cursor: f.cursor as string } : {}) });
346
+ }
347
+ export function parseGuidanceDiffResult(value: unknown, expected?: Pick<GuidanceSelector, "taskId" | "taskCreated" | "id">): GuidanceDiffResult {
348
+ const f = object(value, ["state", "current", "record", "sections", "protectedSections"]), hidden = unavailable(f); if (hidden) return hidden;
349
+ if (f.state !== "available") return invalid();
350
+ const current = currentBinding(f.current), record = parseGuidancePublicRecord(f.record); inCurrent(record, current);
351
+ if (expected && (current.taskId !== expected.taskId || current.taskCreated !== expected.taskCreated || record.id !== expected.id)) return invalid();
352
+ const sections = array(f.sections, EDITABLE_NAMES.length).map((raw, index) => {
353
+ const entry = object(raw, ["section", "before", "after"]); if (entry.section !== EDITABLE_NAMES[index]) return invalid();
354
+ return { section: entry.section as GuidanceEditableSection, before: publicText(entry.before, GUIDANCE_ROLE_MAX_BYTES), after: publicText(entry.after, GUIDANCE_ROLE_MAX_BYTES) };
355
+ });
356
+ const protectedSections = array(f.protectedSections, PROTECTED_NAMES.length);
357
+ if (sections.length !== EDITABLE_NAMES.length || protectedSections.length !== PROTECTED_NAMES.length
358
+ || protectedSections.some((name, index) => name !== PROTECTED_NAMES[index])) return invalid();
359
+ return replyBytes({ state: "available", current, record, sections, protectedSections: [...PROTECTED_NAMES] });
360
+ }
361
+ export function parseGuidanceWriteReceipt(value: unknown): GuidanceWriteReceipt {
362
+ const f = object(value, ["id", "taskId", "experimentId", "status", "already"]);
363
+ if (!executionLinkInteger(f.taskId, 1) || !["declared", "withdrawn"].includes(f.status as string) || typeof f.already !== "boolean") return invalid();
364
+ return { id: hash(f.id), taskId: f.taskId, experimentId: identity(f.experimentId), status: f.status as "declared" | "withdrawn", already: f.already };
365
+ }
366
+ export const guidanceCursorText = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= GUIDANCE_CURSOR_MAX_BYTES && !/[^A-Za-z0-9_-]/.test(value);
367
+ export function parseGuidanceListQuery(value: unknown): Pick<GuidanceCurrent, "taskId" | "taskCreated"> & { cursor?: string } {
368
+ const f = object(value, ["taskId", "taskCreated", "cursor"]);
369
+ if (!executionLinkInteger(f.taskId, 1) || !executionLinkInteger(f.taskCreated) || f.cursor !== undefined && !guidanceCursorText(f.cursor)) return invalid();
370
+ return { taskId: f.taskId, taskCreated: f.taskCreated, ...(f.cursor === undefined ? {} : { cursor: f.cursor as string }) };
371
+ }
372
+ export interface GuidanceCursorContext extends GuidanceCurrent { readonly projectKey: string; readonly actor: string }
373
+ const cursorSignature = (key: string, context: GuidanceCursorContext, after: string): string => createHmac("sha256", key)
374
+ .update(JSON.stringify([1, context.projectKey, context.actor, context.taskId, context.taskCreated, context.flowRevision, after])).digest("hex");
375
+ export function guidancePageCursor(key: string, context: GuidanceCursorContext, after: string): string {
376
+ hash(after);
377
+ return Buffer.from(JSON.stringify({ v: 1, after, signature: cursorSignature(key, context, after) })).toString("base64url");
378
+ }
379
+ export function guidancePageAfter(key: string, context: GuidanceCursorContext, cursor: string): string {
380
+ if (!guidanceCursorText(cursor)) return invalid();
381
+ const raw = Buffer.from(cursor, "base64url"); if (raw.toString("base64url") !== cursor) return invalid();
382
+ const fields = object(JSON.parse(raw.toString("utf8")), ["v", "after", "signature"]);
383
+ if (fields.v !== 1) return invalid();
384
+ const after = hash(fields.after), signature = hash(fields.signature), expected = cursorSignature(key, context, after);
385
+ if (!timingSafeEqual(Buffer.from(signature, "hex"), Buffer.from(expected, "hex"))) return invalid();
386
+ return after;
387
+ }
388
+
389
+ export interface GuidanceIdSelector { readonly taskId: number; readonly taskCreated: number; readonly id: string; readonly flowRevision?: number }
390
+ export function parseGuidanceIdQuery(value: unknown, withdraw = false): GuidanceIdSelector {
391
+ const f = object(value, withdraw ? ["taskId", "taskCreated", "flowRevision", "id"] : ["taskId", "taskCreated", "id"]);
392
+ if (!executionLinkInteger(f.taskId, 1) || !executionLinkInteger(f.taskCreated) || withdraw && !executionLinkInteger(f.flowRevision)) return invalid();
393
+ return { taskId: f.taskId, taskCreated: f.taskCreated, id: hash(f.id), ...(withdraw ? { flowRevision: f.flowRevision as number } : {}) };
394
+ }
395
+
396
+ export function parseGuidanceCreateInput(value: unknown): Readonly<GuidanceVariantV1> {
397
+ return parseGuidanceVariantV1(object(value, ["variant"]).variant);
398
+ }
@@ -190,6 +190,7 @@ export function handoffEventFor(entryEvent: string, state: string): HandoffEvent
190
190
  if (entryEvent === "cancelled" && state === "cancelled") return "cancelled";
191
191
  if (entryEvent === "done" && state === "in_review") return "in_review";
192
192
  if (entryEvent === "approved" && state === "approved") return "approved";
193
+ if (entryEvent === "merged outside the hub" && state === "approved") return "approved";
193
194
  // #733 (agent-hub#1203 H10): a reviewer's changes_requested, and the hub's return of that task to its owner, are states the origin used to hear nothing about. A withdrawn approval is the same
194
195
  // verdict on an approved task: the row it reopens is picked up through the sequence.
195
196
  if (entryEvent === "changes_requested" && state === "changes_requested") return "changes_requested";
@@ -1,3 +1,6 @@
1
+ import { EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
2
+ import { EXECUTION_LINK_LIMITS } from "./execution-links.ts";
3
+ import { GUIDANCE_ROLE_MAX_BYTES, GUIDANCE_RECORD_MAX_BYTES, GUIDANCE_RATIONALE_MAX_BYTES, GUIDANCE_EVIDENCE_MAX_REFS, GUIDANCE_CURSOR_MAX_BYTES, GUIDANCE_HASH_HEX_LENGTH } from "./guidance-variants.ts";
1
4
  import { redFirstSchema } from "./test-integrity.ts";
2
5
  import { SDLC_STAGES } from "./sdlc.ts";
3
6
  import { projectProfile, profileData, PROFILE_CLASS_NAMES, type ProfileName, type ProfileSelection } from "./profiles.ts";
@@ -8,7 +11,7 @@ import { NOTE_KINDS } from "./envelope.ts";
8
11
 
9
12
  /** Restricted to the fixed current-child tools server, never an ordinary peer tool. */
10
13
  /** The fixed MCP surface of a current owned implementer child; independent of broader project roles. */
11
- export const IMPLEMENTER_HUB_TOOL_NAMES: readonly string[] = Object.freeze(["hub_task_accept", "hub_task_decline", "hub_task_done", "hub_checkpoint", "hub_send", "hub_task_show", "hub_task_propose", "hub_remember", "hub_inbox", "hub_permission_request", "hub_study_show", "hub_experiment_show", "hub_experiment_record", "hub_study_handoff", "hub_specs", "hub_delivery_resolve", "hub_evidence_record"]);
14
+ export const IMPLEMENTER_HUB_TOOL_NAMES: readonly string[] = Object.freeze(["hub_task_accept", "hub_task_decline", "hub_task_done", "hub_checkpoint", "hub_send", "hub_task_show", "hub_task_propose", "hub_remember", "hub_visual", "hub_visual_show", "hub_inbox", "hub_permission_request", "hub_study_show", "hub_experiment_show", "hub_experiment_record", "hub_study_handoff", "hub_specs", "hub_delivery_resolve", "hub_evidence_record", "hub_lineage_show", "hub_lineage_link", "hub_guidance_create", "hub_guidance_list", "hub_guidance_show", "hub_guidance_withdraw"]);
12
15
 
13
16
  export const IMPLEMENTER_PERMISSION_TOOL = {
14
17
  name: "hub_permission_request",
@@ -22,6 +25,23 @@ export const ACTIONABLE_MESSAGE_INSTRUCTION = "Do not use [FYI] for PR ready, do
22
25
  const str = { type: "string" } as const;
23
26
  const id = { type: "integer", description: "task id" } as const;
24
27
  const toolWriteRequestId = { type: "string", minLength: 1, maxLength: 256, pattern: "^v1/[A-Za-z0-9._-]{1,128}/[1-9][0-9]{0,15}/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$", description: "control-transport-only request_id returned by an outcome-unknown write; inspect first and retry with the same key and identical arguments only if absent. Direct in-process tool calls cannot use request_id" } as const;
28
+ const visualSideSchema = { oneOf: [
29
+ { type: "object", properties: { text: { type: "string", maxLength: 20 * 1024 } }, required: ["text"], additionalProperties: false },
30
+ { type: "object", properties: { path: { type: "string", minLength: 1, maxLength: 4096 }, alt: { type: "string", maxLength: 1000 } }, required: ["path", "alt"], additionalProperties: false },
31
+ ] } as const;
32
+ const visualTitle = { type: "string", maxLength: 300 } as const;
33
+ const visualCaption = { type: "string", maxLength: 2000 } as const;
34
+ const visualInputSchema = { oneOf: [
35
+ { type: "object", properties: { kind: { const: "mermaid" }, source: { type: "string", minLength: 1, maxLength: 20 * 1024 }, title: visualTitle }, required: ["kind", "source"], additionalProperties: false },
36
+ { type: "object", properties: { kind: { const: "comparison" }, title: visualTitle, options: { type: "array", minItems: 2, maxItems: 6, items: {
37
+ type: "object", properties: { title: visualTitle, summary: { type: "string", maxLength: 4000 }, recommended: { type: "boolean" },
38
+ pros: { type: "array", maxItems: 10, items: { type: "string", maxLength: 2000 } }, cons: { type: "array", maxItems: 10, items: { type: "string", maxLength: 2000 } } }, required: ["title"], additionalProperties: false,
39
+ } } }, required: ["kind", "options"], additionalProperties: false },
40
+ { type: "object", properties: { kind: { const: "table" }, caption: visualCaption, columns: { type: "array", maxItems: 12, items: {
41
+ type: "object", properties: { key: { type: "string", minLength: 1, maxLength: 128 }, label: visualTitle, align: { enum: ["start", "end"] }, format: { enum: ["text", "number", "percent"] } }, required: ["key", "label"], additionalProperties: false,
42
+ } }, rows: { type: "array", maxItems: 500, items: { type: "object", additionalProperties: { oneOf: [{ type: "string", maxLength: 4000 }, { type: "number" }] } } } }, required: ["kind", "columns", "rows"], additionalProperties: false },
43
+ { type: "object", properties: { kind: { const: "beforeAfter" }, caption: visualCaption, before: visualSideSchema, after: visualSideSchema }, required: ["kind", "before", "after"], additionalProperties: false },
44
+ ] } as const;
25
45
  const refs = {
26
46
  type: "object",
27
47
  description: "where the work lives",
@@ -113,11 +133,39 @@ export const EVIDENCE_RECORD_TOOL = tool("hub_evidence_record", "Record a proven
113
133
  }, ["taskId", "claimId", "claimRevision", "sourceId", "rawSha256", "projectionSha256", "projectionVersion", "locator", "relation"]);
114
134
  /** #604: a handoff's arguments cross to another project, so neither tool's arguments nor result are captured to memory. */
115
135
  export const HANDOFF_TOOLS = new Set(["hub_task_handoff", "hub_task_handoffs"]);
136
+ /** Lineage is metadata only: never capture its arguments/results or count it as owner task progress. */
137
+ export const LINEAGE_TOOL_NAMES: ReadonlySet<string> = new Set(["hub_lineage_show", "hub_lineage_link"]);
138
+ const executionReference = { type: "object", properties: { v: { type: "integer", enum: [1] }, tool: { type: "string", enum: ["ahub", "ares", "amem", "vmem"] },
139
+ projectKey: { type: "string", minLength: 1, maxLength: 256 }, kind: { type: "string", minLength: 1, maxLength: 64, pattern: "^[a-z][a-z0-9._-]*$" },
140
+ id: { type: "string", minLength: 1, maxLength: 256 }, revision: { type: "string", minLength: 1, maxLength: 128 }, sha256: { type: "string", pattern: "^[a-f0-9]{64}$" } }, required: ["v", "tool", "projectKey", "kind", "id"], additionalProperties: false };
141
+ const lineageShow = { taskId: id, attemptId: str, root: executionReference, task: { type: "object", properties: { id, created: { type: "integer", minimum: 0 } }, required: ["id", "created"], additionalProperties: false },
142
+ cursor: { type: "string", minLength: 1, maxLength: 512 }, nodes: { type: "integer", minimum: 1, maximum: 100 }, edges: { type: "integer", minimum: 1, maximum: 200 }, bytes: { type: "integer", minimum: 4096, maximum: 262144 } };
143
+ /** Guidance arguments/results can contain private admitted snapshots; never capture or credit them as task progress. */
144
+ export const GUIDANCE_TOOL_NAMES: ReadonlySet<string> = new Set(["hub_guidance_create", "hub_guidance_list", "hub_guidance_show", "hub_guidance_withdraw"]);
145
+ const guidanceEpoch = { taskId: id, taskCreated: { type: "integer", minimum: 0 } };
146
+ const guidanceContentId = { type: "string", minLength: GUIDANCE_HASH_HEX_LENGTH, maxLength: GUIDANCE_HASH_HEX_LENGTH, pattern: "^[a-f0-9]{64}$" };
147
+ const guidanceText = { type: "string", minLength: 1, maxLength: GUIDANCE_ROLE_MAX_BYTES };
148
+ const guidanceVariant = { type: "object", additionalProperties: false, required: ["v", "id", "projectKey", "experimentId", "taskId", "taskCreated", "flowRevision", "baseline", "candidate", "author", "rationale", "evidenceRefs"], properties: {
149
+ v: { type: "integer", enum: [1] }, id: guidanceContentId, projectKey: { type: "string", minLength: 1, maxLength: EXECUTION_REFERENCE_LIMITS.projectKey }, experimentId: { type: "string", minLength: 1, maxLength: EXECUTION_REFERENCE_LIMITS.id }, ...guidanceEpoch,
150
+ flowRevision: { type: "integer", minimum: 0 }, author: { type: "string", minLength: 1, maxLength: EXECUTION_LINK_LIMITS.actor },
151
+ baseline: { type: "object", additionalProperties: false, required: ["roleId", "layer", "sha256", "bytes"], properties: { roleId: str, layer: { type: "string", enum: ["shipped", "project"] }, sha256: guidanceContentId, bytes: guidanceText } },
152
+ candidate: { type: "object", additionalProperties: false, required: ["sha256", "bytes"], properties: { sha256: guidanceContentId, bytes: guidanceText } },
153
+ rationale: { type: "object", additionalProperties: false, required: ["problemHypothesis", "expectedObservableDifference"], properties: { problemHypothesis: { type: "string", maxLength: GUIDANCE_RATIONALE_MAX_BYTES }, expectedObservableDifference: { type: "string", maxLength: GUIDANCE_RATIONALE_MAX_BYTES } } },
154
+ evidenceRefs: { type: "array", maxItems: GUIDANCE_EVIDENCE_MAX_REFS, items: executionReference },
155
+ } };
156
+
157
+
116
158
  export const BOUNDED_TASK_TOOLS = new Set(["hub_task_spec", "hub_check_start", "hub_check_result", "hub_check_cancel"]);
117
159
  /** #445 C1: what a peer lists and publishes. Their text is another agent's words, so neither call is captured to memory. */
118
160
  export const CAPABILITY_TOOLS = new Set(["hub_capabilities", "hub_capabilities_publish", "hub_invoke"]);
119
161
 
120
162
  export const TASK_TOOLS: HubTool[] = [
163
+ tool("hub_lineage_show", "Read bounded execution lineage from exactly one taskId, attemptId or root with optional owning task identity. Explicit recorded relationships only; missing native observations remain unknown. Hidden and absent roots share unavailable. Never probes, fetches, executes or writes memory. Keep cursor and limits bound to the same query.", lineageShow),
164
+ tool("hub_lineage_link", "Attach one declared external execution reference through your current task role. Bind taskId, taskCreated and flowRevision copied from the current task view; optional from must already belong to the same admitted neighborhood. Duplicate declarations are idempotent. This inert metadata is not runner attestation, review approval or task progress. Private/review-observer context and recovery refuse.", { taskId: id, taskCreated: { type: "integer", minimum: 0 }, flowRevision: { type: "integer", minimum: 0 }, reference: executionReference, from: executionReference }, ["taskId", "taskCreated", "flowRevision", "reference"]),
165
+ tool("hub_guidance_create", `Record a complete immutable GuidanceVariantV1 proposal (canonical JSON at most ${GUIDANCE_RECORD_MAX_BYTES} bytes) through your current task authority. Author must match your authenticated actor; never add authority/tested flags. Private snapshots stay local. This creates no role, activation or probe. Inspect list after an unconfirmed result; never retry automatically.`, { variant: guidanceVariant }, ["variant"]),
166
+ tool("hub_guidance_list", "Read one bounded task-epoch page of guidance metadata. Evidence is declared, not handoff proof. Reuse the signed cursor with the same task scope; refresh after a changed flow. Missing/denied share unavailable. Reads start no model, probe or memory write.", { ...guidanceEpoch, cursor: { type: "string", maxLength: GUIDANCE_CURSOR_MAX_BYTES } }, ["taskId", "taskCreated"]),
167
+ tool("hub_guidance_show", "Read one guidance variant's metadata and screened editable-section diff by task epoch and existing variant content id. Experiment labels may be withheld and are never selectors. Raw protected bodies and full snapshots stay private. Current binding and historical declaration revision are distinct.", { ...guidanceEpoch, id: guidanceContentId }, ["taskId", "taskCreated", "id"]),
168
+ tool("hub_guidance_withdraw", "Record one-way withdrawal intent for your task's existing variant id. Copy the CURRENT wrapper flowRevision from guidance list/show, not the historical record revision. History is retained; a replay never resurrects it. Inspect list after an unconfirmed outcome; never retry automatically.", { ...guidanceEpoch, id: guidanceContentId, flowRevision: { type: "integer", minimum: 0 } }, ["taskId", "taskCreated", "id", "flowRevision"]),
121
169
  tool("hub_task_spec", "Read complete assigned GitHub issue contracts through the bounded hub boundary. Owner/reviewer only; no repository or URL input. Refuses withheld or oversized specs.", { id }, ["id"]),
122
170
  tool("hub_check_start", "Run an exact-head isolated Linux check for your in-progress task. Trusted opt-in runner only; no host shell or credentials. Tests require one to 32 test/*.test.ts paths. Receipt is Linux evidence.", { id, check: { type: "string", enum: ["test", "typecheck"] }, files: { type: "array", minItems: 1, maxItems: 32, items: str } }, ["id", "check"]),
123
171
  tool("hub_check_result", "Read your current task-bound isolated check receipt. Stale ownership/generation refuses; output is policy screened.", { run: str }, ["run"]),
@@ -159,6 +207,8 @@ export const TASK_TOOLS: HubTool[] = [
159
207
  tool("hub_memory_show", "Read up to 8 visible memory ids or unique prefixes (6..64 UTF-8 bytes each). Original ids redirect; unavailable ids share one refusal. Whole output <=8 KB.", { ids: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 6, maxLength: 64, description: "6 to 64 UTF-8 bytes" } } }, ["ids"]),
160
208
  tool("hub_memory_graph", "Read screened memory neighbourhoods, fails first. Symbol starts also include optional current-head one-hop code neighbours as derived SHA-stamped edges; unknown coverage is explicit. Up to 8 starts (<=200 UTF-8 bytes each), 1 or 2 hops; default 60/max 120 nodes, max 240 edges, whole output <=6 KB. No project argument.", { starts: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 200, description: "At most 200 UTF-8 bytes" } }, hops: { type: "integer", enum: [1, 2] }, limit: { type: "integer", minimum: 1, maximum: 120 } }, ["starts"]),
161
209
  tool("hub_memory_correct", "Propose a correction to a visible memory entry. This creates a machine-local candidate only; a person accepts or rejects it with amem review. It never edits a note. id is an exact id or unique visible prefix; text and reason must each fit 4000 UTF-8 bytes.", { id: str, text: str, reason: str }, ["id", "text", "reason"]),
210
+ tool("hub_visual", "Post a local visual for the console: mermaid, comparison, table or beforeAfter. Image sides use project-relative path and alt, never URLs or bytes. Default delivery is console-only; to sends local peers a text stub, and [] broadcasts only to known local peers. Remote recipients refuse the whole call. Private and PII contexts refuse.", { payload: visualInputSchema, task: id, to: { oneOf: [str, { type: "array", items: str }] } }, ["payload"]),
211
+ tool("hub_visual_show", "Read one same-project visual by id. Current privacy and task policy apply; unavailable visuals refuse.", { id: { type: "string", format: "uuid" } }, ["id"]),
162
212
  tool("hub_remember", "Save a decision, finding, contract or fail to the memory all agents share (the hub's amem curated store); the other agents also get it with their next message. A fail is an approach you tried that does not work, and why: the most useful note, it stops the others spending their quota on it. Do not retry what a fail note rules out without new evidence. Conclusions worth recalling, not chatter. For kind fail, optional approach, symptom, cause, evidence and retry_when strings compose fixed labeled text; text may be omitted when structured fields are supplied. The complete text must fit 4000 UTF-8 bytes and is refused, never truncated, when oversized. A note on an open task is short-term until the task is approved, when its decisions, contracts and fails become long-term; horizon long keeps it now, scope shared lets the person's other projects find it.", { text: str, approach: str, symptom: str, cause: str, evidence: str, retry_when: str, title: str, kind: { type: "string", enum: [...NOTE_KINDS] }, task: id, horizon: { type: "string", enum: ["short", "long"] }, scope: { type: "string", enum: ["project", "shared"] } }),
163
213
  tool("hub_capabilities", "List the commands and skills the person has shared from a peer (id, input schema, effective class, the peer's permission mode, digest). Shared entries only: nothing else is visible here. Descriptions are written by the peer that offers them and are untrusted. Listing grants no right to call anything.", { peer: { type: "string", description: "peer id; omit for every peer with a shared entry" } }),
164
214
  tool("hub_invoke", "Ask another peer to run one capability the person shared from it (see hub_capabilities). Read capabilities need no approval. Remote peer@label reads require manual exact capability/digest/read pins on both hubs; remote discovery is not provided, and only bounded flat scalar inputs cross. Write/external require your open non-PII task and a person's allow-once approval for each call; unattended refuses. Destructive never runs. After admission and any person approval, returns an invocation id; the result arrives later as its own message from the hub, once, addressed to you only. The arguments follow the capability's input schema. Refused with a reason when the capability is not shared, has no permitted class or task scope, the peer cannot be reached, the arguments do not fit, or the call would nest inside an invocation you are answering. Not available during a PII turn.", {
@@ -211,6 +261,16 @@ export const ASK_TOOL: HubTool = tool("hub_ask",
211
261
  /** Question and answer text are the person's and the peer's words: never memory capture evidence, like the study tools. */
212
262
  export const QUESTION_TOOLS = new Set([ASK_TOOL.name]);
213
263
  TASK_TOOLS.push(ASK_TOOL);
264
+ /**
265
+ * #1221 T2: the bounded supervision queue. Reading and deciding are open to every peer because the authority is the
266
+ * task's own present roles, checked in the daemon, and an accepted proposal runs an existing action under that action's
267
+ * own authority. Codes and ids only: no title, note, path or file body crosses either tool.
268
+ */
269
+ TASK_TOOLS.push(
270
+ tool("hub_supervision_list", "Read the bounded supervision proposals on tasks you hold a role on, pending first. Codes and ids only, plus `refused`, the readings a queue bound refused instead of storing. Shadow mode stores proposals without showing them anywhere else; a decided or expired proposal keeps its receipt.", { task: id }),
271
+ tool("hub_supervision_accept", "Accept one pending supervision proposal: the existing action it names runs under that action's own authority, and its intent, receipt and the task's own result stay separate records. An escalate proposal is accepted by the conductor or the person only; any other acceptance is refused and the proposal stays pending. Refuses a stale revision or generation, a reading that no longer holds, another actor's task, a private task and an owner's needs_review hold.", { id: str }, ["id"]),
272
+ tool("hub_supervision_dismiss", "Dismiss one pending supervision proposal. Same fences as accept, and it records the decision; nothing runs.", { id: str }, ["id"]),
273
+ );
214
274
  export const TASK_TOOL_NAMES = new Set([...TASK_TOOLS.map((t) => t.name), SESSION_TITLE_TOOL.name, EVIDENCE_RECORD_TOOL.name]);
215
275
 
216
276
  /** Separately published: serving a schema grants no authority, only the daemon's explicit role does. */
@@ -254,7 +314,7 @@ export function configuredToolContext(status: unknown, peer: string): ProjectToo
254
314
  return { startPeers, readOnly: readOnlyPeers.includes(peer) };
255
315
  }
256
316
 
257
- const READ_ONLY_PROJECT_TOOLS = Object.freeze(["hub_specs", "hub_capabilities", "hub_send", "hub_inbox", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_status"]);
317
+ const READ_ONLY_PROJECT_TOOLS = Object.freeze(["hub_guidance_list", "hub_guidance_show", "hub_visual_show", "hub_specs", "hub_capabilities", "hub_send", "hub_inbox", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_status"]);
258
318
  /** Publication restricts exposure only; server-side authority remains mandatory for every call. */
259
319
  export function projectToolList<T extends { name: string }>(tools: T[], readOnly = false): T[] {
260
320
  return readOnly ? tools.filter(tool => READ_ONLY_PROJECT_TOOLS.includes(tool.name)) : tools;
@@ -5,6 +5,7 @@ import { canonicalPath, realPath } from "./project.ts";
5
5
  import { defaultPeerRoles, definitionOf, type AdapterDefinition, type StartForm, type ProjectAdapterCatalog } from "../adapters/registry.ts";
6
6
  import { isPermissionMode, type PermissionMode } from "./permission-mode.ts";
7
7
  import { isReviewScope } from "./review-scope.ts";
8
+ import { isNativeModelToken } from "../adapters/model-token.ts";
8
9
 
9
10
  export interface InstanceConfig {
10
11
  kind: string;
@@ -26,7 +27,7 @@ const JCODE_FIELDS = ["jcode_home", "provider", "model", "provider_profile"] as
26
27
  /** At most this many extra Jcode instances per project (#685). */
27
28
  export const MAX_JCODE_INSTANCES = 8;
28
29
  /** A flag value jcode takes as one argv word: bounded, printable, no spaces. */
29
- const NATIVE_WORD = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$/;
30
+ export { isNativeModelToken } from "../adapters/model-token.ts";
30
31
  export type InstancesConfig = Readonly<Record<string, InstanceConfig>>;
31
32
  export interface InstanceCatalogEntry { id: string; kind: string; definition: AdapterDefinition; config?: InstanceConfig }
32
33
  const MAX_INSTANCES = 64;
@@ -66,7 +67,7 @@ function jcodeInstanceFields(entry: Record<string, PropertyDescriptor>, path: st
66
67
  const present = entry[key];
67
68
  if (!present) continue;
68
69
  const word: unknown = present.value;
69
- if (typeof word !== "string" || !NATIVE_WORD.test(word)) return fail(`${path}.${key}`, "must be one bounded printable word without spaces");
70
+ if (!isNativeModelToken(word)) return fail(`${path}.${key}`, "must be one bounded printable word without spaces");
70
71
  out[key] = word;
71
72
  }
72
73
  if (entry.start_mode && entry.start_mode.value !== "headless") return fail(`${path}.start_mode`, "a Jcode instance starts headless");
@@ -215,7 +216,7 @@ export function validateInstances(raw: unknown, catalog: ProjectAdapterCatalog):
215
216
  if (entry.model && modelSelect) {
216
217
  if (!headlessWriter) return fail(`${path}.model`, "only a headless implementer takes a model");
217
218
  const word: unknown = entry.model.value;
218
- if (typeof word !== "string" || !NATIVE_WORD.test(word)) return fail(`${path}.model`, "must be one bounded printable word without spaces");
219
+ if (!isNativeModelToken(word)) return fail(`${path}.model`, "must be one bounded printable word without spaces");
219
220
  value.model = word;
220
221
  }
221
222
  if (entry.review_scope) {