@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
@@ -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_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"]);
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",
@@ -130,11 +133,39 @@ export const EVIDENCE_RECORD_TOOL = tool("hub_evidence_record", "Record a proven
130
133
  }, ["taskId", "claimId", "claimRevision", "sourceId", "rawSha256", "projectionSha256", "projectionVersion", "locator", "relation"]);
131
134
  /** #604: a handoff's arguments cross to another project, so neither tool's arguments nor result are captured to memory. */
132
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
+
133
158
  export const BOUNDED_TASK_TOOLS = new Set(["hub_task_spec", "hub_check_start", "hub_check_result", "hub_check_cancel"]);
134
159
  /** #445 C1: what a peer lists and publishes. Their text is another agent's words, so neither call is captured to memory. */
135
160
  export const CAPABILITY_TOOLS = new Set(["hub_capabilities", "hub_capabilities_publish", "hub_invoke"]);
136
161
 
137
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"]),
138
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"]),
139
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"]),
140
171
  tool("hub_check_result", "Read your current task-bound isolated check receipt. Stale ownership/generation refuses; output is policy screened.", { run: str }, ["run"]),
@@ -230,6 +261,16 @@ export const ASK_TOOL: HubTool = tool("hub_ask",
230
261
  /** Question and answer text are the person's and the peer's words: never memory capture evidence, like the study tools. */
231
262
  export const QUESTION_TOOLS = new Set([ASK_TOOL.name]);
232
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
+ );
233
274
  export const TASK_TOOL_NAMES = new Set([...TASK_TOOLS.map((t) => t.name), SESSION_TITLE_TOOL.name, EVIDENCE_RECORD_TOOL.name]);
234
275
 
235
276
  /** Separately published: serving a schema grants no authority, only the daemon's explicit role does. */
@@ -273,7 +314,7 @@ export function configuredToolContext(status: unknown, peer: string): ProjectToo
273
314
  return { startPeers, readOnly: readOnlyPeers.includes(peer) };
274
315
  }
275
316
 
276
- const READ_ONLY_PROJECT_TOOLS = Object.freeze(["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"]);
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"]);
277
318
  /** Publication restricts exposure only; server-side authority remains mandatory for every call. */
278
319
  export function projectToolList<T extends { name: string }>(tools: T[], readOnly = false): T[] {
279
320
  return readOnly ? tools.filter(tool => READ_ONLY_PROJECT_TOOLS.includes(tool.name)) : tools;
@@ -3,8 +3,10 @@ import type { MlxHandle } from "../models/mlx.ts";
3
3
  import type { ChatMessage, OmniRoute } from "../omniroute/client.ts";
4
4
  import { CLASSES, type TaskClass } from "./board.ts";
5
5
  import { DIGEST, newEnvelope, type Envelope } from "./envelope.ts";
6
- import { buildEscalationJudgeRequest, parseEscalationVerdict, type EscalationVerdict } from "../models/route/escalation.ts";
7
- import type { Conversation } from "../models/route/normalize.ts";
6
+ import { buildEscalationRequest } from "../models/route/hub-prompts.ts";
7
+ import { captureJudgeConversation } from "../models/route/conversation-view.ts";
8
+ import { parseEscalationReply, type EscalationReply } from "../models/route/judge-replies.ts";
9
+ import type { ProgressConversation } from "./progress.ts";
8
10
 
9
11
  export interface InferenceConfig {
10
12
  enabled: boolean;
@@ -148,8 +150,19 @@ export class Inference {
148
150
  }
149
151
 
150
152
  /** A closed escalation verdict, or no verdict when inference is unavailable or malformed. */
151
- async escalate(conversation: Conversation, turn: number): Promise<EscalationVerdict | undefined> {
152
- const request = buildEscalationJudgeRequest(conversation, turn);
153
+ async escalate(conversation: ProgressConversation, turn: number): Promise<EscalationReply | undefined> {
154
+ // This grouped shape is produced by ProgressObserver, not accepted from native model JSON.
155
+ const messages: ChatMessage[] = conversation.instructions.map(content => ({ role: "system", content }));
156
+ for (const frame of conversation.messages) {
157
+ messages.push({ role: frame.role, content: frame.content, ...(frame.toolCalls.length ? {
158
+ tool_calls: frame.toolCalls.map(call => ({ id: call.id, type: "function" as const,
159
+ function: { name: call.name, arguments: JSON.stringify(call.arguments) } })),
160
+ } : {}) });
161
+ for (const result of frame.toolResults) messages.push({ role: "tool", tool_call_id: result.toolCallId,
162
+ content: result.content, ...(result.isError === undefined ? {} : { is_error: result.isError }) });
163
+ }
164
+ const request = buildEscalationRequest(captureJudgeConversation(messages), turn);
165
+ if (!request) return undefined;
153
166
  const user = request.messages[0]?.content;
154
167
  if (!user) return undefined;
155
168
  const answer = await this.complete(
@@ -162,7 +175,7 @@ export class Inference {
162
175
  "new_evidence (boolean, true only for fresh distinct observations) and reason (short string). Return escalate false and category none when evidence is insufficient.",
163
176
  user, request.maxOutputTokens,
164
177
  );
165
- return answer ? parseEscalationVerdict(answer) : undefined;
178
+ return answer ? parseEscalationReply(answer) : undefined;
166
179
  }
167
180
  }
168
181
 
@@ -1,3 +1,4 @@
1
+ import { parseGuidanceListQuery, parseGuidanceIdQuery, parseGuidancePageResult, parseGuidanceDiffResult } from "./guidance-variants.ts";
1
2
  import type { ActionMeta, InboxAnswers } from "@staix/agent-console/contract";
2
3
  import { assertExecutableRuntimeRoot } from "./project-runtime-state.ts";
3
4
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS } from "./planning.ts";
@@ -132,7 +133,7 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
132
133
  // #1057: the worktree shelf's person actions. The refresh is the one that reads GitHub, so it gets the delivery reads' deadline in its own branch below.
133
134
  const worktreeAction = ["worktree_override_set", "worktree_override_clear", "worktrees_refresh_prs"].includes(String(input.action));
134
135
  // The settings actions (#269) reach the project hub as an ordinary session's: this dashboard opens no settings session.
135
- if (!["snapshot", "send", "pause", "resume", "permit", "propose", "intake", "assign", "backlog_pull", "backlog_return", "planning", "planning_undo", "planner_pull", "backlog_split", "release_new", "release_change", "setting", "setting_undo", "setting_preview", "setting_reload", "model_preview", "model_confirm", "config_edit_preview", "config_edit_apply", "start_peer", "sdlc_queue", "sdlc_release", "result_seen", "results_read_all", "results_unread_last"].includes(String(input.action)) && !worktreeAction) return { ok: false, error: "invalid dashboard action" };
136
+ if (!["snapshot", "send", "pause", "resume", "permit", "supervision", "propose", "intake", "assign", "backlog_pull", "backlog_return", "planning", "planning_undo", "planner_pull", "backlog_split", "release_new", "release_change", "setting", "setting_undo", "setting_preview", "setting_reload", "model_preview", "model_confirm", "config_edit_preview", "config_edit_apply", "start_peer", "sdlc_queue", "sdlc_release", "result_seen", "results_read_all", "results_unread_last"].includes(String(input.action)) && !worktreeAction) return { ok: false, error: "invalid dashboard action" };
136
137
  const visualSelector = input.action === "snapshot" ? visualSnapshotSelector(input) : {};
137
138
  client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: input.instanceId });
138
139
  const deliveryRead = input.action === "sdlc_queue" || input.action === "sdlc_release";
@@ -215,7 +216,48 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
215
216
  } catch { return { ok: false, unconfirmed: true as const, text: "Review result is unconfirmed. Refresh and check the task before retrying.", error: "Review result is unconfirmed. Refresh and check the task before retrying." }; }
216
217
  finally { client?.close(); }
217
218
  };
218
- return { list, act, answer, receipt, consoleControl };
219
+ // #1220 T3: the acon provider's execution-lineage read. A port of its own like `answer`, never an `act` action: the
220
+ // dashboard's action list does not grow, so nothing here can link, probe, replay or execute. It sends the control
221
+ // message the console role already owns, answered in-stack by the same Tasks projection the CLI and MCP read.
222
+ const lineageQueryKeys = ["taskId", "attemptId", "root", "task", "cursor", "nodes", "edges", "bytes"] as const;
223
+ const lineage = async (target: { projectId: unknown; instanceId: unknown }, query: Record<string, unknown>) => {
224
+ if (options.stopping?.()) return { ok: false, error: "manager is stopping" };
225
+ const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined;
226
+ if (!project) return { ok: false, error: "unknown project" };
227
+ if (typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "expected daemon instance is required" };
228
+ // The hub parses a closed query: an unknown field would refuse every read, so name it here instead.
229
+ if (!query || typeof query !== "object" || Array.isArray(query) || Object.keys(query).some(key => !(lineageQueryKeys as readonly string[]).includes(key))) return { ok: false, error: "invalid lineage query" };
230
+ let client: ControlClient | undefined;
231
+ try {
232
+ client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId });
233
+ const timeoutMs = options.forwardTimeoutMs?.("lineage_show", 10_000) ?? 10_000;
234
+ const result = await client.request({ t: "lineage_show", ...query }, timeoutMs);
235
+ // A read has no effect to confirm: a missed deadline is a read that did not happen.
236
+ if (result.ok === false && result.error === `no answer from the hub within ${Math.round(timeoutMs / 1000)} s`) return { ok: false, error: "the hub did not answer the lineage read in time; refresh and retry" };
237
+ const { rid: _transportId, ...reply } = result;
238
+ return reply;
239
+ } catch (error) { return { ok: false, error: safeError(error) }; }
240
+ finally { client?.close(); }
241
+ };
242
+ /** Producer-only read port; never forwards an action, actor or person-metadata claim. */
243
+ const guidance = async (target: { projectId: unknown; instanceId: unknown }, op: "list" | "show", input: unknown) => {
244
+ if (options.stopping?.()) return { ok: false, error: "guidance read is unavailable while the manager stops; reconnect before retrying" };
245
+ if (op !== "list" && op !== "show") return { ok: false, error: "guidance console is read-only; use the authorized CLI/MCP for mutations" };
246
+ const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined;
247
+ if (!project || typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "select a running project and current instance before reading guidance" };
248
+ let query; try { query = op === "list" ? parseGuidanceListQuery(input) : parseGuidanceIdQuery(input); }
249
+ catch { return { ok: false, error: "invalid guidance query; select the task epoch and existing variant id or cursor" }; }
250
+ let client: ControlClient | undefined;
251
+ try {
252
+ client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId });
253
+ if (!client.features.includes("guidance_views")) return { ok: false, error: "running hub lacks guidance_views; upgrade and restart the hub before reading guidance" };
254
+ const result = await client.request({ t: op === "list" ? "guidance_list" : "guidance_show", ...query }, options.forwardTimeoutMs?.(`guidance_${op}`, 10_000) ?? 10_000);
255
+ if (result.ok !== true) return { ok: false, error: "guidance read is unavailable; refresh the task scope and current daemon before retrying" };
256
+ return { ok: true, guidance: op === "list" ? parseGuidancePageResult(result.guidance, query) : parseGuidanceDiffResult(result.guidance, query) };
257
+ } catch { return { ok: false, error: "guidance read is unavailable; refresh the task scope or upgrade the hub before retrying" }; }
258
+ finally { client?.close(); }
259
+ };
260
+ return { list, act, answer, receipt, consoleControl, lineage, guidance };
219
261
  }
220
262
 
221
263
  export async function startManager(options: ManagerOptions = {}): Promise<ManagerHandle> {